repo_name
stringlengths
1
62
dataset
stringclasses
1 value
lang
stringclasses
11 values
pr_id
int64
1
20.1k
owner
stringlengths
2
34
reviewer
stringlengths
2
39
diff_hunk
stringlengths
15
262k
code_review_comment
stringlengths
1
99.6k
promptfoo
github_2023
others
3,326
promptfoo
ellipsis-dev[bot]
@@ -0,0 +1,34 @@ +--- +description: Guidelines for Python development +globs: '**/*.py' +alwaysApply: false +--- + +# Python Development Guidelines + +Files: "\*_/_.py"
The file glob pattern `*_/*.py` appears unclear; consider revising it to a standard pattern. ```suggestion Files: "**/*.py" ```
promptfoo
github_2023
others
3,326
promptfoo
ellipsis-dev[bot]
@@ -0,0 +1,94 @@ +--- +description: Guidelines for writing Jest tests for core functionality +globs: 'test/**/*.test.ts,test/**/*.spec.ts' +alwaysApply: false +--- + +# Jest Testing Guidelines + +Files: "test/**/\*.test.ts,test/**/\*.spec.ts"
Typographical note: In line 9, the file glob pattern is written as `test/**/\*.test.ts,test/**/\*.spec.ts` which includes extraneous backslashes before the asterisks. To be consistent with the globs on line 3, consider removing the backslashes unless they are intentionally required for display purposes. ```suggestion Files: "test/**/*.test.ts,test/**/*.spec.ts" ```
promptfoo
github_2023
others
3,326
promptfoo
ellipsis-dev[bot]
@@ -0,0 +1,34 @@ +--- +description: Guidelines for Python development +globs: '**/*.py' +alwaysApply: false +--- + +# Python Development Guidelines + +Files: "\*_/_.py" + +This rule provides guidance for Python development in the promptfoo project. + +## Python Guidelines + +- Use Python 3.9 or later +- Follow the [Google Python Style Guide](mdc:https:/google.github.io/styleguide/pyguide.html)
Typo: The URL in the link is written as `mdc:https:/google.github.io/styleguide/pyguide.html` but it should include two slashes after `https:` (i.e., `mdc:https://google.github.io/styleguide/pyguide.html`). ```suggestion - Follow the [Google Python Style Guide](mdc:https://google.github.io/styleguide/pyguide.html) ```
promptfoo
github_2023
typescript
3,325
promptfoo
ellipsis-dev[bot]
@@ -32,11 +33,81 @@ const YamlEditorComponent: React.FC<YamlEditorProps> = ({ }) => { const darkMode = useTheme().palette.mode === 'dark'; const [code, setCode] = React.useState(''); - const [isReadOnly, setIsReadOnly] = React.useState(readOnly); - const [showCopySuccess, setShowCopySuccess] = React.useState(false); + // Always start in read-only mode on initial load, but respect the readOnly prop + const [isReadOnly, setIsReadOnly] = React.useState(true); + const [parseError, setParseError] = React.useState<string | null>(null); - const toggleReadOnly = () => { - setIsReadOnly(!isReadOnly); + const [notification, setNotification] = React.useState<{ + show: boolean; + message: string; + }>({ show: false, message: '' }); + + const { getTestSuite } = useStore(); + + const parseAndUpdateStore = (yamlContent: string) => {
This duplicates the store update logic in `setStateFromConfig`. Consider using that function after YAML parsing instead of reimplementing the field mapping. - function setStateFromConfig ([evalConfig.ts](https://github.com/promptfoo/promptfoo/blob/888390d069ab391c307ac27f9e990d05ebcbd351/src/app/src/stores/evalConfig.ts#L57-L90))
promptfoo
github_2023
typescript
3,323
promptfoo
ellipsis-dev[bot]
@@ -0,0 +1,103 @@ +import { spawn } from 'child_process'; +import { exec } from 'child_process'; +import type { Command } from 'commander'; +import { promisify } from 'util'; +import logger from '../logger'; + +const execAsync = promisify(exec); + +async function checkModelAuditInstalled(): Promise<boolean> { + try { + await execAsync('python -c "import modelaudit"'); + return true; + } catch { + return false; + } +} + +export function modelScanCommand(program: Command): void { + program + .command('scan-model') + .description('Scan ML models for security vulnerabilities') + .argument('[paths...]', 'Paths to model files or directories to scan') + .option( + '-b, --blacklist <pattern>', + 'Additional blacklist patterns to check against model names', + (val: string, acc: string[]) => [...acc, val], + [] as string[], + ) + .option('-f, --format <format>', 'Output format (text or json)', 'text') + .option('-o, --output <path>', 'Output file path (prints to stdout if not specified)') + .option('-t, --timeout <seconds>', 'Scan timeout in seconds', '300') + .option('-v, --verbose', 'Enable verbose output') + .option('--max-file-size <bytes>', 'Maximum file size to scan in bytes') + .action(async (paths: string[], options) => { + if (!paths || paths.length === 0) { + logger.error( + 'No paths specified. Please provide at least one model file or directory to scan.', + ); + process.exit(1); + } + + // Check if modelaudit is installed + const isModelAuditInstalled = await checkModelAuditInstalled(); + if (!isModelAuditInstalled) { + logger.error('ModelAudit is not installed.'); + logger.info('Please install it using: pip install modelaudit'); + logger.info('For more information, visit: https://www.promptfoo.dev/docs/model-audit/'); + process.exit(1); + } + + const args = ['modelaudit']; + + // Add all paths + args.push(...paths); + + // Add options + if (options.blacklist && options.blacklist.length > 0) { + options.blacklist.forEach((pattern: string) => { + args.push('--blacklist', pattern); + }); + } + + if (options.format) { + args.push('--format', options.format); + } + + if (options.output) { + args.push('--output', options.output); + } + + if (options.timeout) { + args.push('--timeout', options.timeout); + } + + if (options.verbose) { + args.push('--verbose'); + } + + if (options.maxFileSize) { + args.push('--max-file-size', options.maxFileSize); + } + + logger.info(`Running model scan on: ${paths.join(', ')}`); + + const modelAudit = spawn('python', args, { stdio: 'inherit' });
Consider using the '-m' flag when invoking modelaudit. In `checkModelAuditInstalled`, it uses `python -c "import modelaudit"`, but here it's spawned as `python modelaudit ...`. Using `python -m modelaudit` would be more consistent. ```suggestion const modelAudit = spawn('python', ['-m', ...args], { stdio: 'inherit' }); ```
promptfoo
github_2023
typescript
3,323
promptfoo
ellipsis-dev[bot]
@@ -0,0 +1,103 @@ +import { spawn } from 'child_process'; +import { exec } from 'child_process'; +import type { Command } from 'commander'; +import { promisify } from 'util'; +import logger from '../logger'; + +const execAsync = promisify(exec); + +async function checkModelAuditInstalled(): Promise<boolean> { + try { + await execAsync('python -c "import modelaudit"'); + return true; + } catch { + return false; + } +} + +export function modelScanCommand(program: Command): void { + program + .command('scan-model') + .description('Scan ML models for security vulnerabilities') + .argument('[paths...]', 'Paths to model files or directories to scan') + .option( + '-b, --blacklist <pattern>', + 'Additional blacklist patterns to check against model names', + (val: string, acc: string[]) => [...acc, val], + [] as string[], + ) + .option('-f, --format <format>', 'Output format (text or json)', 'text') + .option('-o, --output <path>', 'Output file path (prints to stdout if not specified)') + .option('-t, --timeout <seconds>', 'Scan timeout in seconds', '300')
Consider adding parsers for numeric options (e.g. timeout and max-file-size) to validate and convert input to numbers. ```suggestion .option('-t, --timeout <seconds>', 'Scan timeout in seconds', parseInt, 300) ```
promptfoo
github_2023
typescript
3,323
promptfoo
mldangelo
@@ -60,11 +61,12 @@ async function main() { deleteCommand(program); exportCommand(program); feedbackCommand(program); - const generateCommand = program.command('generate').description('Generate synthetic data');
just an fyi - this changes the help text display alphabetic order
promptfoo
github_2023
typescript
3,323
promptfoo
ellipsis-dev[bot]
@@ -0,0 +1,103 @@ +import { spawn } from 'child_process'; +import { exec } from 'child_process'; +import type { Command } from 'commander'; +import { promisify } from 'util'; +import logger from '../logger'; + +const execAsync = promisify(exec); + +async function checkModelAuditInstalled(): Promise<boolean> { + try { + await execAsync('python -c "import modelaudit"'); + return true; + } catch { + return false; + } +} + +export function modelScanCommand(program: Command): void { + program + .command('scan-model') + .description('Scan ML models for security vulnerabilities') + .argument('[paths...]', 'Paths to model files or directories to scan') + .option( + '-b, --blacklist <pattern>', + 'Additional blacklist patterns to check against model names', + (val: string, acc: string[]) => [...acc, val], + [] as string[], + ) + .option('-f, --format <format>', 'Output format (text or json)', 'text') + .option('-o, --output <path>', 'Output file path (prints to stdout if not specified)') + .option('-t, --timeout <seconds>', 'Scan timeout in seconds', parseInt, 300) + .option('-v, --verbose', 'Enable verbose output') + .option('--max-file-size <bytes>', 'Maximum file size to scan in bytes') + .action(async (paths: string[], options) => { + if (!paths || paths.length === 0) { + logger.error( + 'No paths specified. Please provide at least one model file or directory to scan.', + ); + process.exit(1); + } + + // Check if modelaudit is installed + const isModelAuditInstalled = await checkModelAuditInstalled(); + if (!isModelAuditInstalled) { + logger.error('ModelAudit is not installed.'); + logger.info(`Please install it using: ${chalk.green('pip install modelaudit')}`);
Missing import: 'chalk' is used but not imported.
promptfoo
github_2023
typescript
3,323
promptfoo
ellipsis-dev[bot]
@@ -0,0 +1,104 @@ +import chalk from 'chalk'; +import { spawn } from 'child_process'; +import { exec } from 'child_process'; +import type { Command } from 'commander'; +import { promisify } from 'util'; +import logger from '../logger'; + +const execAsync = promisify(exec); + +async function checkModelAuditInstalled(): Promise<boolean> { + try { + await execAsync('python -c "import modelaudit"'); + return true; + } catch { + return false; + } +} + +export function modelScanCommand(program: Command): void { + program + .command('scan-model') + .description('Scan ML models for security vulnerabilities') + .argument('[paths...]', 'Paths to model files or directories to scan') + .option( + '-b, --blacklist <pattern>', + 'Additional blacklist patterns to check against model names', + (val: string, acc: string[]) => [...acc, val], + [] as string[], + ) + .option('-f, --format <format>', 'Output format (text or json)', 'text') + .option('-o, --output <path>', 'Output file path (prints to stdout if not specified)') + .option('-t, --timeout <seconds>', 'Scan timeout in seconds', Number.parseInt, 300)
Consider wrapping `Number.parseInt` with an explicit radix (e.g., `(val) => Number.parseInt(val, 10)`) to ensure consistent number parsing. ```suggestion .option('-t, --timeout <seconds>', 'Scan timeout in seconds', (val) => Number.parseInt(val, 10), 300) ```
promptfoo
github_2023
typescript
3,321
promptfoo
ellipsis-dev[bot]
@@ -223,7 +224,15 @@ export async function startServer( port = DEFAULT_PORT, browserBehavior = BrowserBehavior.ASK, filterDescription?: string, + envPath?: string, ) { + if (envPath) { + logger.info(`Loading environment variables from ${envPath}`); + dotenv.config({ path: envPath });
Consider capturing the result of `dotenv.config` and checking for errors. This can help log issues with loading the env file. ```suggestion const result = dotenv.config({ path: envPath }); if (result.error) { logger.error(`Error loading env file: ${result.error}`); } ```
promptfoo
github_2023
typescript
3,321
promptfoo
ellipsis-dev[bot]
@@ -223,7 +224,15 @@ port = DEFAULT_PORT, browserBehavior = BrowserBehavior.ASK, filterDescription?: string, + envPath?: string, ) { + if (envPath) {
Consider moving `dotenv.config()` to the top so that env vars are loaded before other modules (e.g. constants) are imported. Also, check its return value for errors.
promptfoo
github_2023
others
3,309
promptfoo
ellipsis-dev[bot]
@@ -170,8 +170,9 @@ tests: foo: bar assert: - type: moderation - provider: 'azure:moderation' - config: - blocklistNames: ['my-custom-blocklist', 'industry-terms'] - haltOnBlocklistHit: true + provider: + id: azure:moderation + config: + blocklistNames: []
Consider providing a non-empty example for `blocklistNames` (like the previous one) to illustrate expected usage. ```suggestion blocklistNames: ['exampleBlocklist'] ```
promptfoo
github_2023
typescript
3,292
promptfoo
ellipsis-dev[bot]
@@ -0,0 +1,288 @@ +import { + getCache, + isCacheEnabled, +} from '../../cache'; +import { getEnvString } from '../../envars'; +import logger from '../../logger'; +import type { + ApiModerationProvider, + ModerationFlag, + ProviderModerationResponse, +} from '../../types'; +import type { EnvOverrides } from '../../types/env'; +import { AzureGenericProvider } from '../azure'; +import { REQUEST_TIMEOUT_MS } from '../shared'; + +// Azure Content Safety moderation model +export const AZURE_MODERATION_MODELS = [ + { id: 'text-content-safety', maxTokens: 10000, capabilities: ['text'] }, +]; + +export type AzureModerationModelId = string; + +// Azure moderation categories based on API docs +export type AzureModerationCategory = 'Hate' | 'SelfHarm' | 'Sexual' | 'Violence'; + +// Types for Azure Content Safety API +interface AzureTextCategoriesAnalysis { + category: AzureModerationCategory; + severity: number; +} + +interface AzureTextBlocklistMatch { + blocklistName: string; + blocklistItemId: string; + blocklistItemText: string; +} + +interface AzureAnalyzeTextResult { + categoriesAnalysis?: AzureTextCategoriesAnalysis[]; + blocklistsMatch?: AzureTextBlocklistMatch[]; +} + +export interface AzureModerationConfig { + apiKey?: string; + apiKeyEnvar?: string; + endpoint?: string; + apiVersion?: string; + headers?: Record<string, string>; + passthrough?: Record<string, any>; +} + +function parseAzureModerationResponse(data: AzureAnalyzeTextResult): ProviderModerationResponse { + try { + // Log the response for debugging + logger.debug(`Azure Content Safety API response: ${JSON.stringify(data)}`); + + // Check if the response is in the expected format + if (!data) { + logger.error('Azure Content Safety API returned invalid response: null or undefined'); + return { flags: [] }; + } + + // The API actually returns a property named 'categoriesAnalysis' + // but we'll also check for potential variations in the response format + const categories = data.categoriesAnalysis || (data as any).categoriesAnalysis || (data as any).categories_analysis || []; + const blocklistMatches = data.blocklistsMatch || (data as any).blocklistsMatch || (data as any).blocklists_match || []; + + if (!categories || categories.length === 0) { + return { flags: [] }; + } + + const flags: ModerationFlag[] = []; + + // Convert severity levels to confidence scores (0-1) + // According to docs, severity can be 0, 2, 4, 6 (FourSeverityLevels) or 0-7 (EightSeverityLevels) + // We'll normalize to 0-1 range + for (const analysis of categories) { + // Only add flags for categories with non-zero severity + if (analysis.severity > 0) { + // Convert severity to confidence (0-1 range) + // Maximum severity is 6 in FourSeverityLevels or 7 in EightSeverityLevels + // We'll use 7 as the maximum to normalize + const confidence = analysis.severity / 7;
Normalizing severity by dividing by 7 assumes the maximum severity is fixed. Confirm that this assumption holds across all cases or consider making it configurable.
promptfoo
github_2023
typescript
3,292
promptfoo
ellipsis-dev[bot]
@@ -0,0 +1,288 @@ +import { + getCache, + isCacheEnabled, +} from '../../cache'; +import { getEnvString } from '../../envars'; +import logger from '../../logger'; +import type { + ApiModerationProvider, + ModerationFlag, + ProviderModerationResponse, +} from '../../types'; +import type { EnvOverrides } from '../../types/env'; +import { AzureGenericProvider } from '../azure'; +import { REQUEST_TIMEOUT_MS } from '../shared'; + +// Azure Content Safety moderation model +export const AZURE_MODERATION_MODELS = [ + { id: 'text-content-safety', maxTokens: 10000, capabilities: ['text'] }, +]; + +export type AzureModerationModelId = string; + +// Azure moderation categories based on API docs +export type AzureModerationCategory = 'Hate' | 'SelfHarm' | 'Sexual' | 'Violence'; + +// Types for Azure Content Safety API +interface AzureTextCategoriesAnalysis { + category: AzureModerationCategory; + severity: number; +} + +interface AzureTextBlocklistMatch { + blocklistName: string; + blocklistItemId: string; + blocklistItemText: string; +} + +interface AzureAnalyzeTextResult { + categoriesAnalysis?: AzureTextCategoriesAnalysis[]; + blocklistsMatch?: AzureTextBlocklistMatch[]; +} + +export interface AzureModerationConfig { + apiKey?: string; + apiKeyEnvar?: string; + endpoint?: string; + apiVersion?: string; + headers?: Record<string, string>; + passthrough?: Record<string, any>; +} + +function parseAzureModerationResponse(data: AzureAnalyzeTextResult): ProviderModerationResponse { + try { + // Log the response for debugging + logger.debug(`Azure Content Safety API response: ${JSON.stringify(data)}`); + + // Check if the response is in the expected format + if (!data) { + logger.error('Azure Content Safety API returned invalid response: null or undefined'); + return { flags: [] }; + } + + // The API actually returns a property named 'categoriesAnalysis' + // but we'll also check for potential variations in the response format + const categories = data.categoriesAnalysis || (data as any).categoriesAnalysis || (data as any).categories_analysis || []; + const blocklistMatches = data.blocklistsMatch || (data as any).blocklistsMatch || (data as any).blocklists_match || []; + + if (!categories || categories.length === 0) { + return { flags: [] }; + } + + const flags: ModerationFlag[] = []; + + // Convert severity levels to confidence scores (0-1) + // According to docs, severity can be 0, 2, 4, 6 (FourSeverityLevels) or 0-7 (EightSeverityLevels) + // We'll normalize to 0-1 range + for (const analysis of categories) { + // Only add flags for categories with non-zero severity + if (analysis.severity > 0) { + // Convert severity to confidence (0-1 range) + // Maximum severity is 6 in FourSeverityLevels or 7 in EightSeverityLevels + // We'll use 7 as the maximum to normalize + const confidence = analysis.severity / 7; + + flags.push({ + code: analysis.category.toLowerCase(), + description: `Content flagged for ${analysis.category}`, + confidence, + }); + } + } + + // Add blocklist matches as additional flags + for (const match of blocklistMatches || []) { + flags.push({ + code: `blocklist:${match.blocklistName}`, + description: `Content matched blocklist item: ${match.blocklistItemText}`, + confidence: 1.0, // Blocklist matches are always 100% confidence + }); + } + + return { flags }; + } catch (error) { + logger.error(`Error parsing Azure Content Safety API response: ${error}`); + return { flags: [], error: 'Failed to parse moderation response' }; + } +} + +function handleApiError(err: any, data?: any): ProviderModerationResponse { + logger.error(`Azure moderation API error: ${err}${data ? `, ${data}` : ''}`); + return { error: err.message || 'Unknown error', flags: [] }; +} + +function getModerationCacheKey( + modelName: string, + config: any, + content: string, +): string { + return `azure-moderation:${modelName}:${JSON.stringify(content)}`; +} + +export class AzureModerationProvider + extends AzureGenericProvider + implements ApiModerationProvider +{ + static MODERATION_MODELS = AZURE_MODERATION_MODELS; + static MODERATION_MODEL_IDS = AZURE_MODERATION_MODELS.map((model) => model.id); + + apiVersion: string; + endpoint?: string; + modelName: string; + configWithHeaders: AzureModerationConfig; + + constructor( + modelName: AzureModerationModelId = 'text-content-safety', + options: { config?: AzureModerationConfig; id?: string; env?: any } = {}, + ) { + super(modelName, options); + + const { config, env } = options; + + this.modelName = modelName; + this.configWithHeaders = config || {}; + this.apiVersion = + config?.apiVersion || + env?.AZURE_CONTENT_SAFETY_API_VERSION || + getEnvString('AZURE_CONTENT_SAFETY_API_VERSION') || + '2024-09-01'; + + this.endpoint = + config?.endpoint || + env?.AZURE_CONTENT_SAFETY_ENDPOINT || + getEnvString('AZURE_CONTENT_SAFETY_ENDPOINT'); + + if (!AzureModerationProvider.MODERATION_MODEL_IDS.includes(modelName)) { + logger.warn(`Using unknown Azure moderation model: ${modelName}`); + } + } + + // Get the specific Azure Content Safety API key + getContentSafetyApiKey(): string | undefined { + const extendedEnv = this.env as EnvOverrides & { AZURE_CONTENT_SAFETY_API_KEY?: string }; + + return ( + this.configWithHeaders.apiKey || + (this.configWithHeaders.apiKeyEnvar + ? process.env[this.configWithHeaders.apiKeyEnvar] || + (this.env && this.configWithHeaders.apiKeyEnvar in this.env + ? (this.env as any)[this.configWithHeaders.apiKeyEnvar] + : undefined) + : undefined) || + extendedEnv?.AZURE_CONTENT_SAFETY_API_KEY || + getEnvString('AZURE_CONTENT_SAFETY_API_KEY') || + // Fall back to standard Azure API keys + this.getApiKey() + ); + } + + async callModerationApi( + userPrompt: string, + assistantResponse: string, + ): Promise<ProviderModerationResponse> { + await this.ensureInitialized(); + + const apiKey = this.configWithHeaders.apiKey || this.getContentSafetyApiKey() || this.getApiKeyOrThrow(); + const endpoint = this.endpoint; + + if (!endpoint) { + return handleApiError( + new Error('Azure Content Safety endpoint is not set. Set the AZURE_CONTENT_SAFETY_ENDPOINT environment variable or add `endpoint` to the provider config.'), + ); + } + + // Log masked API key for debugging + if (apiKey) { + const maskedKey = apiKey.substring(0, 4) + '...' + apiKey.substring(apiKey.length - 4); + logger.debug(`Using Azure Content Safety API key: ${maskedKey}`); + } else { + logger.error('No Azure Content Safety API key found'); + return handleApiError( + new Error('Azure Content Safety API key is not set. Set the AZURE_CONTENT_SAFETY_API_KEY environment variable or add `apiKey` to the provider config.'), + ); + } + + const useCache = isCacheEnabled(); + let cacheKey = ''; + + if (useCache) { + cacheKey = getModerationCacheKey(this.modelName, this.configWithHeaders, assistantResponse); + const cache = await getCache(); + const cachedResponse = await cache.get(cacheKey); + + if (cachedResponse) { + logger.debug('Returning cached Azure moderation response'); + return cachedResponse; + } + } + + try { + // Make sure the endpoint doesn't end with a slash + const cleanEndpoint = endpoint.endsWith('/') ? endpoint.slice(0, -1) : endpoint; + const url = `${cleanEndpoint}/contentsafety/text:analyze?api-version=${this.apiVersion}`; + + const headers = { + 'Content-Type': 'application/json', + 'Ocp-Apim-Subscription-Key': apiKey, + ...(this.configWithHeaders.headers || {}), + }; + + const body = { + text: assistantResponse, + categories: ["Hate", "Sexual", "SelfHarm", "Violence"], + blocklistNames: [], + haltOnBlocklistHit: false, + outputType: 'FourSeverityLevels', + ...(this.configWithHeaders.passthrough || {}), + }; + + logger.debug(`Making Azure Content Safety API request to: ${url}`); + logger.debug(`Request body: ${JSON.stringify(body)}`);
Logging the full request body may expose sensitive information. Consider sanitizing or masking sensitive parts before logging. ```suggestion logger.debug(`Request body: ${JSON.stringify({ ...body, text: '***' })}`); ```
promptfoo
github_2023
typescript
3,292
promptfoo
mldangelo
@@ -0,0 +1,3 @@ +import { AzureModerationProvider } from './moderation';
delete this file or move azure.ts to this file
promptfoo
github_2023
others
3,292
promptfoo
mldangelo
@@ -121,7 +162,7 @@ Then Azure OpenAI will be used as the default provider for all operations includ Because embedding models are distinct from text generation, to set an embedding provider you must specify `AZURE_OPENAI_EMBEDDING_DEPLOYMENT_NAME`. -Note that any moderation tasks will still use the OpenAI API. +Note that any moderation tasks will still use the OpenAI API unless `AZURE_CONTENT_SAFETY_ENDPOINT` is set, in which case the Azure Content Safety API will be used.
ask claude to help you rephrase this
promptfoo
github_2023
others
3,292
promptfoo
mldangelo
@@ -64,23 +64,64 @@ providers: - `azure:chat:<deployment name>` - uses the given deployment (for chat endpoints such as gpt-35-turbo, gpt-4) - `azure:completion:<deployment name>` - uses the given deployment (for completion endpoints such as gpt-35-instruct) +- `azure:moderation` - uses the Azure Content Safety API for content moderation + +## Azure Content Safety for Moderation + +The `azure:moderation` provider integrates with the Azure Content Safety API to provide content moderation capabilities. It analyzes text for harmful content and returns flags for any detected issues.
worth noting that we moderate outputs
promptfoo
github_2023
others
3,292
promptfoo
mldangelo
@@ -64,23 +64,64 @@ providers: - `azure:chat:<deployment name>` - uses the given deployment (for chat endpoints such as gpt-35-turbo, gpt-4) - `azure:completion:<deployment name>` - uses the given deployment (for completion endpoints such as gpt-35-instruct) +- `azure:moderation` - uses the Azure Content Safety API for content moderation + +## Azure Content Safety for Moderation + +The `azure:moderation` provider integrates with the Azure Content Safety API to provide content moderation capabilities. It analyzes text for harmful content and returns flags for any detected issues. + +### Environment Variables + +- `AZURE_CONTENT_SAFETY_ENDPOINT`: The endpoint URL for the Azure Content Safety service +- `AZURE_CONTENT_SAFETY_API_VERSION`: The API version to use (default: "2024-09-01") +- `AZURE_CONTENT_SAFETY_API_KEY`: The API key for Azure Content Safety service (preferred) +- `AZURE_API_KEY`: The API key for Azure services (fallback) + +### Configuration + +```yaml +providers:
This is going to confuse people we should only configure it as a moderation provider and not put it in a provider block
promptfoo
github_2023
others
3,292
promptfoo
mldangelo
@@ -64,23 +64,64 @@ providers: - `azure:chat:<deployment name>` - uses the given deployment (for chat endpoints such as gpt-35-turbo, gpt-4) - `azure:completion:<deployment name>` - uses the given deployment (for completion endpoints such as gpt-35-instruct) +- `azure:moderation` - uses the Azure Content Safety API for content moderation + +## Azure Content Safety for Moderation
worth linking to azure docs
promptfoo
github_2023
typescript
3,292
promptfoo
mldangelo
@@ -0,0 +1,266 @@ +import { getCache, isCacheEnabled } from '../../cache'; +import { getEnvString } from '../../envars'; +import logger from '../../logger'; +import type { + ApiModerationProvider, + ModerationFlag, + ProviderModerationResponse, +} from '../../types'; +import type { EnvOverrides } from '../../types/env'; +import { AzureGenericProvider } from '../azure'; +import { REQUEST_TIMEOUT_MS } from '../shared'; + +export const AZURE_MODERATION_MODELS = [ + { id: 'text-content-safety', maxTokens: 10000, capabilities: ['text'] }, +]; + +export type AzureModerationModelId = string; +export type AzureModerationCategory = 'Hate' | 'SelfHarm' | 'Sexual' | 'Violence'; + +interface AzureTextCategoriesAnalysis { + category: AzureModerationCategory; + severity: number; +} + +interface AzureTextBlocklistMatch { + blocklistName: string; + blocklistItemId: string; + blocklistItemText: string; +} + +interface AzureAnalyzeTextResult { + categoriesAnalysis?: AzureTextCategoriesAnalysis[]; + blocklistsMatch?: AzureTextBlocklistMatch[]; +} + +export interface AzureModerationConfig { + apiKey?: string; + apiKeyEnvar?: string; + endpoint?: string; + apiVersion?: string; + headers?: Record<string, string>; + passthrough?: Record<string, any>; +} + +function parseAzureModerationResponse(data: AzureAnalyzeTextResult): ProviderModerationResponse { + try { + logger.debug(`Azure Content Safety API response: ${JSON.stringify(data)}`); + + if (!data) { + logger.error('Azure Content Safety API returned invalid response: null or undefined'); + return { flags: [] }; + } + + const categories =
why all of these?
promptfoo
github_2023
typescript
3,292
promptfoo
mldangelo
@@ -0,0 +1,266 @@ +import { getCache, isCacheEnabled } from '../../cache'; +import { getEnvString } from '../../envars'; +import logger from '../../logger'; +import type { + ApiModerationProvider, + ModerationFlag, + ProviderModerationResponse, +} from '../../types'; +import type { EnvOverrides } from '../../types/env'; +import { AzureGenericProvider } from '../azure'; +import { REQUEST_TIMEOUT_MS } from '../shared'; + +export const AZURE_MODERATION_MODELS = [ + { id: 'text-content-safety', maxTokens: 10000, capabilities: ['text'] }, +]; + +export type AzureModerationModelId = string; +export type AzureModerationCategory = 'Hate' | 'SelfHarm' | 'Sexual' | 'Violence'; + +interface AzureTextCategoriesAnalysis { + category: AzureModerationCategory; + severity: number; +} + +interface AzureTextBlocklistMatch { + blocklistName: string; + blocklistItemId: string; + blocklistItemText: string; +} + +interface AzureAnalyzeTextResult { + categoriesAnalysis?: AzureTextCategoriesAnalysis[]; + blocklistsMatch?: AzureTextBlocklistMatch[]; +} + +export interface AzureModerationConfig { + apiKey?: string; + apiKeyEnvar?: string; + endpoint?: string; + apiVersion?: string; + headers?: Record<string, string>; + passthrough?: Record<string, any>; +} + +function parseAzureModerationResponse(data: AzureAnalyzeTextResult): ProviderModerationResponse { + try { + logger.debug(`Azure Content Safety API response: ${JSON.stringify(data)}`); + + if (!data) { + logger.error('Azure Content Safety API returned invalid response: null or undefined'); + return { flags: [] }; + } + + const categories = + data.categoriesAnalysis || + (data as any).categoriesAnalysis || + (data as any).categories_analysis || + []; + const blocklistMatches = + data.blocklistsMatch || (data as any).blocklistsMatch || (data as any).blocklists_match || []; + + if (!categories || categories.length === 0) { + return { flags: [] }; + } + + const flags: ModerationFlag[] = []; + + for (const analysis of categories) { + if (analysis.severity > 0) { + const confidence = analysis.severity / 7;
what is going on here?
promptfoo
github_2023
typescript
3,292
promptfoo
mldangelo
@@ -0,0 +1,266 @@ +import { getCache, isCacheEnabled } from '../../cache'; +import { getEnvString } from '../../envars'; +import logger from '../../logger'; +import type { + ApiModerationProvider, + ModerationFlag, + ProviderModerationResponse, +} from '../../types'; +import type { EnvOverrides } from '../../types/env'; +import { AzureGenericProvider } from '../azure'; +import { REQUEST_TIMEOUT_MS } from '../shared'; + +export const AZURE_MODERATION_MODELS = [ + { id: 'text-content-safety', maxTokens: 10000, capabilities: ['text'] }, +]; + +export type AzureModerationModelId = string; +export type AzureModerationCategory = 'Hate' | 'SelfHarm' | 'Sexual' | 'Violence'; + +interface AzureTextCategoriesAnalysis { + category: AzureModerationCategory; + severity: number; +} + +interface AzureTextBlocklistMatch { + blocklistName: string; + blocklistItemId: string; + blocklistItemText: string; +} + +interface AzureAnalyzeTextResult { + categoriesAnalysis?: AzureTextCategoriesAnalysis[]; + blocklistsMatch?: AzureTextBlocklistMatch[]; +} + +export interface AzureModerationConfig { + apiKey?: string; + apiKeyEnvar?: string; + endpoint?: string; + apiVersion?: string; + headers?: Record<string, string>; + passthrough?: Record<string, any>; +} + +function parseAzureModerationResponse(data: AzureAnalyzeTextResult): ProviderModerationResponse { + try { + logger.debug(`Azure Content Safety API response: ${JSON.stringify(data)}`); + + if (!data) { + logger.error('Azure Content Safety API returned invalid response: null or undefined'); + return { flags: [] }; + } + + const categories = + data.categoriesAnalysis || + (data as any).categoriesAnalysis || + (data as any).categories_analysis || + []; + const blocklistMatches = + data.blocklistsMatch || (data as any).blocklistsMatch || (data as any).blocklists_match || []; + + if (!categories || categories.length === 0) { + return { flags: [] }; + } + + const flags: ModerationFlag[] = []; + + for (const analysis of categories) { + if (analysis.severity > 0) { + const confidence = analysis.severity / 7; + + flags.push({ + code: analysis.category.toLowerCase(), + description: `Content flagged for ${analysis.category}`, + confidence, + }); + } + } + + for (const match of blocklistMatches || []) { + flags.push({ + code: `blocklist:${match.blocklistName}`, + description: `Content matched blocklist item: ${match.blocklistItemText}`, + confidence: 1.0, + }); + } + + return { flags }; + } catch (error) { + logger.error(`Error parsing Azure Content Safety API response: ${error}`); + return { flags: [], error: 'Failed to parse moderation response' }; + } +} + +function handleApiError(err: any, data?: any): ProviderModerationResponse { + logger.error(`Azure moderation API error: ${err}${data ? `, ${data}` : ''}`); + return { error: err.message || 'Unknown error', flags: [] }; +} + +function getModerationCacheKey(modelName: string, config: any, content: string): string { + return `azure-moderation:${modelName}:${JSON.stringify(content)}`; +} + +export class AzureModerationProvider extends AzureGenericProvider implements ApiModerationProvider { + static MODERATION_MODELS = AZURE_MODERATION_MODELS; + static MODERATION_MODEL_IDS = AZURE_MODERATION_MODELS.map((model) => model.id); + + apiVersion: string; + endpoint?: string; + modelName: string; + configWithHeaders: AzureModerationConfig; + + constructor( + modelName: AzureModerationModelId = 'text-content-safety', + options: { config?: AzureModerationConfig; id?: string; env?: any } = {}, + ) { + super(modelName, options); + + const { config, env } = options; + + this.modelName = modelName; + this.configWithHeaders = config || {}; + this.apiVersion = + config?.apiVersion || + env?.AZURE_CONTENT_SAFETY_API_VERSION || + getEnvString('AZURE_CONTENT_SAFETY_API_VERSION') || + '2024-09-01'; + + this.endpoint = + config?.endpoint || + env?.AZURE_CONTENT_SAFETY_ENDPOINT || + getEnvString('AZURE_CONTENT_SAFETY_ENDPOINT'); + + if (!AzureModerationProvider.MODERATION_MODEL_IDS.includes(modelName)) { + logger.warn(`Using unknown Azure moderation model: ${modelName}`); + } + } + + getContentSafetyApiKey(): string | undefined { + const extendedEnv = this.env as EnvOverrides & { AZURE_CONTENT_SAFETY_API_KEY?: string }; + + return ( + this.configWithHeaders.apiKey || + (this.configWithHeaders.apiKeyEnvar + ? process.env[this.configWithHeaders.apiKeyEnvar] || + (this.env && this.configWithHeaders.apiKeyEnvar in this.env + ? (this.env as any)[this.configWithHeaders.apiKeyEnvar] + : undefined) + : undefined) || + extendedEnv?.AZURE_CONTENT_SAFETY_API_KEY || + getEnvString('AZURE_CONTENT_SAFETY_API_KEY') || + this.getApiKey() + ); + } + + async callModerationApi( + userPrompt: string, + assistantResponse: string, + ): Promise<ProviderModerationResponse> { + await this.ensureInitialized(); + + const apiKey = + this.configWithHeaders.apiKey || this.getContentSafetyApiKey() || this.getApiKeyOrThrow(); + const endpoint = this.endpoint; + + if (!endpoint) { + return handleApiError( + new Error( + 'Azure Content Safety endpoint is not set. Set the AZURE_CONTENT_SAFETY_ENDPOINT environment variable or add `endpoint` to the provider config.', + ), + ); + } + + if (apiKey) { + const maskedKey = apiKey.substring(0, 4) + '...' + apiKey.substring(apiKey.length - 4); + logger.debug(`Using Azure Content Safety API key: ${maskedKey}`); + } else { + logger.error('No Azure Content Safety API key found'); + return handleApiError( + new Error( + 'Azure Content Safety API key is not set. Set the AZURE_CONTENT_SAFETY_API_KEY environment variable or add `apiKey` to the provider config.', + ), + ); + } + + const useCache = isCacheEnabled(); + let cacheKey = ''; + + if (useCache) { + cacheKey = getModerationCacheKey(this.modelName, this.configWithHeaders, assistantResponse); + const cache = await getCache(); + const cachedResponse = await cache.get(cacheKey); + + if (cachedResponse) { + logger.debug('Returning cached Azure moderation response'); + return cachedResponse; + } + } + + try { + const cleanEndpoint = endpoint.endsWith('/') ? endpoint.slice(0, -1) : endpoint; + const url = `${cleanEndpoint}/contentsafety/text:analyze?api-version=${this.apiVersion}`; + + const headers = { + 'Content-Type': 'application/json', + 'Ocp-Apim-Subscription-Key': apiKey, + ...(this.configWithHeaders.headers || {}), + }; + + const body = { + text: assistantResponse, + categories: ['Hate', 'Sexual', 'SelfHarm', 'Violence'], + blocklistNames: [],
can we make these configurable?
promptfoo
github_2023
typescript
3,292
promptfoo
mldangelo
@@ -150,6 +151,13 @@ export async function getDefaultProviders(env?: EnvOverrides): Promise<DefaultPr synthesizeProvider: OpenAiGradingJsonProvider, }; } + + // If Azure Content Safety endpoint is available, use it for moderation + const extendedEnv = env as EnvOverrides & { AZURE_CONTENT_SAFETY_ENDPOINT?: string };
Can you just add to EnvOverrides?
promptfoo
github_2023
typescript
3,292
promptfoo
mldangelo
@@ -153,3 +153,6 @@ export async function loadApiProviders( } throw new Error('Invalid providers list'); } + +export * from './azure';
please remove
promptfoo
github_2023
typescript
3,292
promptfoo
mldangelo
@@ -168,12 +169,24 @@ export const providerMap: ProviderFactory[] = [ }, { test: (providerPath: string) => - providerPath.startsWith('azure:') || providerPath.startsWith('azureopenai:'), + providerPath.startsWith('azure:') || + providerPath.startsWith('azureopenai:') || + providerPath === 'azure-moderation',
```suggestion providerPath === 'azure:moderation', ```
promptfoo
github_2023
typescript
3,270
promptfoo
ellipsis-dev[bot]
@@ -0,0 +1,241 @@ +import WebSocket from 'ws'; +import { getEnvString } from '../envars'; +import logger from '../logger'; +import type { + ApiProvider, + CallApiContextParams, + ProviderOptions, + ProviderResponse, +} from '../types'; +import '../util'; +import { maybeLoadFromExternalFile, renderVarsInObject } from '../util'; + +interface Blob { + mimeType: string; + data: string; // base64-encoded string +} + +interface FunctionCall { + name: string; + args?: { [key: string]: any }; +} + +interface FunctionResponse { + name: string; + response: { [key: string]: any }; +} + +interface FileData { + mimeType?: string; + fileUri: string; +} + +interface Part { + text?: string; + inlineData?: Blob; + functionCall?: FunctionCall; + functionResponse?: FunctionResponse; + fileData?: FileData; +} + +interface Content { + parts: Part[]; + role?: string; +} + +interface Schema { + type: 'TYPE_UNSPECIFIED' | 'STRING' | 'NUMBER' | 'INTEGER' | 'BOOLEAN' | 'ARRAY' | 'OBJECT'; + format?: string; + description?: string; + nullable?: boolean; + enum?: string[]; + maxItems?: string; + minItems?: string; + properties?: { [key: string]: Schema }; + required?: string[]; + propertyOrdering?: string[]; + items?: Schema; +} + +interface FunctionDeclaration { + name: string; + description: string; + parameters?: Schema; + response?: Schema; +} + +interface GoogleSearchRetrieval { + dynamicRetrievalConfig: { + mode?: 'MODE_UNSPECIFIED' | 'MODE_DYNAMIC'; + dynamicThreshold?: number; + }; +} + +interface Tool { + functionDeclarations?: FunctionDeclaration[]; + googleSearchRetrieval?: GoogleSearchRetrieval; + codeExecution?: object; + googleSearch?: object; +} + +interface CompletionOptions { + apiKey: string; + timeoutMs?: number; + transformResponse?: string | Function; + + // https://ai.google.dev/api/rest/v1beta/models/streamGenerateContent#request-body + context?: string; + examples?: { input: string; output: string }[]; + stopSequence?: string[]; + temperature?: number; + maxOutputTokens?: number; + topP?: number; + topK?: number; + + generationConfig?: { + response_modalities?: string[]; + context?: string; + examples?: { input: string; output: string }[]; + stopSequence?: string[]; + temperature?: number; + maxOutputTokens?: number; + topP?: number; + topK?: number; + }; + + toolConfig?: { + functionCallingConfig?: { + mode?: 'MODE_UNSPECIFIED' | 'AUTO' | 'ANY' | 'NONE'; + allowedFunctionNames?: string[]; + }; + }; + + tools?: Tool[]; + + systemInstruction?: Content; +} + +export class GoogleMMLiveProvider implements ApiProvider { + config: CompletionOptions; + modelName: string; + + constructor(modelName: string, options: ProviderOptions) { + this.config = options.config as CompletionOptions; + this.modelName = modelName; + } + + id(): string { + return `google-mm-live:${this.modelName}`; + } + + toString(): string { + return `[Google Multimodal Live Provider ${this.modelName}]`; + } + + getApiKey(): string | undefined { + return this.config.apiKey || getEnvString('GOOGLE_API_KEY'); + } + + async callApi(prompt: string, context?: CallApiContextParams): Promise<ProviderResponse> { + // https://cloud.google.com/vertex-ai/docs/generative-ai/model-reference/gemini#gemini-pro + + const userMessage = prompt; + + // logger.debug(`Sending WebSocket message to ${this.url}: ${message}`); + + return new Promise<ProviderResponse>((resolve) => { + const url = `wss://generativelanguage.googleapis.com/ws/google.ai.generativelanguage.v1alpha.GenerativeService.BidiGenerateContent?key=${this.getApiKey()}`; + const ws = new WebSocket(url); + const timeout = setTimeout(() => { + ws.close(); + resolve({ error: 'WebSocket request timed out' }); + }, this.config.timeoutMs || 10000); + + let response_text_total = ''; + + ws.onmessage = async (event) => { + // clearTimeout(timeout); + logger.debug(`Received WebSocket response: ${event.data}`); + try { + // Handle Blob data + const responseText = await new Response(event.data.toString('utf-8')).text(); + const response = JSON.parse(responseText); + console.log('Endpoint respopnse:', JSON.stringify(response)); + + // Handle setup complete response + if (response.setupComplete) { + const contentMessage = { + client_content: { + turns: [ + { + role: 'user', + parts: [{ text: userMessage }], + }, + ], + turn_complete: true, + }, + }; + ws.send(JSON.stringify(contentMessage)); + } + // Handle model response + else if (response.serverContent?.modelTurn?.parts?.[0]?.text) { + response_text_total = + response_text_total + response.serverContent.modelTurn.parts[0].text; + } else if (response.toolCall?.functionCalls) { + resolve({ output: JSON.stringify(response) }); + } else if (response.serverContent?.turnComplete) { + if (response_text_total) { + resolve({ output: response_text_total }); + } + ws.close(); + } + } catch (err) { + console.error('Failed to process response:', err); + resolve({ error: `Failed to process response: ${JSON.stringify(err)}` }); + } + }; + + ws.onerror = (err) => { + clearTimeout(timeout); + console.error('WebSocket Error:', err); + resolve({ error: `WebSocket error: ${JSON.stringify(err)}` }); + }; + + ws.onclose = (event) => { + clearTimeout(timeout); + }; + + ws.onopen = () => { + console.log('WebSocket connection is opening...'); + + const setupMessage = { + setup: { + model: `models/${this.modelName}`, + generation_config: { + context: this.config.context, + examples: this.config.examples, + stopSequence: this.config.stopSequence, + temperature: this.config.temperature, + maxOutputTokens: this.config.maxOutputTokens, + topP: this.config.topP, + topK: this.config.topK, + ...this.config.generationConfig, + }, + ...(this.config.toolConfig ? { toolConfig: this.config.toolConfig } : {}), + ...(this.config.tools + ? { + tools: maybeLoadFromExternalFile( + renderVarsInObject(this.config.tools, context?.vars), + ), + } + : {}), + ...(this.config.systemInstruction + ? { tools: maybeLoadFromExternalFile(this.config.systemInstruction) }
Merging 'tools' and 'systemInstruction' under the same key may lead to an override. Consider using separate keys or merging them intentionally. ```suggestion ? { systemInstruction: maybeLoadFromExternalFile(this.config.systemInstruction) } ```
promptfoo
github_2023
typescript
3,270
promptfoo
ellipsis-dev[bot]
@@ -0,0 +1,241 @@ +import WebSocket from 'ws'; +import { getEnvString } from '../envars'; +import logger from '../logger'; +import type { + ApiProvider, + CallApiContextParams, + ProviderOptions, + ProviderResponse, +} from '../types'; +import '../util'; +import { maybeLoadFromExternalFile, renderVarsInObject } from '../util'; + +interface Blob { + mimeType: string; + data: string; // base64-encoded string +} + +interface FunctionCall { + name: string; + args?: { [key: string]: any }; +} + +interface FunctionResponse { + name: string; + response: { [key: string]: any }; +} + +interface FileData { + mimeType?: string; + fileUri: string; +} + +interface Part { + text?: string; + inlineData?: Blob; + functionCall?: FunctionCall; + functionResponse?: FunctionResponse; + fileData?: FileData; +} + +interface Content { + parts: Part[]; + role?: string; +} + +interface Schema { + type: 'TYPE_UNSPECIFIED' | 'STRING' | 'NUMBER' | 'INTEGER' | 'BOOLEAN' | 'ARRAY' | 'OBJECT'; + format?: string; + description?: string; + nullable?: boolean; + enum?: string[]; + maxItems?: string; + minItems?: string; + properties?: { [key: string]: Schema }; + required?: string[]; + propertyOrdering?: string[]; + items?: Schema; +} + +interface FunctionDeclaration { + name: string; + description: string; + parameters?: Schema; + response?: Schema; +} + +interface GoogleSearchRetrieval { + dynamicRetrievalConfig: { + mode?: 'MODE_UNSPECIFIED' | 'MODE_DYNAMIC'; + dynamicThreshold?: number; + }; +} + +interface Tool { + functionDeclarations?: FunctionDeclaration[]; + googleSearchRetrieval?: GoogleSearchRetrieval; + codeExecution?: object; + googleSearch?: object; +} + +interface CompletionOptions { + apiKey: string; + timeoutMs?: number; + transformResponse?: string | Function; + + // https://ai.google.dev/api/rest/v1beta/models/streamGenerateContent#request-body + context?: string; + examples?: { input: string; output: string }[]; + stopSequence?: string[]; + temperature?: number; + maxOutputTokens?: number; + topP?: number; + topK?: number; + + generationConfig?: { + response_modalities?: string[]; + context?: string; + examples?: { input: string; output: string }[]; + stopSequence?: string[]; + temperature?: number; + maxOutputTokens?: number; + topP?: number; + topK?: number; + }; + + toolConfig?: { + functionCallingConfig?: { + mode?: 'MODE_UNSPECIFIED' | 'AUTO' | 'ANY' | 'NONE'; + allowedFunctionNames?: string[]; + }; + }; + + tools?: Tool[]; + + systemInstruction?: Content; +} + +export class GoogleMMLiveProvider implements ApiProvider { + config: CompletionOptions; + modelName: string; + + constructor(modelName: string, options: ProviderOptions) { + this.config = options.config as CompletionOptions; + this.modelName = modelName; + } + + id(): string { + return `google-mm-live:${this.modelName}`; + } + + toString(): string { + return `[Google Multimodal Live Provider ${this.modelName}]`; + } + + getApiKey(): string | undefined { + return this.config.apiKey || getEnvString('GOOGLE_API_KEY'); + } + + async callApi(prompt: string, context?: CallApiContextParams): Promise<ProviderResponse> { + // https://cloud.google.com/vertex-ai/docs/generative-ai/model-reference/gemini#gemini-pro + + const userMessage = prompt; + + // logger.debug(`Sending WebSocket message to ${this.url}: ${message}`); + + return new Promise<ProviderResponse>((resolve) => { + const url = `wss://generativelanguage.googleapis.com/ws/google.ai.generativelanguage.v1alpha.GenerativeService.BidiGenerateContent?key=${this.getApiKey()}`; + const ws = new WebSocket(url); + const timeout = setTimeout(() => { + ws.close(); + resolve({ error: 'WebSocket request timed out' }); + }, this.config.timeoutMs || 10000); + + let response_text_total = ''; + + ws.onmessage = async (event) => { + // clearTimeout(timeout); + logger.debug(`Received WebSocket response: ${event.data}`); + try { + // Handle Blob data + const responseText = await new Response(event.data.toString('utf-8')).text();
Review the conversion of `event.data` using `toString('utf-8')`; ensure that `event.data` is a `Buffer` and not already a string to avoid potential issues.
promptfoo
github_2023
typescript
3,270
promptfoo
ellipsis-dev[bot]
@@ -0,0 +1,241 @@ +import WebSocket from 'ws'; +import { getEnvString } from '../envars'; +import logger from '../logger'; +import type { + ApiProvider, + CallApiContextParams, + ProviderOptions, + ProviderResponse, +} from '../types'; +import '../util'; +import { maybeLoadFromExternalFile, renderVarsInObject } from '../util'; + +interface Blob { + mimeType: string; + data: string; // base64-encoded string +} + +interface FunctionCall { + name: string; + args?: { [key: string]: any }; +} + +interface FunctionResponse { + name: string; + response: { [key: string]: any }; +} + +interface FileData { + mimeType?: string; + fileUri: string; +} + +interface Part { + text?: string; + inlineData?: Blob; + functionCall?: FunctionCall; + functionResponse?: FunctionResponse; + fileData?: FileData; +} + +interface Content { + parts: Part[]; + role?: string; +} + +interface Schema { + type: 'TYPE_UNSPECIFIED' | 'STRING' | 'NUMBER' | 'INTEGER' | 'BOOLEAN' | 'ARRAY' | 'OBJECT'; + format?: string; + description?: string; + nullable?: boolean; + enum?: string[]; + maxItems?: string; + minItems?: string; + properties?: { [key: string]: Schema }; + required?: string[]; + propertyOrdering?: string[]; + items?: Schema; +} + +interface FunctionDeclaration { + name: string; + description: string; + parameters?: Schema; + response?: Schema; +} + +interface GoogleSearchRetrieval { + dynamicRetrievalConfig: { + mode?: 'MODE_UNSPECIFIED' | 'MODE_DYNAMIC'; + dynamicThreshold?: number; + }; +} + +interface Tool { + functionDeclarations?: FunctionDeclaration[]; + googleSearchRetrieval?: GoogleSearchRetrieval; + codeExecution?: object; + googleSearch?: object; +} + +interface CompletionOptions { + apiKey: string; + timeoutMs?: number; + transformResponse?: string | Function; + + // https://ai.google.dev/api/rest/v1beta/models/streamGenerateContent#request-body + context?: string; + examples?: { input: string; output: string }[]; + stopSequence?: string[]; + temperature?: number; + maxOutputTokens?: number; + topP?: number; + topK?: number; + + generationConfig?: { + response_modalities?: string[]; + context?: string; + examples?: { input: string; output: string }[]; + stopSequence?: string[]; + temperature?: number; + maxOutputTokens?: number; + topP?: number; + topK?: number; + }; + + toolConfig?: { + functionCallingConfig?: { + mode?: 'MODE_UNSPECIFIED' | 'AUTO' | 'ANY' | 'NONE'; + allowedFunctionNames?: string[]; + }; + }; + + tools?: Tool[]; + + systemInstruction?: Content; +} + +export class GoogleMMLiveProvider implements ApiProvider { + config: CompletionOptions; + modelName: string; + + constructor(modelName: string, options: ProviderOptions) { + this.config = options.config as CompletionOptions; + this.modelName = modelName; + } + + id(): string { + return `google-mm-live:${this.modelName}`; + } + + toString(): string { + return `[Google Multimodal Live Provider ${this.modelName}]`; + } + + getApiKey(): string | undefined { + return this.config.apiKey || getEnvString('GOOGLE_API_KEY'); + } + + async callApi(prompt: string, context?: CallApiContextParams): Promise<ProviderResponse> { + // https://cloud.google.com/vertex-ai/docs/generative-ai/model-reference/gemini#gemini-pro + + const userMessage = prompt; + + // logger.debug(`Sending WebSocket message to ${this.url}: ${message}`); + + return new Promise<ProviderResponse>((resolve) => { + const url = `wss://generativelanguage.googleapis.com/ws/google.ai.generativelanguage.v1alpha.GenerativeService.BidiGenerateContent?key=${this.getApiKey()}`; + const ws = new WebSocket(url); + const timeout = setTimeout(() => { + ws.close(); + resolve({ error: 'WebSocket request timed out' }); + }, this.config.timeoutMs || 10000); + + let response_text_total = ''; + + ws.onmessage = async (event) => { + // clearTimeout(timeout); + logger.debug(`Received WebSocket response: ${event.data}`); + try { + // Handle Blob data + const responseText = await new Response(event.data.toString('utf-8')).text(); + const response = JSON.parse(responseText); + console.log('Endpoint respopnse:', JSON.stringify(response));
Typo in log message: 'respopnse' should be 'response'. ```suggestion console.log('Endpoint response:', JSON.stringify(response)); ```
promptfoo
github_2023
typescript
3,270
promptfoo
ellipsis-dev[bot]
@@ -0,0 +1,241 @@ +import WebSocket from 'ws'; +import { getEnvString } from '../envars'; +import logger from '../logger'; +import type { + ApiProvider, + CallApiContextParams, + ProviderOptions, + ProviderResponse, +} from '../types'; +import '../util'; +import { maybeLoadFromExternalFile, renderVarsInObject } from '../util'; + +interface Blob { + mimeType: string; + data: string; // base64-encoded string +} + +interface FunctionCall { + name: string; + args?: { [key: string]: any }; +} + +interface FunctionResponse { + name: string; + response: { [key: string]: any }; +} + +interface FileData { + mimeType?: string; + fileUri: string; +} + +interface Part { + text?: string; + inlineData?: Blob; + functionCall?: FunctionCall; + functionResponse?: FunctionResponse; + fileData?: FileData; +} + +interface Content { + parts: Part[]; + role?: string; +} + +interface Schema { + type: 'TYPE_UNSPECIFIED' | 'STRING' | 'NUMBER' | 'INTEGER' | 'BOOLEAN' | 'ARRAY' | 'OBJECT'; + format?: string; + description?: string; + nullable?: boolean; + enum?: string[]; + maxItems?: string; + minItems?: string; + properties?: { [key: string]: Schema }; + required?: string[]; + propertyOrdering?: string[]; + items?: Schema; +} + +interface FunctionDeclaration { + name: string; + description: string; + parameters?: Schema; + response?: Schema; +} + +interface GoogleSearchRetrieval { + dynamicRetrievalConfig: { + mode?: 'MODE_UNSPECIFIED' | 'MODE_DYNAMIC'; + dynamicThreshold?: number; + }; +} + +interface Tool { + functionDeclarations?: FunctionDeclaration[]; + googleSearchRetrieval?: GoogleSearchRetrieval; + codeExecution?: object; + googleSearch?: object; +} + +interface CompletionOptions { + apiKey: string; + timeoutMs?: number; + transformResponse?: string | Function; + + // https://ai.google.dev/api/rest/v1beta/models/streamGenerateContent#request-body + context?: string; + examples?: { input: string; output: string }[]; + stopSequence?: string[]; + temperature?: number; + maxOutputTokens?: number; + topP?: number; + topK?: number; + + generationConfig?: { + response_modalities?: string[]; + context?: string; + examples?: { input: string; output: string }[]; + stopSequence?: string[]; + temperature?: number; + maxOutputTokens?: number; + topP?: number; + topK?: number; + }; + + toolConfig?: { + functionCallingConfig?: { + mode?: 'MODE_UNSPECIFIED' | 'AUTO' | 'ANY' | 'NONE'; + allowedFunctionNames?: string[]; + }; + }; + + tools?: Tool[]; + + systemInstruction?: Content; +} + +export class GoogleMMLiveProvider implements ApiProvider { + config: CompletionOptions; + modelName: string; + + constructor(modelName: string, options: ProviderOptions) { + this.config = options.config as CompletionOptions; + this.modelName = modelName; + } + + id(): string { + return `google-mm-live:${this.modelName}`; + } + + toString(): string { + return `[Google Multimodal Live Provider ${this.modelName}]`; + } + + getApiKey(): string | undefined { + return this.config.apiKey || getEnvString('GOOGLE_API_KEY'); + } + + async callApi(prompt: string, context?: CallApiContextParams): Promise<ProviderResponse> { + // https://cloud.google.com/vertex-ai/docs/generative-ai/model-reference/gemini#gemini-pro + + const userMessage = prompt; + + // logger.debug(`Sending WebSocket message to ${this.url}: ${message}`); + + return new Promise<ProviderResponse>((resolve) => { + const url = `wss://generativelanguage.googleapis.com/ws/google.ai.generativelanguage.v1alpha.GenerativeService.BidiGenerateContent?key=${this.getApiKey()}`; + const ws = new WebSocket(url); + const timeout = setTimeout(() => { + ws.close(); + resolve({ error: 'WebSocket request timed out' }); + }, this.config.timeoutMs || 10000); + + let response_text_total = ''; + + ws.onmessage = async (event) => { + // clearTimeout(timeout); + logger.debug(`Received WebSocket response: ${event.data}`); + try { + // Handle Blob data + const responseText = await new Response(event.data.toString('utf-8')).text(); + const response = JSON.parse(responseText); + console.log('Endpoint respopnse:', JSON.stringify(response)); + + // Handle setup complete response + if (response.setupComplete) { + const contentMessage = { + client_content: { + turns: [ + { + role: 'user', + parts: [{ text: userMessage }], + }, + ], + turn_complete: true, + }, + }; + ws.send(JSON.stringify(contentMessage)); + } + // Handle model response + else if (response.serverContent?.modelTurn?.parts?.[0]?.text) { + response_text_total = + response_text_total + response.serverContent.modelTurn.parts[0].text; + } else if (response.toolCall?.functionCalls) { + resolve({ output: JSON.stringify(response) });
Consider clearing the timeout and closing the WebSocket after calling resolve in each branch within the `onmessage` handler. Currently, the timeout is only cleared in `onerror` and `onclose`, which may lead to lingering timers or connections.
promptfoo
github_2023
typescript
3,271
promptfoo
ellipsis-dev[bot]
@@ -201,6 +201,12 @@ export function createApp() { // Must come after the above routes (particularly /api/config) so it doesn't // overwrite dynamic routes. + + express.static.mime.define({ + 'application/javascript': ['js', 'mjs', 'jsx', 'ts', 'tsx'], + 'text/javascript': ['js', 'mjs', 'jsx', 'ts', 'tsx'],
Duplicate MIME definitions: the same extensions are mapped to both `'application/javascript'` and `'text/javascript'`, which may cause unpredictable behavior. Consider using a single, correct MIME type (likely `'application/javascript'` for module scripts). ```suggestion ```
promptfoo
github_2023
typescript
3,275
promptfoo
ellipsis-dev[bot]
@@ -113,7 +113,15 @@ export class GolangProvider implements ApiProvider { if (entry.isDirectory()) { copyDir(srcPath, destPath); } else { - fs.copyFileSync(srcPath, destPath); + // Special handling for main.go to remove var CallApi declaration + if (entry.name === 'main.go') { + let content = fs.readFileSync(srcPath, 'utf-8'); + // Remove the var CallApi declaration while preserving the file + content = content.replace(/\/\/ CallApi.*?var CallApi.*?\n/s, '');
Regex in special handling may be too rigid. It assumes a specific formatting for the `CallApi` declaration. Consider making it more robust (e.g., accounting for varying whitespace or comments) and add tests. ```suggestion content = content.replace(/\/\/\s*CallApi[\s\S]*?var\s+CallApi[\s\S]*?\n/s, ''); ```
promptfoo
github_2023
typescript
3,287
promptfoo
ellipsis-dev[bot]
@@ -124,6 +124,14 @@ export async function doEval( ({ config, testSuite, basePath: _basePath } = await resolveConfigs(cmdObj, defaultConfig)); + // Ensure evaluateOptions from the config file are applied + if (config.evaluateOptions) { + evaluateOptions = { + ...evaluateOptions,
The new merge block here (lines 127–133) uses `evaluateOptions = { ...evaluateOptions, ...config.evaluateOptions }`. Later, when constructing the final options object (which sets `maxConcurrency` from cmdObj and then spreads `evaluateOptions`), the config file’s maxConcurrency ends up overriding the command-line value. Since tests expect command-line options (even undefined) to take precedence, consider reversing the merge order (or adjusting the spread order in the final options) so that command-line values override config settings.
promptfoo
github_2023
typescript
3,299
promptfoo
ellipsis-dev[bot]
@@ -15,20 +15,51 @@ function makeRequest(path: string, method: string, body?: any) { }); } -export async function getConfigFromCloud(id: string) { +export async function getProviderFromCloud(id: string) { if (!cloudConfig.isEnabled()) { - throw new Error('Cloud config is not enabled. Please run `promptfoo auth login` to login.'); + throw new Error( + `Could not fetch Provider ${id} from cloud. Cloud config is not enabled. Please run \`promptfoo auth login\` to login.`, + ); + } + try { + const response = await makeRequest(`api/providers/${id}`, 'GET'); + + const body = await response.json(); + if (response.ok) { + logger.info(`Provider fetched from cloud: ${id}`); + logger.debug(`Provider from cloud: ${JSON.stringify(body, null, 2)}`); + } else { + throw new Error(`Failed to fetch provider from cloud: ${response.statusText}`); + } + return body.config; + } catch (e) { + logger.error(`Failed to fetch provider from cloud: ${id}.`); + logger.error(String(e)); + throw new Error(`Failed to fetch provider from cloud: ${id}.`);
When rethrowing errors in `getProviderFromCloud` (and similarly in `getConfigFromCloud`), consider preserving the original error details (e.g., by using the error 'cause') to aid debugging. ```suggestion throw new Error(`Failed to fetch provider from cloud: ${id}.`, { cause: e }); ```
promptfoo
github_2023
typescript
3,299
promptfoo
ellipsis-dev[bot]
@@ -29,6 +31,13 @@ export async function loadApiProvider( const renderedProviderPath = getNunjucksEngine().renderString(providerPath, {}); + if (renderedProviderPath.startsWith(CLOUD_PREFIX_IDENTIFIER)) { + const cloudDatabaseId = renderedProviderPath.slice(CLOUD_PREFIX_IDENTIFIER.length); + + const provider = await getProviderFromCloud(cloudDatabaseId); + return loadApiProvider(provider.id, { ...context, options: provider });
Recursively calling `loadApiProvider` after fetching a cloud provider might risk an infinite loop if the returned `provider.id` still starts with the `CLOUD_PREFIX_IDENTIFIER`. Consider adding a check to prevent recursion. ```suggestion if (!provider.id.startsWith(CLOUD_PREFIX_IDENTIFIER)) return loadApiProvider(provider.id, { ...context, options: provider }); ```
promptfoo
github_2023
typescript
3,299
promptfoo
mldangelo
@@ -15,20 +15,51 @@ function makeRequest(path: string, method: string, body?: any) { }); } -export async function getConfigFromCloud(id: string) { +export async function getProviderFromCloud(id: string) { if (!cloudConfig.isEnabled()) { - throw new Error('Cloud config is not enabled. Please run `promptfoo auth login` to login.'); + throw new Error( + `Could not fetch Provider ${id} from cloud. Cloud config is not enabled. Please run \`promptfoo auth login\` to login.`, + ); + } + try { + const response = await makeRequest(`api/providers/${id}`, 'GET'); + + const body = await response.json();
nit, type - consider zod!
promptfoo
github_2023
typescript
3,299
promptfoo
ellipsis-dev[bot]
@@ -1,6 +1,9 @@ +import { ProviderOptions } from 'src/types'; import { fetchWithProxy } from '../fetch'; import { cloudConfig } from '../globalConfig/cloud'; import logger from '../logger'; +import { ProviderOptionsSchema, ProvidersSchema } from '../validators/providers';
Unused `ProvidersSchema` import detected. Remove if not required. ```suggestion import { ProviderOptionsSchema } from '../validators/providers'; ```
promptfoo
github_2023
typescript
3,300
promptfoo
github-advanced-security[bot]
@@ -0,0 +1,171 @@ +import { fetchWithProxy } from '../../src/fetch'; +import { cloudConfig } from '../../src/globalConfig/cloud'; +import { makeRequest } from '../../src/util/cloud'; + +jest.mock('../../src/fetch'); +jest.mock('../../src/globalConfig/cloud'); + +describe('cloud utils', () => { + const mockFetchWithProxy = jest.mocked(fetchWithProxy); + const mockCloudConfig = cloudConfig as jest.Mocked<typeof cloudConfig>; + + beforeEach(() => { + jest.resetAllMocks(); + + mockCloudConfig.getApiHost.mockReturnValue('https://api.example.com'); + mockCloudConfig.getApiKey.mockReturnValue('test-api-key'); + }); + + describe('makeRequest', () => { + it('should make request with correct URL and headers', async () => { + const path = 'test/path'; + const method = 'POST'; + const body = { data: 'test' }; + + await makeRequest(path, method, body); + + expect(mockFetchWithProxy).toHaveBeenCalledWith('https://api.example.com/test/path', { + method: 'POST', + body: JSON.stringify(body), + headers: { Authorization: 'Bearer test-api-key' }, + }); + }); + + it('should make GET request without body', async () => { + const path = 'test/path'; + const method = 'GET'; + + await makeRequest(path, method); + + expect(mockFetchWithProxy).toHaveBeenCalledWith('https://api.example.com/test/path', { + method: 'GET', + body: undefined, + headers: { Authorization: 'Bearer test-api-key' }, + }); + }); + + it('should handle undefined API key', async () => { + mockCloudConfig.getApiKey.mockReturnValue(undefined); + + const path = 'test/path'; + const method = 'GET'; + + await makeRequest(path, method); + + expect(mockFetchWithProxy).toHaveBeenCalledWith('https://api.example.com/test/path', { + method: 'GET', + body: undefined, + headers: { Authorization: 'Bearer undefined' },
## Hard-coded credentials The hard-coded value "Bearer undefined" is used as [authorization header](1). [Show more details](https://github.com/promptfoo/promptfoo/security/code-scanning/86)
promptfoo
github_2023
typescript
3,302
promptfoo
ellipsis-dev[bot]
@@ -112,6 +112,13 @@ export interface ProviderResponse { isRefusal?: boolean; sessionId?: string; guardrails?: GuardrailResponse; + audio?: { + id?: string; + expires_at?: number;
Consider revising `expires_at` to use camelCase (i.e. `expiresAt`) for consistency with the rest of the codebase. While this is purely stylistic, consistent naming helps maintain readability. ```suggestion expiresAt?: number; ```
promptfoo
github_2023
others
3,301
promptfoo
ellipsis-dev[bot]
@@ -2,262 +2,307 @@ sidebar_label: Custom Javascript --- -# Javascript Provider +# Custom Javascript Providers
Use standard capitalization for JavaScript. Consider changing 'Custom Javascript Providers' to 'Custom JavaScript Providers' for consistency. ```suggestion # Custom JavaScript Providers ```
promptfoo
github_2023
others
3,301
promptfoo
ellipsis-dev[bot]
@@ -2,262 +2,307 @@ sidebar_label: Custom Javascript --- -# Javascript Provider +# Custom Javascript Providers -Promptfoo supports custom Javascript and Typescript for integrations that go beyond single API calls (see also [HTTP API](/docs/providers/http/), [Python](/docs/providers/python/), [Browser](/docs/providers/browser/), and [Custom Script](/docs/providers/custom-script/)). +Custom Javascript providers let you create providers in JavaScript or TypeScript to integrate with any API or service not built into promptfoo. -To create a custom API provider, implement the `ApiProvider` interface in a separate module. Here is the interface: +## Supported File Formats and Examples -```ts -export interface CallApiContextParams { - vars: Record<string, string | object>; - prompt: Prompt; - // Used when provider is overridden on the test case. - originalProvider?: ApiProvider; - logger?: winston.Logger; -} - -export interface CallApiOptionsParams { - // Whether to include logprobs in API response (used with OpenAI providers) - includeLogProbs?: boolean; -} - -export interface ApiProvider { - constructor(options: { id?: string; config: Record<string, any> }); - - // Unique identifier for the provider - id: () => string; - - // Text generation function - callApi: ( - prompt: string, - context?: CallApiContextParams, - options?: CallApiOptionsParams, - ) => Promise<ProviderResponse>; +promptfoo supports multiple JavaScript module formats. Complete working examples are available on GitHub: - // Embedding function - callEmbeddingApi?: (prompt: string) => Promise<ProviderEmbeddingResponse>; +- [CommonJS Provider](https://github.com/promptfoo/promptfoo/tree/main/examples/custom-provider) - (`.js`, `.cjs`) - Uses `module.exports` and `require()` +- [ESM Provider](https://github.com/promptfoo/promptfoo/tree/main/examples/custom-provider-mjs) - (`.mjs`, `.js` with `"type": "module"`) - Uses `import`/`export` +- [TypeScript Provider](https://github.com/promptfoo/promptfoo/tree/main/examples/custom-provider-typescript) - (`.ts`) - Provides type safety with interfaces +- [Embeddings Provider](https://github.com/promptfoo/promptfoo/tree/main/examples/custom-provider-embeddings) (commonjs) - // Classification function - callClassificationApi?: (prompt: string) => Promise<ProviderClassificationResponse>; +## Provider Interface - // Shown on output UI - label?: ProviderLabel; +At minimum, a custom provider must implement an `id` method and a `callApi` method. - // Applied by the evaluator on provider response - transform?: string; +```javascript title="echoProvider.js" +export default class EchoProvider { + id = () => 'echo'; - // Custom delay for the provider - delay?: number; - - // Provider configuration - config?: any; - - // Optional method to customize how this provider is serialized to JSON. When JSON.stringify() is called on this provider, this method will be used instead of the default serialization behavior. - toJSON?: () => any; -} - -export interface ProviderResponse { - cached?: boolean; - cost?: number; - error?: string; - logProbs?: number[]; - metadata?: Record<string, any>; - output?: string | any; - tokenUsage?: TokenUsage; + callApi = async (prompt, context, options) => { + return { + output: `Echo: ${prompt}`, + }; + }; } ``` -See also: [ProviderResponse](/docs/configuration/reference/#providerresponse) - -## Example +You can optionally use a constructor to initialize the provider, for example: -Here's an example of a custom API provider that returns a predefined output along with token usage: +```javascript title="openaiProvider.js" +const promptfoo = require('promptfoo').default; -```javascript -class CustomApiProvider { +module.exports = class OpenAIProvider { constructor(options) { - // Provider ID can be overridden by the config file (e.g. when using multiple of the same provider) - this.providerId = options.id || 'custom provider'; - - // options.config contains any custom options passed to the provider + this.providerId = options.id || 'openai-custom'; this.config = options.config; } id() { return this.providerId; } - async callApi(prompt, context) { - // Add your custom API logic here - // Use options like: `this.config.temperature`, `this.config.max_tokens`, etc. - - console.log('Vars for this test case:', JSON.stringify(context.vars)); + async callApi(prompt, context, options) { + const { data } = await promptfoo.cache.fetchWithCache( + 'https://api.openai.com/v1/chat/completions', + { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + Authorization: `Bearer ${process.env.OPENAI_API_KEY}`, + }, + body: JSON.stringify({ + model: this.config?.model || 'gpt-4o-mini', + messages: [{ role: 'user', content: prompt }], + max_tokens: this.config?.max_tokens || 1024, + temperature: this.config?.temperature || 0, + }), + }, + ); return { - // Required - output: 'Model output', - - // Optional - tokenUsage: { - total: 10, - prompt: 5, - completion: 5, - }, + output: data.choices[0].message.content, + tokenUsage: data.usage, }; } -} +}; +``` + +`callApi` returns a `ProviderResponse` object. The `ProviderResponse` object format: -module.exports = CustomApiProvider; +```javascript +{ + // main response shown to users + output: "Model response - can be text or structured data", + error: "Error message if applicable", + tokenUsage: { + total: 100, + prompt: 50, + completion: 50, + }, + cost: 0.002, + cached: false, + metadata: {}, // Additional data + ... +} ``` -Custom API providers can also be used for embeddings, classification, similarity, or moderation. +### Context Parameter + +The `context` parameter contains: ```javascript -module.exports = class CustomApiProvider { +{ + vars: {}, // Test case variables + prompt: {}, // Original prompt template + originalProvider: {}, // Used when provider is overridden + logger: {} // Winston logger instance +} +``` + +### Two-Stage Provider + +```javascript title="twoStageProvider.js" +const promptfoo = require('promptfoo').default; + +module.exports = class TwoStageProvider { constructor(options) { - this.providerId = options.id || 'custom provider'; + this.providerId = options.id || 'two-stage'; this.config = options.config; } id() { return this.providerId; } - // Embeddings - async callEmbeddingApi(prompt) { - // Add your custom embedding logic here - return { - embedding: [], // Your embedding array - tokenUsage: { total: 10, prompt: 1, completion: 0 }, - }; - } + async callApi(prompt) {
For consistency with other examples, update the `Two-Stage Provider's` `callApi` signature to include optional `context` and `options` parameters or document the deviation. ```suggestion async callApi(prompt, context = {}, options = {}) { ```
promptfoo
github_2023
others
3,273
promptfoo
ellipsis-dev[bot]
@@ -868,9 +868,7 @@ }, { "type": "object", - "additionalProperties": { - "type": "string" - } + "additionalProperties": {}
Relaxing `additionalProperties` to `{}` lets non-string values pass, since transformation is handled later. Ensure consumers expect transformed strings.
promptfoo
github_2023
typescript
3,273
promptfoo
ellipsis-dev[bot]
@@ -825,7 +825,9 @@ export const TestSuiteConfigSchema = z.object({ nunjucksFilters: z.record(z.string(), z.string()).optional(), // Envvar overrides - env: z.union([ProviderEnvOverridesSchema, z.record(z.string(), z.string())]).optional(), + env: z + .union([ProviderEnvOverridesSchema, z.record(z.string(), z.any().transform(String))])
Consider checking for null/undefined when using `z.any().transform(String)` to convert env var values. ```suggestion .union([ProviderEnvOverridesSchema, z.record(z.string(), z.any().transform(value => value == null ? '' : String(value)))]) ```
promptfoo
github_2023
typescript
3,283
promptfoo
ellipsis-dev[bot]
@@ -54,24 +55,32 @@ class GoogleGenericProvider implements ApiProvider { } getApiHost(): string | undefined { - return ( + const apiHost = ( this.config.apiHost || this.env?.GOOGLE_API_HOST || this.env?.PALM_API_HOST || getEnvString('GOOGLE_API_HOST') || getEnvString('PALM_API_HOST') || DEFAULT_API_HOST ); + if (apiHost) { + return getNunjucksEngine().renderString(apiHost, {});
Consider handling errors from `getNunjucksEngine.renderString` in case template processing fails. This would avoid potential runtime issues if the provided template is malformed.
promptfoo
github_2023
typescript
3,283
promptfoo
ellipsis-dev[bot]
@@ -54,24 +55,32 @@ } getApiHost(): string | undefined { - return ( + const apiHost = ( this.config.apiHost || this.env?.GOOGLE_API_HOST || this.env?.PALM_API_HOST || getEnvString('GOOGLE_API_HOST') || getEnvString('PALM_API_HOST') || DEFAULT_API_HOST ); + if (apiHost) { + return getNunjucksEngine().renderString(apiHost, {});
Consider passing a context with environment variables or relevant data into `renderString` instead of an empty object, to fully enable templating for credentials. ```suggestion return getNunjucksEngine().renderString(apiHost, this.env || {}); ```
promptfoo
github_2023
typescript
3,282
promptfoo
ellipsis-dev[bot]
@@ -15,9 +15,10 @@ export function createXAIProvider( const xaiConfig = { ...options, config: { - ...options.config, - apiBaseUrl: 'https://api.x.ai/v1', + // Only set default URL if not already provided in config + apiBaseUrl: options.config?.config?.apiBaseUrl || 'https://api.x.ai/v1',
Incorrect property access for custom `apiBaseUrl`. Use `options.config?.apiBaseUrl` instead of `options.config?.config?.apiBaseUrl` as tests provide `apiBaseUrl` directly in `config`. ```suggestion apiBaseUrl: options.config?.apiBaseUrl || 'https://api.x.ai/v1', ```
promptfoo
github_2023
go
3,226
promptfoo
ellipsis-dev[bot]
@@ -10,22 +10,16 @@ import ( "github.com/promptfoo/promptfoo/examples/golang-provider/pkg1" ) -// client is the OpenAI API client instance used for all requests +// client is the shared OpenAI client instance used for all requests. var client = core.NewClient() // handlePrompt processes a prompt with configurable reasoning effort. -// It accepts: -// - prompt: the input text to send to the model -// - options: configuration map containing reasoning_effort setting -// - ctx: additional context (currently unused) -// -// Returns a map containing the "output" key with the model's response, -// or an error if the API call fails. +// It extracts the reasoning_effort from options (defaulting to pkg1's default) +// and calls the OpenAI API through the core client. func handlePrompt(prompt string, options map[string]interface{}, ctx map[string]interface{}) (map[string]interface{}, error) { - // Get reasoning_effort from config, default to pkg1's default if not specified reasoningEffort := pkg1.GetDefaultReasoningEffort() - if mode, ok := options["config"].(map[string]interface{})["reasoning_effort"].(string); ok { - reasoningEffort = mode + if val, ok := options["config"].(map[string]interface{})["reasoning_effort"].(string); ok {
Chained type assertions (options["config"].(map[string]interface{})["reasoning_effort"]) could panic if 'config' is missing or malformed. Consider checking that 'config' exists before asserting.
promptfoo
github_2023
typescript
3,226
promptfoo
ellipsis-dev[bot]
@@ -102,44 +102,55 @@ export class GolangProvider implements ApiProvider { try { // Create temp directory tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'golang-provider-')); + logger.debug(`Created temp directory: ${tempDir}`); + + // Create provider subdirectory + const providerDir = path.join(tempDir, 'provider'); + fs.mkdirSync(providerDir, { recursive: true }); + logger.debug(`Created provider subdirectory: ${providerDir}`); + + // Copy the script to provider directory with original name + const tempProviderPath = path.join(providerDir, path.basename(absPath)); + fs.copyFileSync(absPath, tempProviderPath); + logger.debug(`Copied ${path.basename(absPath)} to: ${tempProviderPath}`); + + // Ensure the provider file has the correct package declaration + let providerContent = fs.readFileSync(tempProviderPath, 'utf8'); + if (!providerContent.startsWith('package provider')) { + providerContent = providerContent.replace(/package\s+main/, 'package provider'); + fs.writeFileSync(tempProviderPath, providerContent); + } - // Helper function to copy directory recursively - const copyDir = (src: string, dest: string) => { - fs.mkdirSync(dest, { recursive: true }); - const entries = fs.readdirSync(src, { withFileTypes: true }); - for (const entry of entries) { - const srcPath = path.join(src, entry.name); - const destPath = path.join(dest, entry.name); - if (entry.isDirectory()) { - copyDir(srcPath, destPath); - } else { - fs.copyFileSync(srcPath, destPath); - } - } - }; - - // Copy the entire module structure - copyDir(moduleRoot, tempDir); - - const relativeScriptPath = path.relative(moduleRoot, absPath); - const scriptDir = path.dirname(path.join(tempDir, relativeScriptPath)); - - // Copy wrapper.go to the same directory as the script - const tempWrapperPath = path.join(scriptDir, 'wrapper.go'); - fs.mkdirSync(scriptDir, { recursive: true }); + // Copy wrapper.go to temp directory + const tempWrapperPath = path.join(tempDir, 'wrapper.go'); fs.copyFileSync(path.join(__dirname, '../golang/wrapper.go'), tempWrapperPath); + logger.debug(`Copied wrapper.go to: ${tempWrapperPath}`); + + // Create go.mod in temp directory + logger.debug('Creating go.mod file'); + const goModContent = `module tempmod + +go 1.21 + +require github.com/sashabaranov/go-openai v1.17.9 +`; + fs.writeFileSync(path.join(tempDir, 'go.mod'), goModContent); + + // Run go mod tidy + logger.debug('Running go mod tidy'); + await execAsync(`cd ${tempDir} && ${this.config.goExecutable || 'go'} mod tidy`);
Consider quoting the temporary directory path in the exec commands to handle potential spaces in paths. ```suggestion await execAsync(`cd "${tempDir}" && ${this.config.goExecutable || 'go'} mod tidy`); ```
promptfoo
github_2023
typescript
3,226
promptfoo
ellipsis-dev[bot]
@@ -102,44 +102,55 @@ try { // Create temp directory tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'golang-provider-')); + logger.debug(`Created temp directory: ${tempDir}`); + + // Create provider subdirectory + const providerDir = path.join(tempDir, 'provider'); + fs.mkdirSync(providerDir, { recursive: true }); + logger.debug(`Created provider subdirectory: ${providerDir}`); + + // Copy the script to provider directory with original name + const tempProviderPath = path.join(providerDir, path.basename(absPath)); + fs.copyFileSync(absPath, tempProviderPath); + logger.debug(`Copied ${path.basename(absPath)} to: ${tempProviderPath}`); + + // Ensure the provider file has the correct package declaration + let providerContent = fs.readFileSync(tempProviderPath, 'utf8'); + if (!providerContent.startsWith('package provider')) { + providerContent = providerContent.replace(/package\s+main/, 'package provider'); + fs.writeFileSync(tempProviderPath, providerContent); + } - // Helper function to copy directory recursively - const copyDir = (src: string, dest: string) => { - fs.mkdirSync(dest, { recursive: true }); - const entries = fs.readdirSync(src, { withFileTypes: true }); - for (const entry of entries) { - const srcPath = path.join(src, entry.name); - const destPath = path.join(dest, entry.name); - if (entry.isDirectory()) { - copyDir(srcPath, destPath); - } else { - fs.copyFileSync(srcPath, destPath); - } - } - }; - - // Copy the entire module structure - copyDir(moduleRoot, tempDir); - - const relativeScriptPath = path.relative(moduleRoot, absPath); - const scriptDir = path.dirname(path.join(tempDir, relativeScriptPath)); - - // Copy wrapper.go to the same directory as the script - const tempWrapperPath = path.join(scriptDir, 'wrapper.go'); - fs.mkdirSync(scriptDir, { recursive: true }); + // Copy wrapper.go to temp directory + const tempWrapperPath = path.join(tempDir, 'wrapper.go'); fs.copyFileSync(path.join(__dirname, '../golang/wrapper.go'), tempWrapperPath); + logger.debug(`Copied wrapper.go to: ${tempWrapperPath}`); + + // Create go.mod in temp directory + logger.debug('Creating go.mod file'); + const goModContent = `module tempmod + +go 1.21 + +require github.com/sashabaranov/go-openai v1.17.9 +`; + fs.writeFileSync(path.join(tempDir, 'go.mod'), goModContent); + + // Run go mod tidy + logger.debug('Running go mod tidy'); + await execAsync(`cd ${tempDir} && ${this.config.goExecutable || 'go'} mod tidy`); const executablePath = path.join(tempDir, 'golang_wrapper'); - const tempScriptPath = path.join(tempDir, relativeScriptPath); - // Build from the script directory - const compileCommand = `cd ${scriptDir} && ${this.config.goExecutable || 'go'} build -o ${executablePath} wrapper.go ${path.basename(relativeScriptPath)}`; + // Build from the temp directory + const compileCommand = `cd ${tempDir} && ${this.config.goExecutable || 'go'} build -o ${executablePath} .`;
Similarly, consider quoting paths (like tempDir and executablePath) in the build command to prevent issues if the paths contain spaces. ```suggestion const compileCommand = `cd "${tempDir}" && ${this.config.goExecutable || 'go'} build -o "${executablePath}" .`; ```
promptfoo
github_2023
go
3,226
promptfoo
ellipsis-dev[bot]
@@ -0,0 +1,77 @@ +package main + +import ( + "encoding/json" + "fmt" + "os" + "reflect" +) + +// CallApi is the provider's implementation of promptfoo's API interface. +// It processes prompts with configurable reasoning effort and returns the model's response. +// +// The prompt parameter is the input text to send to the model. +// The options parameter may contain a config map with a "reasoning_effort" key +// that accepts "low", "medium", or "high" values. +// +// Returns a map containing the "output" key with the model's response, +// or an error if the API call fails. +type ApiFunc func(string, map[string]interface{}, map[string]interface{}) (map[string]interface{}, error) + +// Default implementation that will be replaced by the actual provider +func defaultCallApi(prompt string, options map[string]interface{}, ctx map[string]interface{}) (map[string]interface{}, error) { + return nil, fmt.Errorf("CallApi not implemented") +} + +var CallApi ApiFunc = defaultCallApi + +func main() { + if len(os.Args) != 4 { + fmt.Println("Usage: golang_wrapper <script_path> <function_name> <json_args>") + os.Exit(1) + } + + functionName := os.Args[2] + jsonArgs := os.Args[3] + + // Parse the JSON arguments + var args []interface{} + err := json.Unmarshal([]byte(jsonArgs), &args) + if err != nil { + fmt.Printf("Error parsing JSON arguments: %v\n", err) + os.Exit(1) + } + + // Get the function by name using reflection + f := reflect.ValueOf(nil) + switch functionName { + case "call_api", "CallApi": + f = reflect.ValueOf(CallApi) + default: + fmt.Printf("Unknown function: %s\n", functionName) + os.Exit(1) + } + + // Call the function + result := f.Call([]reflect.Value{ + reflect.ValueOf(args[0].(string)),
Ensure that the parsed JSON args length is validated before accessing indices 0-2, to avoid potential panics on unexpected input.
promptfoo
github_2023
typescript
3,272
promptfoo
ellipsis-dev[bot]
@@ -128,6 +130,7 @@ const PluginTable = ({ {shouldRenderDescription && ( <td style={{ ...styles.td, ...styles.columns.description }}> {plugin.description} + {showRemoteStatus && plugin.isRemote && ' 🌐'}
In the grouped plugins block, the remote status is conditionally rendered using both `showRemoteStatus` and `plugin.isRemote`. Consider wrapping the icon in a `<span>` with a title for consistency with the non-grouped block. ```suggestion {showRemoteStatus && plugin.isRemote && <span title="Uses remote inference"> 🌐</span>} ```
promptfoo
github_2023
typescript
3,272
promptfoo
ellipsis-dev[bot]
@@ -157,7 +160,12 @@ <td style={styles.td}> <a href={plugin.link}>{plugin.name}</a> </td> - {shouldRenderDescription && <td style={styles.td}>{plugin.description}</td>} + {shouldRenderDescription && ( + <td style={styles.td}> + {plugin.description} + {plugin.isRemote && <span title="Uses remote inference"> 🌐</span>}
Non-grouped plugin rows render the remote icon without checking `showRemoteStatus`. It should conditionally display the icon based on `showRemoteStatus` for consistency. ```suggestion {showRemoteStatus && plugin.isRemote && <span title="Uses remote inference"> 🌐</span>} ```
promptfoo
github_2023
typescript
3,239
promptfoo
ellipsis-dev[bot]
@@ -153,7 +153,22 @@ export async function renderPrompt( if (typeof result === 'string') { basePrompt = result; } else if (typeof result === 'object') { - basePrompt = JSON.stringify(result); + // Check if it's using the structured PromptFunctionResult format + if ('prompt' in result) { + basePrompt = + typeof result.prompt === 'string' ? result.prompt : JSON.stringify(result.prompt); + + // Merge config if provided + if (result.config) { + prompt.config = { + ...prompt.config,
When merging provider config from prompt functions, consider defaulting to an empty object in case prompt.config is undefined (e.g. use `{ ...(prompt.config || {}), ...result.config }`) to avoid runtime errors. ```suggestion ...(prompt.config || {}), ```
promptfoo
github_2023
others
3,239
promptfoo
ellipsis-dev[bot]
@@ -252,6 +256,31 @@ if __name__ == "__main__": print(my_prompt_function(json.loads(sys.argv[1]))) ``` +A Python prompt function `prompt_with_config.py:my_prompt_function` that returns both prompt content and provider configuration: + +````python title=prompt_with_config.py
It looks like the code fence for the Python prompt function example (`prompt_with_config.py`) starts with four backticks (````python) but ends with only three (```). To ensure the markdown renders correctly, please adjust the opening fence to use three backticks, matching the closing fence. ```suggestion ```python title=prompt_with_config.py ```
promptfoo
github_2023
others
3,262
promptfoo
mldangelo
@@ -0,0 +1,17 @@ +# yaml-language-server: $schema=https://promptfoo.dev/config-schema.json +description: 'Bedrock Nova Eval with Images' + +prompts: + - file://nova_multimodal_prompt.json + +providers: + - id: bedrock:amazon.nova-pro-v1:0 + config: + region: 'us-east-1' + inferenceConfig: + temperature: 0.7 + max_new_tokens: 256 + +tests: + - vars: + image: file://cat.jpg
don't leave us hanging! Add a cat image!
promptfoo
github_2023
others
3,262
promptfoo
mldangelo
@@ -548,6 +548,86 @@ module.exports = (output, { vars }) => { }; ``` +### Loading images and other file types + +Promptfoo supports loading various file types as variables in your prompts: + +```yaml title="promptfooconfig.yaml" +tests: + - vars: + text_file: file://path/to/text.txt + yaml_file: file://path/to/data.yaml + pdf_document: file://path/to/document.pdf + image: file://path/to/image.png + video: file://path/to/video.mp4 +``` + +When loading files as variables: + +- **Text files** are loaded as plain text +- **YAML/YML files** are loaded as JSON strings +- **PDF files** are parsed to extract text (requires `pdf-parse` package) +- **Image files** (jpg, jpeg, png, gif, bmp, webp, svg) are loaded as base64 strings +- **Video files** (mp4, webm, ogg, mov, avi, wmv, mkv, m4v) are loaded as base64 strings + +This is particularly useful for multimodal models that can process text, images, and videos. For example, to include an image in a prompt for a vision model: + +```yaml title="promptfooconfig.yaml" +prompts: + - |- + [ + { + "role": "user", + "content": [ + { + "type": "text", + "text": "Describe what you see in this image:" + }, + { + "type": "image_url", + "image_url": { + "url": "data:image/jpeg;base64,{{image}}" + } + } + ] + } + ] + +tests: + - vars: + image: file://path/to/image.jpg +``` + +Similarly, for video content: + +```yaml title="promptfooconfig.yaml" +prompts: + - |- + [ + { + "role": "user", + "content": [ + { + "type": "text", + "text": "Describe what happens in this video:" + }, + { + "type": "video_url", + "video_url": { + "url": "data:video/mp4;base64,{{video}}" + } + } + ] + } + ] + +tests: + - vars: + video: file://path/to/video.mp4 +``` + +The media files will be automatically loaded and converted to base64 strings that can be used directly in your prompts for multimodal models.
nit, consider adding a note about how to disable
promptfoo
github_2023
typescript
3,262
promptfoo
mldangelo
@@ -18,6 +18,18 @@ import invariant from './util/invariant'; import { getNunjucksEngine } from './util/templates'; import { transform } from './util/transform'; +function isImageFile(filePath: string): boolean {
nit, move into src/util/file.ts
promptfoo
github_2023
others
3,262
promptfoo
mldangelo
@@ -548,6 +548,88 @@ module.exports = (output, { vars }) => { }; ``` +### Loading images and other file types + +Promptfoo supports loading various file types as variables in your prompts: + +```yaml title="promptfooconfig.yaml" +tests: + - vars: + text_file: file://path/to/text.txt + yaml_file: file://path/to/data.yaml + pdf_document: file://path/to/document.pdf + image: file://path/to/image.png + video: file://path/to/video.mp4 +``` + +When loading files as variables: + +- **Text files** are loaded as plain text +- **YAML/YML files** are loaded as JSON strings +- **PDF files** are parsed to extract text (requires `pdf-parse` package) +- **Image files** (jpg, jpeg, png, gif, bmp, webp, svg) are loaded as base64 strings +- **Video files** (mp4, webm, ogg, mov, avi, wmv, mkv, m4v) are loaded as base64 strings + +This is particularly useful for multimodal models that can process text, images, and videos. For example, to include an image in a prompt for a vision model: + +```yaml title="promptfooconfig.yaml" +prompts: + - |- + [ + { + "role": "user", + "content": [ + { + "type": "text", + "text": "Describe what you see in this image:" + }, + { + "type": "image_url", + "image_url": { + "url": "data:image/jpeg;base64,{{image}}" + } + } + ] + } + ] + +tests: + - vars: + image: file://path/to/image.jpg +``` + +Similarly, for video content: + +```yaml title="promptfooconfig.yaml" +prompts: + - |- + [ + { + "role": "user", + "content": [ + { + "type": "text", + "text": "Describe what happens in this video:" + }, + { + "type": "video_url", + "video_url": { + "url": "data:video/mp4;base64,{{video}}" + } + } + ] + } + ] + +tests: + - vars: + video: file://path/to/video.mp4 +``` + +The media files will be automatically loaded and converted to base64 strings that can be used directly in your prompts for multimodal models. + +To disable this behavior, set the `PROMPTFOO_DISABLE_MULTIMEDIA_AS_BASE64` environment variable to `false`.
TRUE!!!
promptfoo
github_2023
javascript
3,268
promptfoo
mldangelo
@@ -175,7 +175,7 @@ const config = { label: 'Docs', }, { - href: 'https://promptfoo.dev/models/', + href: '/models/',
will break docusaurus
promptfoo
github_2023
typescript
3,252
promptfoo
ellipsis-dev[bot]
@@ -153,6 +153,30 @@ const PressContent = () => { Featured Podcasts </Typography> <Grid container spacing={4} mb={6}> + <Grid item xs={12} md={6}> + <Box + className={styles.coverageItem} + p={3} + sx={{ height: '100%', display: 'flex', flexDirection: 'column' }} + > + <Typography variant="h6" component="h4" gutterBottom> + What DeepSeek Means for Cybersecurity + </Typography> + <Typography variant="subtitle2" color="text.secondary" gutterBottom> + AI + a16z • February 28, 2025 + </Typography> + <Typography variant="body2" paragraph sx={{ flex: 1 }}> + In this episode, a16z partner Joel de la Garza speaks with a trio of security + experts, including Promptfoo founder Ian Webster, about the security implications + of the DeepSeek reasoning model. Ian's segment focuses on vulnerabilities within + DeepSeek itself, and how users can protect themselves against backdoors, + jailbreaks, and censorship. + </Typography> + <Link href="https://open.spotify.com/episode/6dgcEOdie8Mtl5COJjjHFy">
Consider adding target="_blank" and rel="noopener noreferrer" to the external Spotify link for security. ```suggestion <Link href="https://open.spotify.com/episode/6dgcEOdie8Mtl5COJjjHFy" target="_blank" rel="noopener noreferrer"> ```
promptfoo
github_2023
typescript
3,242
promptfoo
ellipsis-dev[bot]
@@ -50,42 +59,42 @@ export default function ExtensionEditor({ onExtensionsChange, onValidationChange, }: ExtensionEditorProps) { - const [value, setValue] = React.useState(''); - - React.useEffect(() => { - if (extensions.length > 0) { - setValue(extensions[0].replace(FILE_PROTOCOL_PREFIX, '')); - } else { - setValue(''); - } - }, [extensions]); + const [isTyping, setIsTyping] = React.useState(false); + const typingTimeoutRef = React.useRef<ReturnType<typeof setTimeout>>(); - const error = React.useMemo(() => validatePath(value), [value]); - - React.useEffect(() => { - onValidationChange?.(!!error); - }, [error, onValidationChange]); + const error = React.useMemo(() => validatePath(extensions[0], isTyping), [extensions, isTyping]); const handleChange = React.useCallback( (e: React.ChangeEvent<HTMLInputElement>) => { const newValue = e.target.value; - setValue(newValue); + setIsTyping(true); - if (!newValue.trim()) { - onExtensionsChange([]); - return; + // Clear any existing timeout + if (typingTimeoutRef.current) { + clearTimeout(typingTimeoutRef.current); } - const validationResult = validatePath(newValue); - if (validationResult === undefined) { - onExtensionsChange([`${FILE_PROTOCOL_PREFIX}${newValue}`]); - } else { - // Invalid input: Parent state is not updated, error will be shown via onValidationChange - } + // Set a new timeout to mark typing as finished + typingTimeoutRef.current = setTimeout(() => { + setIsTyping(false); + }, 500); + const validationResult = validatePath(newValue, true); + onValidationChange?.(!!validationResult); + + onExtensionsChange([`${FILE_PROTOCOL_PREFIX}${newValue}`]); }, [onExtensionsChange],
Include onValidationChange in the dependency array for the handleChange callback to avoid potential stale closures. ```suggestion [onExtensionsChange, onValidationChange], ```
promptfoo
github_2023
typescript
3,248
promptfoo
ellipsis-dev[bot]
@@ -10,97 +8,266 @@ import type { } from '../../types'; import { REQUEST_TIMEOUT_MS } from '../shared'; +export const OPENAI_MODERATION_MODELS = [ + { id: 'omni-moderation-latest', maxTokens: 32768, capabilities: ['text', 'image'] }, + { id: 'omni-moderation-2024-09-26', maxTokens: 32768, capabilities: ['text', 'image'] }, + { id: 'text-moderation-latest', maxTokens: 32768, capabilities: ['text'] }, + { id: 'text-moderation-stable', maxTokens: 32768, capabilities: ['text'] }, + { id: 'text-moderation-007', maxTokens: 32768, capabilities: ['text'] }, +]; + +export type OpenAIModerationModelId = string; + +// Define category names as a union type +export type ModerationCategory = + | 'sexual' + | 'sexual/minors' + | 'harassment' + | 'harassment/threatening' + | 'hate' + | 'hate/threatening' + | 'illicit' + | 'illicit/violent' + | 'self-harm' + | 'self-harm/intent' + | 'self-harm/instructions' + | 'violence' + | 'violence/graphic'; + +// Simplified type definitions using mapped types +type OpenAIModerationCategories = Record<ModerationCategory | string, boolean>; +type OpenAIModerationCategoryScores = Record<ModerationCategory | string, number>; +type OpenAIModerationCategoryAppliedInputTypes = Record< + ModerationCategory | string, + string[] | undefined +>; + +interface OpenAIModerationResult { + flagged: boolean; + categories: OpenAIModerationCategories; + category_scores: OpenAIModerationCategoryScores; + category_applied_input_types?: OpenAIModerationCategoryAppliedInputTypes; +} + +interface OpenAIModerationResponse { + id: string; + model: string; + results: OpenAIModerationResult[]; +} + +export type TextInput = { + type: 'text'; + text: string; +}; + +export type ImageInput = { + type: 'image_url'; + image_url: { + url: string; + }; +}; + +export type ModerationInput = string | (TextInput | ImageInput)[]; + +// Type guards for better type safety +export function isTextInput(input: TextInput | ImageInput): input is TextInput { + return input.type === 'text'; +} + +export function isImageInput(input: TextInput | ImageInput): input is ImageInput { + return input.type === 'image_url'; +} + +export interface OpenAIModerationConfig { + apiKey?: string; + headers?: Record<string, string>; + passthrough?: Record<string, any>; +} + +// Standalone utility functions + +/** + * Parse OpenAI moderation API response into standardized format + */ +function parseOpenAIModerationResponse(data: OpenAIModerationResponse): ProviderModerationResponse { + const { results } = data; + + if (!results || results.length === 0) { + return { flags: [] }; + } + + const flags: ModerationFlag[] = []; + for (const result of results) { + if (result.flagged) { + for (const [category, flagged] of Object.entries(result.categories)) { + if (flagged) { + const appliedTo = result.category_applied_input_types?.[category]; + flags.push({ + code: category, + description: category + (appliedTo ? ` (applied to: ${appliedTo.join(', ')})` : ''), + confidence: result.category_scores[category], + }); + } + } + } + } + + return { flags }; +} + +/** + * Format API error response + */ +function handleApiError(err: any, data?: any): ProviderModerationResponse { + logger.error(`API error: ${String(err)}`); + return { + error: data + ? `API error: ${String(err)}: ${typeof data === 'string' ? data : JSON.stringify(data)}` + : `API call error: ${String(err)}`, + }; +} + +/** + * Generate cache key for a moderation request + */ +function getModerationCacheKey( + modelName: string, + config: any, + content: string | (TextInput | ImageInput)[], +): string { + const contentKey = typeof content === 'string' ? content : JSON.stringify(content); + return `openai:moderation:${modelName}:${JSON.stringify(config)}:${contentKey}`; +} + +/** + * Check if the moderation model supports image input + */ +export function supportsImageInput(modelName: string): boolean { + const model = OPENAI_MODERATION_MODELS.find((model) => model.id === modelName); + return model?.capabilities.includes('image') ?? false; +} + +/** + * Format content based on model capabilities + */ +export function formatModerationInput( + content: string | (TextInput | ImageInput)[], + supportsImages: boolean, +): ModerationInput { + // For string input, wrap in array if model supports images + if (typeof content === 'string') { + return supportsImages ? [{ type: 'text', text: content }] : content; + } + + // For array input, filter out images if model doesn't support them + if (!supportsImages) { + logger.warn('Using image inputs with a text-only moderation model. Images will be ignored.'); + const textContent = content + .filter(isTextInput) + .map((item) => item.text) + .join(' '); + return textContent; + } + + return content; +} + export class OpenAiModerationProvider extends OpenAiGenericProvider implements ApiModerationProvider { + static MODERATION_MODELS = OPENAI_MODERATION_MODELS; + static MODERATION_MODEL_IDS = OPENAI_MODERATION_MODELS.map((model) => model.id); + + constructor( + modelName: OpenAIModerationModelId = 'text-moderation-latest', + options: { config?: OpenAIModerationConfig; id?: string; env?: any } = {}, + ) { + super(modelName, options); + if (!OpenAiModerationProvider.MODERATION_MODEL_IDS.includes(modelName)) { + logger.warn(`Using unknown OpenAI moderation model: ${modelName}`); + } + } + async callModerationApi( - userPrompt: string, // userPrompt is not supported by OpenAI moderation API - assistantResponse: string, + userPrompt: string,
The 'userPrompt' parameter is not used in the API call. If it's not needed, consider removing or documenting its purpose.
promptfoo
github_2023
typescript
3,248
promptfoo
ellipsis-dev[bot]
@@ -10,97 +8,266 @@ } from '../../types'; import { REQUEST_TIMEOUT_MS } from '../shared'; +export const OPENAI_MODERATION_MODELS = [ + { id: 'omni-moderation-latest', maxTokens: 32768, capabilities: ['text', 'image'] }, + { id: 'omni-moderation-2024-09-26', maxTokens: 32768, capabilities: ['text', 'image'] }, + { id: 'text-moderation-latest', maxTokens: 32768, capabilities: ['text'] }, + { id: 'text-moderation-stable', maxTokens: 32768, capabilities: ['text'] }, + { id: 'text-moderation-007', maxTokens: 32768, capabilities: ['text'] }, +]; + +export type OpenAIModerationModelId = string; + +// Define category names as a union type +export type ModerationCategory = + | 'sexual' + | 'sexual/minors' + | 'harassment' + | 'harassment/threatening' + | 'hate' + | 'hate/threatening' + | 'illicit' + | 'illicit/violent' + | 'self-harm' + | 'self-harm/intent' + | 'self-harm/instructions' + | 'violence' + | 'violence/graphic'; + +// Simplified type definitions using mapped types +type OpenAIModerationCategories = Record<ModerationCategory | string, boolean>; +type OpenAIModerationCategoryScores = Record<ModerationCategory | string, number>; +type OpenAIModerationCategoryAppliedInputTypes = Record< + ModerationCategory | string, + string[] | undefined +>; + +interface OpenAIModerationResult { + flagged: boolean; + categories: OpenAIModerationCategories; + category_scores: OpenAIModerationCategoryScores; + category_applied_input_types?: OpenAIModerationCategoryAppliedInputTypes; +} + +interface OpenAIModerationResponse { + id: string; + model: string; + results: OpenAIModerationResult[]; +} + +export type TextInput = { + type: 'text'; + text: string; +}; + +export type ImageInput = { + type: 'image_url'; + image_url: { + url: string; + }; +}; + +export type ModerationInput = string | (TextInput | ImageInput)[]; + +// Type guards for better type safety +export function isTextInput(input: TextInput | ImageInput): input is TextInput { + return input.type === 'text'; +} + +export function isImageInput(input: TextInput | ImageInput): input is ImageInput { + return input.type === 'image_url'; +} + +export interface OpenAIModerationConfig { + apiKey?: string; + headers?: Record<string, string>; + passthrough?: Record<string, any>; +} + +// Standalone utility functions + +/** + * Parse OpenAI moderation API response into standardized format + */ +function parseOpenAIModerationResponse(data: OpenAIModerationResponse): ProviderModerationResponse { + const { results } = data; + + if (!results || results.length === 0) { + return { flags: [] }; + } + + const flags: ModerationFlag[] = []; + for (const result of results) { + if (result.flagged) { + for (const [category, flagged] of Object.entries(result.categories)) { + if (flagged) { + const appliedTo = result.category_applied_input_types?.[category]; + flags.push({ + code: category, + description: category + (appliedTo ? ` (applied to: ${appliedTo.join(', ')})` : ''), + confidence: result.category_scores[category], + }); + } + } + } + } + + return { flags }; +} + +/** + * Format API error response + */ +function handleApiError(err: any, data?: any): ProviderModerationResponse { + logger.error(`API error: ${String(err)}`); + return { + error: data + ? `API error: ${String(err)}: ${typeof data === 'string' ? data : JSON.stringify(data)}` + : `API call error: ${String(err)}`, + }; +} + +/** + * Generate cache key for a moderation request + */ +function getModerationCacheKey( + modelName: string, + config: any, + content: string | (TextInput | ImageInput)[], +): string { + const contentKey = typeof content === 'string' ? content : JSON.stringify(content); + return `openai:moderation:${modelName}:${JSON.stringify(config)}:${contentKey}`;
Consider using a deterministic serialization for the config object in getModerationCacheKey to ensure that equivalent configurations produce the same cache key. ```suggestion return `openai:moderation:${modelName}:${stableStringify(config)}:${contentKey}`; ```
promptfoo
github_2023
typescript
3,245
promptfoo
ellipsis-dev[bot]
@@ -32,173 +58,211 @@ export class OpenAiImageProvider extends OpenAiGenericProvider { this.config = options.config || {}; } + /** + * Validate the size parameter for the given model + */ + private validateSizeForModel(size: string, model: string): { valid: boolean; message?: string } { + if (model === 'dall-e-3') { + const validSizes: DallE3Size[] = ['1024x1024', '1792x1024', '1024x1792']; + if (!validSizes.includes(size as DallE3Size)) { + return { + valid: false, + message: `Invalid size "${size}" for DALL-E 3. Valid sizes are: ${validSizes.join(', ')}`, + }; + } + } else if (model === 'dall-e-2') { + const validSizes: DallE2Size[] = ['256x256', '512x512', '1024x1024']; + if (!validSizes.includes(size as DallE2Size)) { + return { + valid: false, + message: `Invalid size "${size}" for DALL-E 2. Valid sizes are: ${validSizes.join(', ')}`, + }; + } + } + return { valid: true }; + } + + /** + * Format the output based on the response format and data + */ + private formatOutput( + data: any, + prompt: string, + responseFormat?: string, + ): string | { error: string } { + if (responseFormat === 'b64_json') { + const b64Json = data.data[0].b64_json; + if (!b64Json) { + return { error: `No base64 image data found in response: ${JSON.stringify(data)}` }; + } + + // Return the original JSON response with base64 data + // This allows the UI to handle the data directly + return JSON.stringify(data); + } else { + // Default URL format + const url = data.data[0].url; + if (!url) { + return { error: `No image URL found in response: ${JSON.stringify(data)}` }; + } + + const sanitizedPrompt = prompt + .replace(/\r?\n|\r/g, ' ') + .replace(/\[/g, '(') + .replace(/\]/g, ')'); + const ellipsizedPrompt = ellipsize(sanitizedPrompt, 50); + + return `![${ellipsizedPrompt}](${url})`; + } + } + async callApi( prompt: string, context?: CallApiContextParams, callApiOptions?: CallApiOptionsParams, ): Promise<ProviderResponse> { - const cache = getCache(); - const cacheKey = `openai:image:${safeJsonStringify({ context, prompt })}`; - if (!this.getApiKey()) { throw new Error( 'OpenAI API key is not set. Set the OPENAI_API_KEY environment variable or add `apiKey` to the provider config.', ); } - const openai = new OpenAI({ - apiKey: this.getApiKey(), - organization: this.getOrganization(), - baseURL: this.getApiUrl(), - maxRetries: 3, - timeout: REQUEST_TIMEOUT_MS, - defaultHeaders: this.config.headers, - }); - - let response: OpenAI.Images.ImagesResponse | undefined; - let cached = false; - if (isCacheEnabled()) { - // Try to get the cached response - const cachedResponse = await cache.get(cacheKey); - if (cachedResponse) { - logger.debug(`Retrieved cached response for ${prompt}: ${cachedResponse}`); - response = JSON.parse(cachedResponse as string) as OpenAI.Images.ImagesResponse; - cached = true; - } - } + // Merge configs from the provider and the prompt + const config = { + ...this.config, + ...context?.prompt?.config, + }; - if (!response) { - response = await openai.images.generate({ - model: this.modelName, - prompt, - n: 1, - size: - ((this.config.size || process.env.OPENAI_IMAGE_SIZE) as - | '1024x1024' - | '256x256' - | '512x512' - | '1792x1024' - | '1024x1792' - | undefined) || '1024x1024', - }); - } - const url = response.data[0].url; - if (!url) { + // Check model and set default if not provided + const model = config.model || this.modelName; + const operation = ('operation' in config && config.operation) || 'generation'; + + // Set default response format + const responseFormat = config.response_format || 'url'; + + // Set the API endpoint based on the operation + let endpoint = '/images/generations'; + if (model === 'dall-e-2') { + if (operation === 'variation') { + endpoint = '/images/variations'; + } else if (operation === 'edit') { + endpoint = '/images/edits'; + } + } else if (operation !== 'generation') { return { - error: `No image URL found in response: ${JSON.stringify(response)}`, + error: `Operation ${operation} is only supported for dall-e-2 model.`, }; } - if (!cached && isCacheEnabled()) { - try { - await cache.set(cacheKey, JSON.stringify(response)); - } catch (err) { - logger.error(`Failed to cache response: ${String(err)}`); + // For generation operation, use JSON body + if (operation === 'generation') { + // Set default size based on model + let size = config.size; + if (!size) { + size = model === 'dall-e-3' ? '1024x1024' : '1024x1024';
The default size assignment is redundant as both branches for DALL-E 3 and DALL-E 2 yield '1024x1024'. Confirm if different defaults were intended. ```suggestion size = '1024x1024'; ```
promptfoo
github_2023
others
3,245
promptfoo
ellipsis-dev[bot]
@@ -1,13 +1,30 @@ # yaml-language-server: $schema=https://promptfoo.dev/config-schema.json prompts: - - 'In the style of Van Gogh: {{subject}}' - - 'In the style of Dali: {{subject}}' + - 'In the style of {{artist}}: {{subject}}' providers: - - openai:image:dall-e-3 + - id: openai:image:dall-e-3 + config: + size: 1024x1024 # Valid sizes for DALL-E 3: 1024x1024, 1792x1024, 1024x1792 + + - id: openai:image:dall-e-2 + config: + size: 512x512 # Valid sizes for DALL-E 2: 256x256, 512x512, 1024x1024 + # response_format: b64_json # Returns the raw JSON response with base64-encoded image data
Consider removing the commented-out 'response_format' setting if it's no longer used to reduce confusion. ```suggestion ```
promptfoo
github_2023
typescript
3,234
promptfoo
ellipsis-dev[bot]
@@ -14,10 +14,17 @@ import invariant from '../util/invariant'; export { determineShareDomain } from '../share'; -export async function createPublicUrl(evalRecord: Eval, showAuth: boolean) { +export async function createAndDisplayShareableUrl( + evalRecord: Eval, + showAuth: boolean, +): Promise<string | null> { const url = await createShareableUrl(evalRecord, showAuth); - logger.info(`View results: ${chalk.greenBright.bold(url)}`); + if (url) { + logger.info(`View results: ${chalk.greenBright.bold(url)}`); + } else { + logger.error('Failed to create shareable URL');
Consider if a failure to create a URL should also exit the process (or propagate an error) to signal failure more explicitly in CLI context.
promptfoo
github_2023
typescript
3,215
promptfoo
ellipsis-dev[bot]
@@ -461,124 +477,156 @@ export class VertexChatProvider extends VertexGenericProvider { tokenUsage.cached = tokenUsage.total; } logger.debug(`Returning cached response: ${cachedResponse}`); - return { ...parsedCachedResponse, cached: true }; + response = { ...parsedCachedResponse, cached: true }; } } - let data; - try { - const { client, projectId } = await getGoogleClient(); - const url = `https://${this.getApiHost()}/${this.getApiVersion()}/projects/${projectId}/locations/${this.getRegion()}/publishers/${this.getPublisher()}/models/${ - this.modelName - }:streamGenerateContent`; - const res = await client.request({ - url, - method: 'POST', - data: body, - timeout: REQUEST_TIMEOUT_MS, - }); - data = res.data as GeminiApiResponse; - logger.debug(`Gemini API response: ${JSON.stringify(data)}`); - } catch (err) { - const geminiError = err as GaxiosError; - if ( - geminiError.response && - geminiError.response.data && - geminiError.response.data[0] && - geminiError.response.data[0].error - ) { - const errorDetails = geminiError.response.data[0].error; - const code = errorDetails.code; - const message = errorDetails.message; - const status = errorDetails.status; - logger.debug(`Gemini API error:\n${JSON.stringify(errorDetails)}`); + if (response === undefined) { + let data; + try { + const { client, projectId } = await getGoogleClient(); + const url = `https://${this.getApiHost()}/${this.getApiVersion()}/projects/${projectId}/locations/${this.getRegion()}/publishers/${this.getPublisher()}/models/${ + this.modelName + }:streamGenerateContent`; + const res = await client.request({ + url, + method: 'POST', + data: body, + timeout: REQUEST_TIMEOUT_MS, + }); + data = res.data as GeminiApiResponse; + logger.debug(`Gemini API response: ${JSON.stringify(data)}`); + } catch (err) { + const geminiError = err as GaxiosError; + if ( + geminiError.response && + geminiError.response.data && + geminiError.response.data[0] && + geminiError.response.data[0].error + ) { + const errorDetails = geminiError.response.data[0].error; + const code = errorDetails.code; + const message = errorDetails.message; + const status = errorDetails.status; + logger.debug(`Gemini API error:\n${JSON.stringify(errorDetails)}`); + return { + error: `API call error: Status ${status}, Code ${code}, Message:\n\n${message}`, + }; + } + logger.debug(`Gemini API error:\n${JSON.stringify(err)}`); return { - error: `API call error: Status ${status}, Code ${code}, Message:\n\n${message}`, + error: `API call error: ${String(err)}`, }; } - logger.debug(`Gemini API error:\n${JSON.stringify(err)}`); - return { - error: `API call error: ${String(err)}`, - }; - } - logger.debug(`Gemini API response: ${JSON.stringify(data)}`); - try { - const dataWithError = data as GeminiErrorResponse[]; - const error = dataWithError[0]?.error; - if (error) { - return { - error: `Error ${error.code}: ${error.message}`, - }; - } - const dataWithResponse = data as GeminiResponseData[]; - let output = ''; - for (const datum of dataWithResponse) { - if (datum.candidates && datum.candidates[0]?.content?.parts) { - for (const candidate of datum.candidates) { - if (candidate.content?.parts) { - for (const part of candidate.content.parts) { - if ('text' in part) { - output += part.text; - } else { - output += JSON.stringify(part); + logger.debug(`Gemini API response: ${JSON.stringify(data)}`); + try { + const dataWithError = data as GeminiErrorResponse[]; + const error = dataWithError[0]?.error; + if (error) { + return { + error: `Error ${error.code}: ${error.message}`, + }; + } + const dataWithResponse = data as GeminiResponseData[]; + let output = ''; + for (const datum of dataWithResponse) { + if (datum.candidates && datum.candidates[0]?.content?.parts) { + for (const candidate of datum.candidates) { + if (candidate.content?.parts) { + for (const part of candidate.content.parts) { + if ('text' in part) { + output += part.text; + } else { + output += JSON.stringify(part); + } } } } + } else if (datum.candidates && datum.candidates[0]?.finishReason === 'SAFETY') { + if (cliState.config?.redteam) { + // Refusals are not errors during redteams, they're actually successes. + return { + output: 'Content was blocked due to safety settings.', + }; + } + return { + error: 'Content was blocked due to safety settings.', + }; } - } else if (datum.candidates && datum.candidates[0]?.finishReason === 'SAFETY') { + } + + if ('promptFeedback' in data[0] && data[0].promptFeedback?.blockReason) { if (cliState.config?.redteam) { // Refusals are not errors during redteams, they're actually successes. return { - output: 'Content was blocked due to safety settings.', + output: `Content was blocked due to safety settings: ${data[0].promptFeedback.blockReason}`, }; } return { - error: 'Content was blocked due to safety settings.', + error: `Content was blocked due to safety settings: ${data[0].promptFeedback.blockReason}`, }; } - } - if ('promptFeedback' in data[0] && data[0].promptFeedback?.blockReason) { - if (cliState.config?.redteam) { - // Refusals are not errors during redteams, they're actually successes. + if (!output) { return { - output: `Content was blocked due to safety settings: ${data[0].promptFeedback.blockReason}`, + error: `No output found in response: ${JSON.stringify(data)}`, }; } - return { - error: `Content was blocked due to safety settings: ${data[0].promptFeedback.blockReason}`, + + const lastData = dataWithResponse[dataWithResponse.length - 1]; + const tokenUsage = { + total: lastData.usageMetadata?.totalTokenCount || 0, + prompt: lastData.usageMetadata?.promptTokenCount || 0, + completion: lastData.usageMetadata?.candidatesTokenCount || 0, + }; + response = { + cached: false, + output, + tokenUsage, }; - } - if (!output) { + if (isCacheEnabled()) { + await cache.set(cacheKey, JSON.stringify(response)); + } + } catch (err) { return { - error: `No output found in response: ${JSON.stringify(data)}`, + error: `Gemini API response error: ${String(err)}. Response data: ${JSON.stringify(data)}`, }; } - - const lastData = dataWithResponse[dataWithResponse.length - 1]; - const tokenUsage = { - total: lastData.usageMetadata?.totalTokenCount || 0, - prompt: lastData.usageMetadata?.promptTokenCount || 0, - completion: lastData.usageMetadata?.candidatesTokenCount || 0, - }; - const response = { - cached: false, - output, - tokenUsage, - }; - - if (isCacheEnabled()) { - await cache.set(cacheKey, JSON.stringify(response)); + } + try { + // Handle function tool callbacks + if (this.config.functionToolCallbacks && isValidJson(response.output)) { + const structured_output = JSON.parse(response.output); + if (structured_output.functionCall) { + const results = []; + const functionName = structured_output.functionCall.name + if (this.config.functionToolCallbacks[functionName]) { + try { + const functionResult = await this.config.functionToolCallbacks[functionName]( + JSON.stringify(structured_output.functionCall.args), + ); + results.push(functionResult); + } catch (error) { + logger.error(`Error executing function ${functionName}: ${error}`); + } + } + if (results.length > 0) { + response = { + cached: response.cached, + output: results.join('\n'), + tokenUsage: response.tokenUsage, + } + } + } } - - return response; } catch (err) { return { - error: `Gemini API response error: ${String(err)}. Response data: ${JSON.stringify(data)}`, + error: `Tool callback error: ${String(err)}.}`,
There appears to be an extra closing curly brace in the error message template for tool callback errors. ```suggestion error: `Tool callback error: ${String(err)}`, ```
promptfoo
github_2023
typescript
3,215
promptfoo
ellipsis-dev[bot]
@@ -461,124 +477,156 @@ tokenUsage.cached = tokenUsage.total; } logger.debug(`Returning cached response: ${cachedResponse}`); - return { ...parsedCachedResponse, cached: true }; + response = { ...parsedCachedResponse, cached: true }; } } - let data; - try { - const { client, projectId } = await getGoogleClient(); - const url = `https://${this.getApiHost()}/${this.getApiVersion()}/projects/${projectId}/locations/${this.getRegion()}/publishers/${this.getPublisher()}/models/${ - this.modelName - }:streamGenerateContent`; - const res = await client.request({ - url, - method: 'POST', - data: body, - timeout: REQUEST_TIMEOUT_MS, - }); - data = res.data as GeminiApiResponse; - logger.debug(`Gemini API response: ${JSON.stringify(data)}`); - } catch (err) { - const geminiError = err as GaxiosError; - if ( - geminiError.response && - geminiError.response.data && - geminiError.response.data[0] && - geminiError.response.data[0].error - ) { - const errorDetails = geminiError.response.data[0].error; - const code = errorDetails.code; - const message = errorDetails.message; - const status = errorDetails.status; - logger.debug(`Gemini API error:\n${JSON.stringify(errorDetails)}`); + if (response === undefined) { + let data; + try { + const { client, projectId } = await getGoogleClient(); + const url = `https://${this.getApiHost()}/${this.getApiVersion()}/projects/${projectId}/locations/${this.getRegion()}/publishers/${this.getPublisher()}/models/${ + this.modelName + }:streamGenerateContent`; + const res = await client.request({ + url, + method: 'POST', + data: body, + timeout: REQUEST_TIMEOUT_MS, + }); + data = res.data as GeminiApiResponse; + logger.debug(`Gemini API response: ${JSON.stringify(data)}`); + } catch (err) { + const geminiError = err as GaxiosError; + if ( + geminiError.response && + geminiError.response.data && + geminiError.response.data[0] && + geminiError.response.data[0].error + ) { + const errorDetails = geminiError.response.data[0].error; + const code = errorDetails.code; + const message = errorDetails.message; + const status = errorDetails.status; + logger.debug(`Gemini API error:\n${JSON.stringify(errorDetails)}`); + return { + error: `API call error: Status ${status}, Code ${code}, Message:\n\n${message}`, + }; + } + logger.debug(`Gemini API error:\n${JSON.stringify(err)}`); return { - error: `API call error: Status ${status}, Code ${code}, Message:\n\n${message}`, + error: `API call error: ${String(err)}`, }; } - logger.debug(`Gemini API error:\n${JSON.stringify(err)}`); - return { - error: `API call error: ${String(err)}`, - }; - } - logger.debug(`Gemini API response: ${JSON.stringify(data)}`); - try { - const dataWithError = data as GeminiErrorResponse[]; - const error = dataWithError[0]?.error; - if (error) { - return { - error: `Error ${error.code}: ${error.message}`, - }; - } - const dataWithResponse = data as GeminiResponseData[]; - let output = ''; - for (const datum of dataWithResponse) { - if (datum.candidates && datum.candidates[0]?.content?.parts) { - for (const candidate of datum.candidates) { - if (candidate.content?.parts) { - for (const part of candidate.content.parts) { - if ('text' in part) { - output += part.text; - } else { - output += JSON.stringify(part); + logger.debug(`Gemini API response: ${JSON.stringify(data)}`); + try { + const dataWithError = data as GeminiErrorResponse[]; + const error = dataWithError[0]?.error; + if (error) { + return { + error: `Error ${error.code}: ${error.message}`, + }; + } + const dataWithResponse = data as GeminiResponseData[]; + let output = ''; + for (const datum of dataWithResponse) { + if (datum.candidates && datum.candidates[0]?.content?.parts) { + for (const candidate of datum.candidates) { + if (candidate.content?.parts) { + for (const part of candidate.content.parts) { + if ('text' in part) { + output += part.text; + } else { + output += JSON.stringify(part); + } } } } + } else if (datum.candidates && datum.candidates[0]?.finishReason === 'SAFETY') { + if (cliState.config?.redteam) { + // Refusals are not errors during redteams, they're actually successes. + return { + output: 'Content was blocked due to safety settings.', + }; + } + return { + error: 'Content was blocked due to safety settings.', + }; } - } else if (datum.candidates && datum.candidates[0]?.finishReason === 'SAFETY') { + } + + if ('promptFeedback' in data[0] && data[0].promptFeedback?.blockReason) { if (cliState.config?.redteam) { // Refusals are not errors during redteams, they're actually successes. return { - output: 'Content was blocked due to safety settings.', + output: `Content was blocked due to safety settings: ${data[0].promptFeedback.blockReason}`, }; } return { - error: 'Content was blocked due to safety settings.', + error: `Content was blocked due to safety settings: ${data[0].promptFeedback.blockReason}`, }; } - } - if ('promptFeedback' in data[0] && data[0].promptFeedback?.blockReason) { - if (cliState.config?.redteam) { - // Refusals are not errors during redteams, they're actually successes. + if (!output) { return { - output: `Content was blocked due to safety settings: ${data[0].promptFeedback.blockReason}`, + error: `No output found in response: ${JSON.stringify(data)}`, }; } - return { - error: `Content was blocked due to safety settings: ${data[0].promptFeedback.blockReason}`, + + const lastData = dataWithResponse[dataWithResponse.length - 1]; + const tokenUsage = { + total: lastData.usageMetadata?.totalTokenCount || 0, + prompt: lastData.usageMetadata?.promptTokenCount || 0, + completion: lastData.usageMetadata?.candidatesTokenCount || 0, + }; + response = { + cached: false, + output, + tokenUsage, }; - } - if (!output) { + if (isCacheEnabled()) { + await cache.set(cacheKey, JSON.stringify(response)); + } + } catch (err) { return { - error: `No output found in response: ${JSON.stringify(data)}`, + error: `Gemini API response error: ${String(err)}. Response data: ${JSON.stringify(data)}`, }; } - - const lastData = dataWithResponse[dataWithResponse.length - 1]; - const tokenUsage = { - total: lastData.usageMetadata?.totalTokenCount || 0, - prompt: lastData.usageMetadata?.promptTokenCount || 0, - completion: lastData.usageMetadata?.candidatesTokenCount || 0, - }; - const response = { - cached: false, - output, - tokenUsage, - }; - - if (isCacheEnabled()) { - await cache.set(cacheKey, JSON.stringify(response)); + } + try { + // Handle function tool callbacks + if (this.config.functionToolCallbacks && isValidJson(response.output)) { + const structured_output = JSON.parse(response.output); + if (structured_output.functionCall) { + const results = []; + const functionName = structured_output.functionCall.name + if (this.config.functionToolCallbacks[functionName]) { + try { + const functionResult = await this.config.functionToolCallbacks[functionName]( + JSON.stringify(structured_output.functionCall.args),
When handling the function callback, the code JSON.stringifies the functionCall.args before passing it to the callback. Ensure that functionCall.args is always an object; if there’s a chance it might already be a string, you could end up double-stringifying. A brief note or type check here would improve clarity. ```suggestion JSON.stringify(typeof structured_output.functionCall.args === 'string' ? JSON.parse(structured_output.functionCall.args) : structured_output.functionCall.args), ```
promptfoo
github_2023
others
3,223
promptfoo
ellipsis-dev[bot]
@@ -154,36 +162,51 @@ Export an eval record to JSON format. To export the most recent, use evalId `lat | ------------------------- | ------------------------------------------- | | `-o, --output <filepath>` | File to write. Writes to stdout by default. | -# Environment variables +## `promptfoo auth` -These general-purpose environment variables are supported: +Manage authentication for cloud features. -| Name | Description | Default | -| -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | -------------- | -| `FORCE_COLOR` | Set to 0 to disable terminal colors for printed outputs | | -| `PROMPTFOO_ASSERTIONS_MAX_CONCURRENCY` | How many assertions to run at a time | 3 | -| `PROMPTFOO_CONFIG_DIR` | Directory that stores eval history | `~/.promptfoo` | -| `PROMPTFOO_DISABLE_AJV_STRICT_MODE` | If set, disables AJV strict mode for JSON schema validation | | -| `PROMPTFOO_DISABLE_CONVERSATION_VAR` | Prevents the `_conversation` variable from being set | | -| `PROMPTFOO_DISABLE_ERROR_LOG` | Prevents error logs from being written to a file | | -| `PROMPTFOO_DISABLE_JSON_AUTOESCAPE` | If set, disables smart variable substitution within JSON prompts | | -| `PROMPTFOO_DISABLE_REF_PARSER` | Prevents JSON schema dereferencing | | -| `PROMPTFOO_DISABLE_TEMPLATING` | Disable Nunjucks rendering | | -| `PROMPTFOO_DISABLE_VAR_EXPANSION` | Prevents Array-type vars from being expanded into multiple test cases | | -| `PROMPTFOO_FAILED_TEST_EXIT_CODE` | Override the exit code when there is at least 1 test case failure or when the pass rate is below PROMPTFOO_PASS_RATE_THRESHOLD | 100 | -| `PROMPTFOO_LOG_DIR` | Directory to write error logs | `.` | -| `PROMPTFOO_PASS_RATE_THRESHOLD` | Set a minimum pass rate threshold (as a percentage). If not set, defaults to 0 failures | 0 | -| `PROMPTFOO_REQUIRE_JSON_PROMPTS` | By default the chat completion provider will wrap non-JSON messages in a single user message. Setting this envar to true disables that behavior. | | -| `PROMPTFOO_STRIP_PROMPT_TEXT` | Strip prompt text from results to reduce memory usage | false | -| `PROMPTFOO_STRIP_RESPONSE_OUTPUT` | Strip model response outputs from results to reduce memory usage | false | -| `PROMPTFOO_STRIP_TEST_VARS` | Strip test variables from results to reduce memory usage | false | -| `PROMPTFOO_STRIP_GRADING_RESULT` | Strip grading results from results to reduce memory usage | false | -| `PROMPTFOO_STRIP_METADATA` | Strip metadata from results to reduce memory usage | false | -| `PROMPTFOO_SHARE_CHUNK_SIZE` | Number of results to send in each chunk. This is used to estimate the size of the results and to determine the number of chunks to send. | | +### `promptfoo auth login` -:::tip -promptfoo will load environment variables from the `.env` in your current working directory. -::: +Login to the promptfoo cloud. + +| Option | Description | +| --------------------- | -------------------------------------------------------------------------- | +| `-o, --org <orgId>` | The organization ID to login to | +| `-h, --host <host>` | The host of the promptfoo instance (API URL if different from the app URL) | +| `-k, --api-key <key>` | Login using an API key | + +### `promptfoo auth logout` + +Logout from the promptfoo cloud. + +## `promptfoo config`
Config command documentation: The section only covers email (get/set/unset). If other configuration keys are supported, consider generalizing this section or noting that it's currently limited to email.
promptfoo
github_2023
typescript
3,224
promptfoo
ellipsis-dev[bot]
@@ -0,0 +1,131 @@ +import React from 'react'; +import { Alert, Box, Button, Collapse, Typography } from '@mui/material'; + +interface Props { + children: React.ReactNode; + name?: string; // Name of the component/page being wrapped + fallback?: React.ReactNode; // Optional custom fallback UI +} + +interface State { + hasError: boolean; + error: Error | null; + errorInfo: React.ErrorInfo | null; + showDetails: boolean; +} + +class ErrorBoundary extends React.Component<Props, State> { + constructor(props: Props) { + super(props); + this.state = { + hasError: false, + error: null, + errorInfo: null, + showDetails: false, + }; + } + + static getDerivedStateFromError(error: Error): Partial<State> { + return { hasError: true, error }; + } + + componentDidCatch(error: Error, errorInfo: React.ErrorInfo): void { + this.setState({ errorInfo }); + + // Log to console + console.error(`Error in ${this.props.name || 'component'}:`, { + error, + componentStack: errorInfo.componentStack, + }); + } + + private handleReload = (): void => {
Consider allowing a reset callback prop instead of always reloading the page. This gives developers control over how to recover from errors.
promptfoo
github_2023
typescript
3,220
promptfoo
ellipsis-dev[bot]
@@ -17,6 +17,16 @@ import { safeJsonStringify } from '../util/json'; import { ellipsize } from '../util/text'; import { parseChatPrompt } from './shared'; +async function getReplicateClient(): Promise<typeof Replicate> {
Consider caching the module in getReplicateClient to avoid repeated dynamic imports.
promptfoo
github_2023
typescript
3,196
promptfoo
ellipsis-dev[bot]
@@ -0,0 +1,366 @@ +import React, { useState } from 'react'; +import { Link } from 'react-router-dom'; +import DownloadIcon from '@mui/icons-material/Download'; +import Autocomplete from '@mui/material/Autocomplete'; +import Box from '@mui/material/Box'; +import Button from '@mui/material/Button'; +import CircularProgress from '@mui/material/CircularProgress'; +import Menu from '@mui/material/Menu'; +import MenuItem from '@mui/material/MenuItem'; +import Pagination from '@mui/material/Pagination'; +import Table from '@mui/material/Table'; +import TableBody from '@mui/material/TableBody'; +import TableCell from '@mui/material/TableCell'; +import TableContainer from '@mui/material/TableContainer'; +import TableHead from '@mui/material/TableHead'; +import TableRow from '@mui/material/TableRow'; +import TableSortLabel from '@mui/material/TableSortLabel'; +import TextField from '@mui/material/TextField'; +import type { PromptMetrics } from '@promptfoo/types'; +import type { StandaloneEval } from '@promptfoo/util'; + +interface HistoryProps { + data: StandaloneEval[]; + isLoading: boolean; + error: string | null; +} + +export default function History({ data, isLoading, error }: HistoryProps) { + const [sortField, setSortField] = useState<string | null>(null); + const [sortOrder, setSortOrder] = useState<'asc' | 'desc'>('asc'); + const [anchorEl, setAnchorEl] = useState<null | HTMLElement>(null); + const [page, setPage] = React.useState(1); + const [filter, setFilter] = useState({ evalId: '', datasetId: '', provider: '', promptId: '' }); + + const rowsPerPage = 25; + const open = Boolean(anchorEl); + + const handleSort = (field: string) => { + const isAsc = sortField === field && sortOrder === 'asc'; + setSortField(field); + setSortOrder(isAsc ? 'desc' : 'asc'); + }; + + const handleClick = (event: React.MouseEvent<HTMLButtonElement>) => { + setAnchorEl(event.currentTarget); + }; + + const handleClose = () => { + setAnchorEl(null); + }; + + const calculatePassRate = ( + metrics: { testPassCount: number; testFailCount: number } | undefined, + ) => { + if (metrics?.testPassCount != null && metrics?.testFailCount != null) { + return ( + (metrics.testPassCount / (metrics.testPassCount + metrics.testFailCount)) * + 100 + ).toFixed(2); + } + return '-'; + }; + + const convertToCSV = (arr: StandaloneEval[]) => { + const headers = [
CSV export: Header count (8) mismatches row length (9). Consider adding a header for testErrorCount or removing it from rows. ```suggestion const headers = ['Eval', 'Dataset', 'Provider', 'Prompt', 'Pass Rate %', 'Pass Count', 'Fail Count', 'Error Count', 'Raw score']; ```
promptfoo
github_2023
typescript
3,196
promptfoo
ellipsis-dev[bot]
@@ -0,0 +1,366 @@ +import React, { useState } from 'react'; +import { Link } from 'react-router-dom'; +import DownloadIcon from '@mui/icons-material/Download'; +import Autocomplete from '@mui/material/Autocomplete'; +import Box from '@mui/material/Box'; +import Button from '@mui/material/Button'; +import CircularProgress from '@mui/material/CircularProgress'; +import Menu from '@mui/material/Menu'; +import MenuItem from '@mui/material/MenuItem'; +import Pagination from '@mui/material/Pagination'; +import Table from '@mui/material/Table'; +import TableBody from '@mui/material/TableBody'; +import TableCell from '@mui/material/TableCell'; +import TableContainer from '@mui/material/TableContainer'; +import TableHead from '@mui/material/TableHead'; +import TableRow from '@mui/material/TableRow'; +import TableSortLabel from '@mui/material/TableSortLabel'; +import TextField from '@mui/material/TextField'; +import type { PromptMetrics } from '@promptfoo/types'; +import type { StandaloneEval } from '@promptfoo/util'; + +interface HistoryProps { + data: StandaloneEval[]; + isLoading: boolean; + error: string | null; +} + +export default function History({ data, isLoading, error }: HistoryProps) { + const [sortField, setSortField] = useState<string | null>(null); + const [sortOrder, setSortOrder] = useState<'asc' | 'desc'>('asc'); + const [anchorEl, setAnchorEl] = useState<null | HTMLElement>(null); + const [page, setPage] = React.useState(1); + const [filter, setFilter] = useState({ evalId: '', datasetId: '', provider: '', promptId: '' }); + + const rowsPerPage = 25; + const open = Boolean(anchorEl); + + const handleSort = (field: string) => { + const isAsc = sortField === field && sortOrder === 'asc'; + setSortField(field); + setSortOrder(isAsc ? 'desc' : 'asc'); + }; + + const handleClick = (event: React.MouseEvent<HTMLButtonElement>) => { + setAnchorEl(event.currentTarget); + }; + + const handleClose = () => { + setAnchorEl(null); + }; + + const calculatePassRate = ( + metrics: { testPassCount: number; testFailCount: number } | undefined, + ) => { + if (metrics?.testPassCount != null && metrics?.testFailCount != null) { + return ( + (metrics.testPassCount / (metrics.testPassCount + metrics.testFailCount)) * + 100 + ).toFixed(2); + } + return '-'; + }; + + const convertToCSV = (arr: StandaloneEval[]) => { + const headers = [ + 'Eval', + 'Dataset', + 'Provider', + 'Prompt', + 'Pass Rate %', + 'Pass Count', + 'Fail Count', + 'Raw score', + ]; + const rows = arr.map((col) => [ + col.evalId ?? '', + col.datasetId?.slice(0, 6) ?? '', + col.provider ?? '', + (col.promptId?.slice(0, 6) ?? '') + ' ' + (col.raw ?? ''), + calculatePassRate(col.metrics), + col.metrics?.testPassCount == null ? '-' : `${col.metrics.testPassCount}`, + col.metrics?.testFailCount == null ? '-' : `${col.metrics.testFailCount}`, + col.metrics?.testErrorCount == null ? '-' : `${col.metrics.testErrorCount}`, + col.metrics?.score == null ? '-' : col.metrics.score?.toFixed(2), + ]); + return [headers] + .concat(rows) + .map((it) => it.map((value) => value ?? '').join(',')) + .join('\n'); + }; + + const handleExport = (format: string) => { + const dataStr = format === 'json' ? JSON.stringify(data) : convertToCSV(data); + const blob = new Blob([dataStr], { type: `text/${format};charset=utf-8;` }); + const link = document.createElement('a'); + link.href = URL.createObjectURL(blob); + link.download = `cols_export.${format}`; + link.click(); + URL.revokeObjectURL(link.href); + setAnchorEl(null); + }; + + const getSortedValues = (sortOrder: string, a: number, b: number): number => { + return sortOrder === 'asc' ? a - b : b - a; + }; + + const getValue = (metrics: PromptMetrics | undefined, sortField: string): number => { + if (metrics) { + return metrics[sortField as keyof PromptMetrics] as number; + } + return 0; + }; + + const filteredCols = React.useMemo(() => { + return data.filter( + (col) => + (filter.evalId ? col.evalId?.includes(filter.evalId) : true) && + (filter.datasetId ? col.datasetId?.startsWith(filter.datasetId) : true) && + (filter.provider ? col.provider?.includes(filter.provider) : true) && + (filter.promptId ? col.promptId?.startsWith(filter.promptId) : true), + ); + }, [data, filter]); + + const sortedCols = React.useMemo(() => { + return filteredCols.sort((a, b) => {
For immutability and to avoid side effects, consider sorting a copy of the filtered array (e.g. using slice()) before applying sort(). ```suggestion return filteredCols.slice().sort((a, b) => { ```
promptfoo
github_2023
typescript
3,196
promptfoo
ellipsis-dev[bot]
@@ -0,0 +1,366 @@ +import React, { useState } from 'react'; +import { Link } from 'react-router-dom'; +import DownloadIcon from '@mui/icons-material/Download'; +import Autocomplete from '@mui/material/Autocomplete'; +import Box from '@mui/material/Box'; +import Button from '@mui/material/Button'; +import CircularProgress from '@mui/material/CircularProgress'; +import Menu from '@mui/material/Menu'; +import MenuItem from '@mui/material/MenuItem'; +import Pagination from '@mui/material/Pagination'; +import Table from '@mui/material/Table'; +import TableBody from '@mui/material/TableBody'; +import TableCell from '@mui/material/TableCell'; +import TableContainer from '@mui/material/TableContainer'; +import TableHead from '@mui/material/TableHead'; +import TableRow from '@mui/material/TableRow'; +import TableSortLabel from '@mui/material/TableSortLabel'; +import TextField from '@mui/material/TextField'; +import type { PromptMetrics } from '@promptfoo/types'; +import type { StandaloneEval } from '@promptfoo/util'; + +interface HistoryProps { + data: StandaloneEval[]; + isLoading: boolean; + error: string | null; +} + +export default function History({ data, isLoading, error }: HistoryProps) { + const [sortField, setSortField] = useState<string | null>(null); + const [sortOrder, setSortOrder] = useState<'asc' | 'desc'>('asc'); + const [anchorEl, setAnchorEl] = useState<null | HTMLElement>(null); + const [page, setPage] = React.useState(1); + const [filter, setFilter] = useState({ evalId: '', datasetId: '', provider: '', promptId: '' }); + + const rowsPerPage = 25; + const open = Boolean(anchorEl); + + const handleSort = (field: string) => { + const isAsc = sortField === field && sortOrder === 'asc'; + setSortField(field); + setSortOrder(isAsc ? 'desc' : 'asc'); + }; + + const handleClick = (event: React.MouseEvent<HTMLButtonElement>) => { + setAnchorEl(event.currentTarget); + }; + + const handleClose = () => { + setAnchorEl(null); + }; + + const calculatePassRate = ( + metrics: { testPassCount: number; testFailCount: number } | undefined, + ) => { + if (metrics?.testPassCount != null && metrics?.testFailCount != null) { + return ( + (metrics.testPassCount / (metrics.testPassCount + metrics.testFailCount)) * + 100 + ).toFixed(2); + } + return '-'; + }; + + const convertToCSV = (arr: StandaloneEval[]) => { + const headers = [ + 'Eval', + 'Dataset', + 'Provider', + 'Prompt', + 'Pass Rate %', + 'Pass Count', + 'Fail Count', + 'Raw score', + ]; + const rows = arr.map((col) => [ + col.evalId ?? '', + col.datasetId?.slice(0, 6) ?? '', + col.provider ?? '', + (col.promptId?.slice(0, 6) ?? '') + ' ' + (col.raw ?? ''), + calculatePassRate(col.metrics), + col.metrics?.testPassCount == null ? '-' : `${col.metrics.testPassCount}`, + col.metrics?.testFailCount == null ? '-' : `${col.metrics.testFailCount}`, + col.metrics?.testErrorCount == null ? '-' : `${col.metrics.testErrorCount}`, + col.metrics?.score == null ? '-' : col.metrics.score?.toFixed(2), + ]); + return [headers] + .concat(rows) + .map((it) => it.map((value) => value ?? '').join(',')) + .join('\n'); + }; + + const handleExport = (format: string) => { + const dataStr = format === 'json' ? JSON.stringify(data) : convertToCSV(data); + const blob = new Blob([dataStr], { type: `text/${format};charset=utf-8;` }); + const link = document.createElement('a'); + link.href = URL.createObjectURL(blob); + link.download = `cols_export.${format}`; + link.click(); + URL.revokeObjectURL(link.href); + setAnchorEl(null); + }; + + const getSortedValues = (sortOrder: string, a: number, b: number): number => { + return sortOrder === 'asc' ? a - b : b - a; + }; + + const getValue = (metrics: PromptMetrics | undefined, sortField: string): number => { + if (metrics) { + return metrics[sortField as keyof PromptMetrics] as number; + } + return 0; + }; + + const filteredCols = React.useMemo(() => { + return data.filter( + (col) => + (filter.evalId ? col.evalId?.includes(filter.evalId) : true) && + (filter.datasetId ? col.datasetId?.startsWith(filter.datasetId) : true) && + (filter.provider ? col.provider?.includes(filter.provider) : true) && + (filter.promptId ? col.promptId?.startsWith(filter.promptId) : true), + ); + }, [data, filter]); + + const sortedCols = React.useMemo(() => { + return filteredCols.sort((a, b) => { + if (!sortField) { + return 0; + } + if (sortField === 'passRate') { + const aValue = Number.parseFloat(calculatePassRate(a.metrics)); + const bValue = Number.parseFloat(calculatePassRate(b.metrics)); + return getSortedValues(sortOrder, aValue, bValue); + } else if (sortField === 'evalId') { + // Ensure sortField is a key of StandaloneEval + if (sortField in a && sortField in b) { + const aValue = a[sortField as keyof StandaloneEval] || ''; + const bValue = b[sortField as keyof StandaloneEval] || ''; + return sortOrder === 'asc' + ? aValue.toString().localeCompare(bValue.toString()) + : bValue.toString().localeCompare(aValue.toString()); + } + return 0; + } else { + const aValue = getValue(a.metrics, sortField); + const bValue = getValue(b.metrics, sortField); + return getSortedValues(sortOrder, aValue, bValue); + } + }); + }, [filteredCols, sortField, sortOrder]); + + const evalIdOptions = React.useMemo( + () => Array.from(new Set(data.map((col) => col.evalId))), + [data], + ); + const datasetIdOptions = React.useMemo( + () => Array.from(new Set(data.map((col) => col.datasetId))), + [data], + ); + const providerOptions = React.useMemo( + () => Array.from(new Set(data.map((col) => col.provider))), + [data], + ); + const promptIdOptions = React.useMemo( + () => Array.from(new Set(data.map((col) => col.promptId))), + [data], + ); + + return ( + <Box paddingX={2}> + <Box display="flex" justifyContent="space-between" alignItems="center"> + <h2>Eval History</h2> + <div> + <Button + id="export-button" + aria-controls={open ? 'export-menu' : undefined} + aria-haspopup="true" + aria-expanded={open ? 'true' : undefined} + onClick={handleClick} + startIcon={<DownloadIcon />} + > + Export + </Button> + <Menu + id="export-menu" + anchorEl={anchorEl} + open={open} + onClose={handleClose} + MenuListProps={{ + 'aria-labelledby': 'export-button', + }} + > + <MenuItem onClick={() => handleExport('csv')}>CSV</MenuItem> + <MenuItem onClick={() => handleExport('json')}>JSON</MenuItem> + </Menu> + </div> + </Box> + <Box>This page shows performance metrics for recent evals.</Box> + <Box display="flex" flexDirection="row" gap={2} my={2}> + <Autocomplete + options={evalIdOptions} + value={filter.evalId} + onChange={(event, newValue) => { + setFilter({ ...filter, evalId: newValue || '' }); + }} + renderInput={(params) => ( + <TextField {...params} label="Eval ID" variant="outlined" size="small" fullWidth /> + )} + sx={{ width: 220 }} + /> + <Autocomplete + options={datasetIdOptions} + value={filter.datasetId} + onChange={(event, newValue) => { + setFilter({ ...filter, datasetId: newValue || '' }); + }} + renderInput={(params) => ( + <TextField {...params} label="Dataset ID" variant="outlined" size="small" fullWidth /> + )} + sx={{ width: 220 }} + /> + <Autocomplete + options={providerOptions} + value={filter.provider} + onChange={(event, newValue) => { + setFilter({ ...filter, provider: newValue || '' }); + }} + renderInput={(params) => ( + <TextField {...params} label="Provider" variant="outlined" size="small" fullWidth /> + )} + sx={{ width: 220 }} + /> + <Autocomplete + options={promptIdOptions} + value={filter.promptId} + onChange={(event, newValue) => { + setFilter({ ...filter, promptId: newValue || '' }); + }} + renderInput={(params) => ( + <TextField {...params} label="Prompt ID" variant="outlined" size="small" fullWidth /> + )} + sx={{ width: 220 }} + /> + </Box> + <TableContainer> + <Table> + <TableHead> + <TableRow> + <TableCell> + <TableSortLabel + active={sortField === 'evalId'} + direction={sortField === 'evalId' ? sortOrder : 'asc'} + onClick={() => handleSort('evalId')} + > + Eval + </TableSortLabel> + </TableCell> + <TableCell>Dataset</TableCell> + <TableCell>Provider</TableCell> + <TableCell>Prompt</TableCell> + <TableCell> + <TableSortLabel + active={sortField === 'passRate'} + direction={sortField === 'passRate' ? sortOrder : 'asc'} + onClick={() => handleSort('passRate')} + > + Pass Rate % + </TableSortLabel> + </TableCell> + <TableCell> + <TableSortLabel + active={sortField === 'testPassCount'} + direction={sortField === 'testPassCount' ? sortOrder : 'asc'} + onClick={() => handleSort('testPassCount')} + > + Pass Count + </TableSortLabel> + </TableCell> + <TableCell> + <TableSortLabel + active={sortField === 'testFailCount'} + direction={sortField === 'testFailCount' ? sortOrder : 'asc'} + onClick={() => handleSort('testFailCount')} + > + Fail Count + </TableSortLabel> + </TableCell> + <TableCell> + <TableSortLabel + active={sortField === 'score'} + direction={sortField === 'score' ? sortOrder : 'asc'} + onClick={() => handleSort('score')} + > + Raw score + </TableSortLabel> + </TableCell> + </TableRow> + </TableHead> + <TableBody> + {sortedCols.slice((page - 1) * rowsPerPage, page * rowsPerPage).map((col, index) => ( + <TableRow + key={index} + hover + onClick={() => + setFilter({ + ...filter, + evalId: col.evalId, + datasetId: col.datasetId || '', + promptId: col.promptId || '', + provider: col.provider, + }) + } + > + <TableCell> + <Link to={`/eval?evalId=${col.evalId}`} onClick={(e) => e.stopPropagation()}> + {col.evalId} + </Link> + </TableCell> + <TableCell> + <Link to={`/datasets?id=${col.datasetId}`} onClick={(e) => e.stopPropagation()}> + {col.datasetId?.slice(0, 6)} + </Link> + </TableCell> + <TableCell>{col.provider}</TableCell> + <TableCell> + <Link to={`/prompts?id=${col.promptId}`} onClick={(e) => e.stopPropagation()}> + [{col.promptId?.slice(0, 6)}] + </Link>{' '} + {col.raw} + </TableCell> + <TableCell>{calculatePassRate(col.metrics)}</TableCell> + <TableCell> + {col.metrics?.testPassCount == null ? '-' : `${col.metrics.testPassCount}`} + </TableCell> + <TableCell> + {col.metrics?.testFailCount == null + ? '- ' + + (col.metrics?.testErrorCount && col.metrics.testErrorCount > 0 + ? `+ ${col.metrics.testErrorCount} errors` + : '') + : `${col.metrics.testFailCount} ` + + (col.metrics?.testErrorCount ? `+ ${col.metrics.testErrorCount} errors` : '')} + </TableCell> + <TableCell> + {col.metrics?.score == null ? '-' : col.metrics.score?.toFixed(2)} + </TableCell> + </TableRow> + ))} + </TableBody> + </Table> + {Math.ceil(filteredCols.length / rowsPerPage) > 1 && ( + <Pagination + count={Math.ceil(sortedCols.length / rowsPerPage)} + page={page} + onChange={(event, value) => setPage(value)} + sx={{ pt: 2, pb: 4, display: 'flex', justifyContent: 'center' }} + /> + )} + </TableContainer> + {isLoading && ( + <Box display="flex" justifyContent="center" my={4}> + <CircularProgress /> + </Box> + )} + </Box> + );
The 'error' prop isn’t reflected in the UI. Consider adding error handling so that users are informed when loading history data fails.
promptfoo
github_2023
typescript
3,202
promptfoo
ellipsis-dev[bot]
@@ -253,23 +273,47 @@ export class AnthropicMessagesProvider implements ApiProvider { ); } - const { system, extractedMessages } = parseMessages(prompt); + const { system, extractedMessages, thinking } = parseMessages(prompt); + + // Validate thinking configuration + if (thinking && 'type' in thinking && thinking.type === 'enabled') { + if (!thinking.budget_tokens || thinking.budget_tokens < 1024) { + throw new Error('Thinking budget must be at least 1024 tokens when enabled'); + } + if (this.config?.max_tokens && thinking.budget_tokens >= this.config.max_tokens) { + throw new Error('Thinking budget must be less than max_tokens'); + } + } + const params: Anthropic.MessageCreateParams = { model: this.modelName, ...(system ? { system } : {}), max_tokens: this.config?.max_tokens || getEnvInt('ANTHROPIC_MAX_TOKENS', 1024), messages: extractedMessages, stream: false, - temperature: this.config.temperature || getEnvFloat('ANTHROPIC_TEMPERATURE', 0), + temperature: + (this.config.thinking || thinking) && !this.config.temperature
Using '!this.config.temperature' can override an explicit value of 0. Consider checking for undefined (e.g. 'this.config.temperature === undefined') so that valid falsy values like 0 are preserved. ```suggestion (this.config.thinking || thinking) && this.config.temperature === undefined ```
promptfoo
github_2023
others
3,209
promptfoo
ellipsis-dev[bot]
@@ -0,0 +1,17 @@ +# yaml-language-server: $schema=https://promptfoo.dev/config-schema.json +# This configuration runs each prompt through a series of example inputs and checks if they meet requirements. + +prompts: + - "You are a helpful assistant. Reply with a concise answer to this inquiry: '{{question}}'" + +providers: + - id: 'vertex:claude-3-5-sonnet-v2' + config: + publisher: anthropic + region: us-east5 + +tests: + - vars: + question: 'Solve 3*x^3-5*x=1' + - vars: + question: What's the weather in New York?
Consider quoting the weather question properly to avoid YAML parsing issues due to the apostrophe (e.g. use double quotes). ```suggestion question: "What's the weather in New York?" ```
promptfoo
github_2023
typescript
3,209
promptfoo
ellipsis-dev[bot]
@@ -132,6 +133,44 @@ interface VertexCompletionOptions { systemInstruction?: Content; } +// Claude API interfaces
Consider extracting the Claude API interfaces (ClaudeMessage, ClaudeRequest, ClaudeResponse) into a separate module for better modularity and reuse.
promptfoo
github_2023
others
3,199
promptfoo
ellipsis-dev[bot]
@@ -152,14 +152,14 @@ With the evaluation complete, it's time to dig into the results and see how the Some key things to look for: -- Which model had a higher overall pass rate on the test assertions? In this case, both models did equally well in terms of getting the answer, which is great - these riddles often trip up less powerful models like GPT 3.5 and Claude 2. +- Which model had a higher overall pass rate on the test assertions? In this case, both models did equally well in terms of getting the answer, which is great - these riddles often trip up less powerful models like GPT 3.7 and Claude 2.
In the bullet point on line 155, the text refers to 'GPT 3.7', which appears inconsistent with the models being compared (Claude 3.7 vs GPT-4o). Please check if 'GPT 3.7' is a typo and should be corrected to 'Claude 3.7' or another appropriate model name. ```suggestion - Which model had a higher overall pass rate on the test assertions? In this case, both models did equally well in terms of getting the answer, which is great - these riddles often trip up less powerful models like GPT-4o and Claude 2. ```
promptfoo
github_2023
others
3,199
promptfoo
ellipsis-dev[bot]
@@ -1,15 +1,15 @@ --- -sidebar_label: 'Claude 3.5 vs GPT-4o' -description: 'Learn how to benchmark Claude 3.5 against GPT-4o using your own data with promptfoo. Discover which model performs best for your specific use case.' +sidebar_label: 'Claude 3.7 vs GPT-4o' +description: 'Learn how to benchmark Claude 3.7 against GPT-4o using your own data with promptfoo. Discover which model performs best for your specific use case.' --- -# Claude 3.5 vs GPT-4o: Benchmark on Your Own Data +# Claude 3.7 vs GPT-4o: Benchmark on Your Own Data When evaluating the performance of LLMs, generic benchmarks will only get you so far. This is especially the case for Claude vs GPT, as there are many split evaluations (subjective and objective) on their efficacy. You should test these models on tasks that are relevant to your specific use case, rather than relying solely on public benchmarks. -This guide will walk you through setting up a comparison between Anthropic's Claude 3.5 and OpenAI's GPT-4o using `promptfoo`. The end result is a side-by-side evaluation of how these models perform on custom tasks: +This guide will walk you through setting up a comparison between Anthropic's Claude 3.7 and OpenAI's GPT-4o using `promptfoo`. The end result is a side-by-side evaluation of how these models perform on custom tasks: ![Claude 3.5 vs GPT-4o comparison](/img/docs/claude3.5-vs-gpt4o.png)
Inconsistent image reference: document title and content refer to Claude 3.7, but the image now shows Claude 3.5. ```suggestion ![Claude 3.7 vs GPT-4o comparison](/img/docs/claude3.7-vs-gpt4o.png) ```
promptfoo
github_2023
python
3,174
promptfoo
ellipsis-dev[bot]
@@ -1,18 +1,23 @@ from openai import AsyncOpenAI, OpenAI +import random async_client = AsyncOpenAI() client = OpenAI() def call_api(prompt, options, context): + # Randomly throw error 30% of the time + if random.random() < 0.5:
The comment on line 9 says 'Randomly throw error 30% of the time' but the condition uses < 0.5, which is 50%. Please update either the code or the comment. ```suggestion if random.random() < 0.3: ```
promptfoo
github_2023
typescript
3,174
promptfoo
ellipsis-dev[bot]
@@ -1,168 +1,240 @@ import { filterTests } from '../../../src/commands/eval/filterTests'; -import type { TestSuite } from '../../../src/types'; +import Eval from '../../../src/models/eval'; +import type { TestSuite, TestCase } from '../../../src/types'; +import { ResultFailureReason } from '../../../src/types'; + +jest.mock('../../../src/models/eval', () => ({ + findById: jest.fn(), +})); describe('filterTests', () => { - const testNoDescription = {}; - const testHuey = { - description: 'Huey', - }; - const testDewey = { - description: 'Dewey', - }; - const testLouie = { - description: 'Louie', + const mockTestSuite: TestSuite = { + prompts: [], + providers: [], + tests: [ + { + description: 'test1', + vars: { var1: 'test1' }, + assert: [], + metadata: { type: 'unit' }, + }, + { + description: 'test2', + vars: { var1: 'test2' }, + assert: [], + metadata: { type: 'integration' }, + }, + { + description: 'test3', + vars: { var1: 'test3' }, + assert: [], + metadata: { type: 'unit' }, + }, + ], }; - const tests = [testHuey, testNoDescription, testDewey, testLouie]; - const testSuite = { - tests, - } as TestSuite; - - it('should run all tests when no args', async () => { - const result = await filterTests(testSuite, {}); - expect(result).toStrictEqual(tests); + beforeEach(() => { + jest.resetAllMocks(); + const mockEval = { + id: 'eval-123', + createdAt: new Date().getTime(), + config: {}, + results: [], + resultsCount: 0, + prompts: [], + persisted: true, + toEvaluateSummary: jest.fn().mockResolvedValue({ + version: 2, + timestamp: new Date().toISOString(), + results: [ + { + vars: { var1: 'test1' }, + success: false, + failureReason: ResultFailureReason.ASSERT, + testCase: mockTestSuite.tests![0], + }, + { + vars: { var1: 'test3' }, + success: false, + failureReason: ResultFailureReason.ERROR, + testCase: mockTestSuite.tests![2], + }, + ], + table: { head: { prompts: [], vars: [] }, body: [] }, + stats: { + successes: 0, + failures: 0, + errors: 0, + tokenUsage: { + total: 0, + prompt: 0, + completion: 0, + cached: 0, + numRequests: 0, + completionDetails: { + reasoning: 0, + acceptedPrediction: 0, + rejectedPrediction: 0, + }, + }, + }, + }), + }; + jest.mocked(Eval.findById).mockResolvedValue(mockEval as any); }); - it('handles no tests', async () => { - const result = await filterTests({} as TestSuite, {}); + it('should return all tests if no options provided', async () => { + const result = await filterTests(mockTestSuite, {}); + expect(result).toEqual(mockTestSuite.tests); + }); + it('should return empty array if testSuite has no tests', async () => { + const result = await filterTests({ prompts: [], providers: [] }, {}); expect(result).toEqual([]); }); - describe('firstN', () => { - it('should only run Huey and Dewey', async () => { - const result = await filterTests(testSuite, { firstN: '2' }); - - expect(result).toStrictEqual(tests.slice(0, 2)); + describe('metadata filter', () => { + it('should filter tests by metadata key-value pair', async () => { + const result = await filterTests(mockTestSuite, { metadata: 'type=unit' }); + expect(result).toHaveLength(2); + expect(result.map((t: TestCase) => t.vars?.var1)).toEqual(['test1', 'test3']); }); - it('throws an exception when firstN is not a number', async () => { - await expect(() => filterTests(testSuite, { firstN: 'NOPE' })).rejects.toEqual( - new Error('firstN must be a number, got: NOPE'), + it('should throw error if metadata filter format is invalid', async () => { + await expect(filterTests(mockTestSuite, { metadata: 'invalid' })).rejects.toThrow( + '--filter-metadata must be specified in key=value format', ); }); - }); - - describe('pattern', () => { - it('should only return tests whose description ends in "ey"', async () => { - const result = await filterTests(testSuite, { pattern: 'ey$' }); - expect(result).toStrictEqual([testHuey, testDewey]); + it('should exclude tests without metadata', async () => { + const testSuite = { + ...mockTestSuite, + tests: [...mockTestSuite.tests!, { description: 'no-metadata', vars: {}, assert: [] }], + }; + const result = await filterTests(testSuite, { metadata: 'type=unit' }); + expect(result).toHaveLength(2); + expect(result.map((t: TestCase) => t.vars?.var1)).toEqual(['test1', 'test3']); }); + }); - it('can combine firstN and pattern', async () => { - const result = await filterTests(testSuite, { firstN: '1', pattern: 'ey$' }); + describe('failing filter', () => { + it('should filter failing tests when failing option is provided', async () => { + const result = await filterTests(mockTestSuite, { failing: 'eval-123' }); + expect(result).toHaveLength(2); + expect(result.map((t: TestCase) => t.vars?.var1)).toEqual(['test1', 'test3']); + }); + }); - expect(result).toStrictEqual([testHuey]); + describe('errors only filter', () => { + it('should filter error tests when errorsOnly option is provided', async () => { + const result = await filterTests(mockTestSuite, { errorsOnly: 'eval-123' }); + expect(result).toHaveLength(1); + expect(result[0]?.vars?.var1).toBe('test3'); }); + }); - it('does not mutate when when has args', async () => { - const result = await filterTests(testSuite, { firstN: '1', pattern: 'ey$' }); + describe('pattern filter', () => { + it('should filter tests by description pattern', async () => { + const result = await filterTests(mockTestSuite, { pattern: 'test[12]' }); + expect(result).toHaveLength(2); + expect(result.map((t: TestCase) => t.vars?.var1)).toEqual(['test1', 'test2']); + }); - expect(result).not.toBe(tests); + it('should handle tests without description', async () => { + const testSuite = { + ...mockTestSuite, + tests: [...mockTestSuite.tests!, { vars: {}, assert: [] }], + }; + const result = await filterTests(testSuite, { pattern: 'test' }); + expect(result).toHaveLength(3); }); }); - describe('sample', () => { - it('should return the requested number of random tests', async () => { - const result = await filterTests(testSuite, { sample: 2 }); - + describe('firstN filter', () => {
Consider also testing when firstN exceeds total test count.
promptfoo
github_2023
typescript
3,174
promptfoo
ellipsis-dev[bot]
@@ -0,0 +1,64 @@ +import Eval from '../../models/eval'; +import type { TestSuite, EvaluateResult } from '../../types'; +import { readOutput, resultIsForTestCase } from '../../util'; + +type Tests = NonNullable<TestSuite['tests']>; + +/** + * A function that determines whether a test result should be included in the filtered results. + * @param result - The eval result to check + * @returns True if the result should be included, false otherwise + */ +type ResultFilterFn = (result: EvaluateResult) => boolean; + +/** + * Filters a test suite based on results from a previous eval. + * Can handle both file paths to JSON results and eval IDs. + * + * @param testSuite - The test suite containing all tests + * @param pathOrId - Either a file path to a JSON results file or an eval ID + * @param filterFn - A function that determines which results to include + * @returns A filtered array of tests based on the filter function + * @throws {Error} If the file path is invalid or if the eval ID doesn't exist
Doc comment says an Error is thrown on invalid input, but the implementation returns an empty array. Update the documentation to match the behavior.
promptfoo
github_2023
others
3,174
promptfoo
ellipsis-dev[bot]
@@ -1438,6 +1438,9 @@ "watch": { "type": "boolean" }, + "filterErrorsOnly": {
Consider adding a descriptive "description" field for the new filterErrorsOnly property to document its usage, similar to other properties.
promptfoo
github_2023
typescript
3,184
promptfoo
ellipsis-dev[bot]
@@ -0,0 +1,623 @@ +import { desc, eq, like, and, sql, not } from 'drizzle-orm'; +import NodeCache from 'node-cache'; +import { getDb } from '../database'; +import { + datasetsTable, + evalsTable, + evalsToDatasetsTable, + evalsToPromptsTable, + evalsToTagsTable, + promptsTable, + tagsTable, + evalResultsTable, +} from '../database/tables'; +import { getAuthor } from '../globalConfig/accounts'; +import logger from '../logger'; +import Eval, { createEvalId, getSummaryOfLatestEvals } from '../models/eval'; +import { generateIdFromPrompt } from '../models/prompt'; +import { + type EvalWithMetadata, + type EvaluateTable, + type PromptWithMetadata, + type ResultsFile, + type TestCase, + type TestCasesWithMetadata, + type TestCasesWithMetadataPrompt, + type UnifiedConfig, + type CompletedPrompt, + type ResultLightweight, + type EvaluateSummaryV2, +} from '../types'; +import invariant from '../util/invariant'; +import { sha256 } from './createHash'; + +const DEFAULT_QUERY_LIMIT = 100; + +export async function writeResultsToDatabase(
This functionality already exists in `Eval.create`. Consider using that instead to avoid duplication. - static method `Eval.create` ([eval.ts](https://github.com/promptfoo/promptfoo/blob/d555ee28c4722ed9967c629fc6f8a719b5c600f8/src/models/eval.ts#L149-L260))
promptfoo
github_2023
typescript
3,184
promptfoo
ellipsis-dev[bot]
@@ -0,0 +1,623 @@ +import { desc, eq, like, and, sql, not } from 'drizzle-orm';
Usage of performance.now() requires importing performance. Add: `import { performance } from 'perf_hooks';` at the top. ```suggestion import { performance } from 'perf_hooks'; ```
promptfoo
github_2023
typescript
3,184
promptfoo
ellipsis-dev[bot]
@@ -0,0 +1,623 @@ +import { desc, eq, like, and, sql, not } from 'drizzle-orm'; +import NodeCache from 'node-cache'; +import { getDb } from '../database'; +import { + datasetsTable, + evalsTable, + evalsToDatasetsTable, + evalsToPromptsTable, + evalsToTagsTable, + promptsTable, + tagsTable, + evalResultsTable, +} from '../database/tables'; +import { getAuthor } from '../globalConfig/accounts'; +import logger from '../logger'; +import Eval, { createEvalId, getSummaryOfLatestEvals } from '../models/eval'; +import { generateIdFromPrompt } from '../models/prompt'; +import { + type EvalWithMetadata, + type EvaluateTable, + type PromptWithMetadata, + type ResultsFile, + type TestCase, + type TestCasesWithMetadata, + type TestCasesWithMetadataPrompt, + type UnifiedConfig, + type CompletedPrompt, + type ResultLightweight, + type EvaluateSummaryV2, +} from '../types'; +import invariant from '../util/invariant'; +import { sha256 } from './createHash'; + +const DEFAULT_QUERY_LIMIT = 100; + +export async function writeResultsToDatabase( + results: EvaluateSummaryV2, + config: Partial<UnifiedConfig>, + createdAt: Date = new Date(), +): Promise<string> { + createdAt = createdAt || (results.timestamp ? new Date(results.timestamp) : new Date()); + const evalId = createEvalId(createdAt); + const db = getDb(); + + const promises = []; + promises.push( + db + .insert(evalsTable) + .values({ + id: evalId, + createdAt: createdAt.getTime(), + author: getAuthor(), + description: config.description, + config, + results, + }) + .onConflictDoNothing() + .run(), + ); + + logger.debug(`Inserting eval ${evalId}`); + + // Record prompt relation + invariant(results.table, 'Table is required'); + + for (const prompt of results.table.head.prompts) { + const label = prompt.label || prompt.display || prompt.raw; + const promptId = generateIdFromPrompt(prompt); + + promises.push( + db + .insert(promptsTable) + .values({ + id: promptId, + prompt: label, + }) + .onConflictDoNothing() + .run(), + ); + + promises.push( + db + .insert(evalsToPromptsTable) + .values({ + evalId, + promptId, + }) + .onConflictDoNothing() + .run(), + ); + + logger.debug(`Inserting prompt ${promptId}`); + } + + // Record dataset relation + const datasetId = sha256(JSON.stringify(config.tests || [])); + promises.push( + db + .insert(datasetsTable) + .values({ + id: datasetId, + tests: config.tests, + }) + .onConflictDoNothing() + .run(), + ); + + promises.push( + db + .insert(evalsToDatasetsTable) + .values({ + evalId, + datasetId, + }) + .onConflictDoNothing() + .run(), + ); + + logger.debug(`Inserting dataset ${datasetId}`); + + // Record tags + if (config.tags) { + for (const [tagKey, tagValue] of Object.entries(config.tags)) { + const tagId = sha256(`${tagKey}:${tagValue}`); + + promises.push( + db + .insert(tagsTable) + .values({ + id: tagId, + name: tagKey, + value: tagValue, + }) + .onConflictDoNothing() + .run(), + ); + + promises.push( + db + .insert(evalsToTagsTable) + .values({ + evalId, + tagId, + }) + .onConflictDoNothing() + .run(), + ); + + logger.debug(`Inserting tag ${tagId}`); + } + } + + logger.debug(`Awaiting ${promises.length} promises to database...`); + await Promise.all(promises); + + return evalId; +} + +/** + * + * @returns Last n evals in descending order. + */ +export async function listPreviousResults( + limit: number = DEFAULT_QUERY_LIMIT, + filterDescription?: string, + datasetId?: string, +): Promise<ResultLightweight[]> { + const db = getDb(); + const startTime = performance.now(); + + const query = db + .select({ + evalId: evalsTable.id, + createdAt: evalsTable.createdAt, + description: evalsTable.description, + numTests: sql<number>`json_array_length(${evalsTable.results}->'table'->'body')`, + datasetId: evalsToDatasetsTable.datasetId, + isRedteam: sql<boolean>`json_type(${evalsTable.config}, '$.redteam') IS NOT NULL`, + }) + .from(evalsTable) + .leftJoin(evalsToDatasetsTable, eq(evalsTable.id, evalsToDatasetsTable.evalId)) + .where( + and( + datasetId ? eq(evalsToDatasetsTable.datasetId, datasetId) : undefined, + filterDescription ? like(evalsTable.description, `%${filterDescription}%`) : undefined, + not(eq(evalsTable.results, {})), + ), + ); + + const results = query.orderBy(desc(evalsTable.createdAt)).limit(limit).all(); + const mappedResults = results.map((result) => ({ + evalId: result.evalId, + createdAt: result.createdAt, + description: result.description, + numTests: result.numTests, + datasetId: result.datasetId, + isRedteam: result.isRedteam, + })); + + const endTime = performance.now(); + const executionTime = endTime - startTime; + const evalResults = await getSummaryOfLatestEvals(undefined, filterDescription, datasetId); + logger.debug(`listPreviousResults execution time: ${executionTime.toFixed(2)}ms`); + const combinedResults = [...evalResults, ...mappedResults]; + return combinedResults; +} + +export async function readResult( + id: string, +): Promise<{ id: string; result: ResultsFile; createdAt: Date } | undefined> { + try { + const eval_ = await Eval.findById(id); + invariant(eval_, `Eval with ID ${id} not found.`); + return { + id, + result: await eval_.toResultsFile(), + createdAt: new Date(eval_.createdAt), + }; + } catch (err) { + logger.error(`Failed to read result with ID ${id} from database:\n${err}`); + } +} + +export async function updateResult( + id: string, + newConfig?: Partial<UnifiedConfig>, + newTable?: EvaluateTable, +): Promise<void> { + try { + // Fetch the existing eval data from the database + const existingEval = await Eval.findById(id); + + if (!existingEval) { + logger.error(`Eval with ID ${id} not found.`); + return; + } + + if (newConfig) { + existingEval.config = newConfig; + } + if (newTable) { + existingEval.setTable(newTable); + } + + await existingEval.save(); + + logger.info(`Updated eval with ID ${id}`); + } catch (err) { + logger.error(`Failed to update eval with ID ${id}:\n${err}`); + } +} + +export async function getLatestEval(filterDescription?: string): Promise<ResultsFile | undefined> { + const eval_ = await Eval.latest(); + return await eval_?.toResultsFile(); +} + +export async function getPromptsWithPredicate( + predicate: (result: ResultsFile) => boolean, + limit: number, +): Promise<PromptWithMetadata[]> { + // TODO(ian): Make this use a proper database query + const evals_ = await Eval.getMany(limit); + + const groupedPrompts: { [hash: string]: PromptWithMetadata } = {}; + + for (const eval_ of evals_) { + const createdAt = new Date(eval_.createdAt).toISOString(); + const resultWrapper: ResultsFile = await eval_.toResultsFile(); + if (predicate(resultWrapper)) { + for (const prompt of eval_.getPrompts()) { + const promptId = sha256(prompt.raw); + const datasetId = resultWrapper.config.tests + ? sha256(JSON.stringify(resultWrapper.config.tests)) + : '-'; + if (promptId in groupedPrompts) { + groupedPrompts[promptId].recentEvalDate = new Date( + Math.max( + groupedPrompts[promptId].recentEvalDate.getTime(), + new Date(createdAt).getTime(), + ), + ); + groupedPrompts[promptId].count += 1; + groupedPrompts[promptId].evals.push({ + id: eval_.id, + datasetId, + metrics: prompt.metrics, + }); + } else { + groupedPrompts[promptId] = { + count: 1, + id: promptId, + prompt, + recentEvalDate: new Date(createdAt), + recentEvalId: eval_.id, + evals: [ + { + id: eval_.id, + datasetId, + metrics: prompt.metrics, + }, + ], + }; + } + } + } + } + + return Object.values(groupedPrompts); +} + +export function getPromptsForTestCasesHash( + testCasesSha256: string, + limit: number = DEFAULT_QUERY_LIMIT, +) { + return getPromptsWithPredicate((result) => { + const testsJson = JSON.stringify(result.config.tests); + const hash = sha256(testsJson); + return hash === testCasesSha256; + }, limit); +} + +export function getPromptsForTestCases(testCases: TestCase[]) { + const testCasesJson = JSON.stringify(testCases); + const testCasesSha256 = sha256(testCasesJson); + return getPromptsForTestCasesHash(testCasesSha256); +} + +export async function getTestCasesWithPredicate( + predicate: (result: ResultsFile) => boolean, + limit: number, +): Promise<TestCasesWithMetadata[]> { + const evals_ = await Eval.getMany(limit); + + const groupedTestCases: { [hash: string]: TestCasesWithMetadata } = {}; + + for (const eval_ of evals_) { + const createdAt = new Date(eval_.createdAt).toISOString(); + const resultWrapper: ResultsFile = await eval_.toResultsFile(); + const testCases = resultWrapper.config.tests; + if (testCases && predicate(resultWrapper)) { + const evalId = eval_.id; + const datasetId = sha256(JSON.stringify(testCases)); + + if (datasetId in groupedTestCases) { + groupedTestCases[datasetId].recentEvalDate = new Date( + Math.max(groupedTestCases[datasetId].recentEvalDate.getTime(), eval_.createdAt), + ); + groupedTestCases[datasetId].count += 1; + const newPrompts = eval_.getPrompts().map((prompt) => ({ + id: sha256(prompt.raw), + prompt, + evalId, + })); + const promptsById: Record<string, TestCasesWithMetadataPrompt> = {}; + for (const prompt of groupedTestCases[datasetId].prompts.concat(newPrompts)) { + if (!(prompt.id in promptsById)) { + promptsById[prompt.id] = prompt; + } + } + groupedTestCases[datasetId].prompts = Object.values(promptsById); + } else { + const newPrompts = eval_.getPrompts().map((prompt) => ({ + id: sha256(prompt.raw), + prompt, + evalId, + })); + const promptsById: Record<string, TestCasesWithMetadataPrompt> = {}; + for (const prompt of newPrompts) { + if (!(prompt.id in promptsById)) { + promptsById[prompt.id] = prompt; + } + } + groupedTestCases[datasetId] = { + id: datasetId, + count: 1, + testCases, + recentEvalDate: new Date(createdAt), + recentEvalId: evalId, + prompts: Object.values(promptsById), + }; + } + } + } + + return Object.values(groupedTestCases); +} + +export function getPrompts(limit: number = DEFAULT_QUERY_LIMIT) { + return getPromptsWithPredicate(() => true, limit); +} + +export async function getTestCases(limit: number = DEFAULT_QUERY_LIMIT) { + return getTestCasesWithPredicate(() => true, limit); +} + +export async function getPromptFromHash(hash: string) { + const prompts = await getPrompts(); + for (const prompt of prompts) { + if (prompt.id.startsWith(hash)) { + return prompt; + } + } + return undefined; +} + +export async function getDatasetFromHash(hash: string) { + const datasets = await getTestCases(); + for (const dataset of datasets) { + if (dataset.id.startsWith(hash)) { + return dataset; + } + } + return undefined; +} + +export async function getEvalsWithPredicate( + predicate: (result: ResultsFile) => boolean, + limit: number, +): Promise<EvalWithMetadata[]> { + const db = getDb(); + const evals_ = await db + .select({ + id: evalsTable.id, + createdAt: evalsTable.createdAt, + author: evalsTable.author, + results: evalsTable.results, + config: evalsTable.config, + description: evalsTable.description, + }) + .from(evalsTable) + .orderBy(desc(evalsTable.createdAt)) + .limit(limit) + .all(); + + const ret: EvalWithMetadata[] = []; + + for (const eval_ of evals_) { + const createdAt = new Date(eval_.createdAt).toISOString(); + const resultWrapper: ResultsFile = { + version: 3, + createdAt, + author: eval_.author, + // @ts-ignore + results: eval_.results, + config: eval_.config, + }; + if (predicate(resultWrapper)) { + const evalId = eval_.id; + ret.push({ + id: evalId, + date: new Date(eval_.createdAt), + config: eval_.config, + // @ts-ignore + results: eval_.results, + description: eval_.description || undefined, + }); + } + } + + return ret; +} + +export async function getEvals(limit: number = DEFAULT_QUERY_LIMIT) { + return getEvalsWithPredicate(() => true, limit); +} + +export async function getEvalFromId(hash: string) { + const evals_ = await getEvals(); + for (const eval_ of evals_) { + if (eval_.id.startsWith(hash)) { + return eval_; + } + } + return undefined; +} + +export async function deleteEval(evalId: string) { + const db = getDb(); + await db.transaction(async () => { + // We need to clean up foreign keys first. We don't have onDelete: 'cascade' set on all these relationships. + await db.delete(evalsToPromptsTable).where(eq(evalsToPromptsTable.evalId, evalId)).run(); + await db.delete(evalsToDatasetsTable).where(eq(evalsToDatasetsTable.evalId, evalId)).run(); + await db.delete(evalsToTagsTable).where(eq(evalsToTagsTable.evalId, evalId)).run(); + await db.delete(evalResultsTable).where(eq(evalResultsTable.evalId, evalId)).run(); + + // Finally, delete the eval record + const deletedIds = await db.delete(evalsTable).where(eq(evalsTable.id, evalId)).run(); + if (deletedIds.changes === 0) { + throw new Error(`Eval with ID ${evalId} not found`); + } + }); +} + +/** + * Deletes all evaluations and related records with foreign keys from the database. + * @async + * @returns {Promise<void>} + */ +export async function deleteAllEvals(): Promise<void> { + const db = getDb(); + await db.transaction(async (tx) => { + await tx.delete(evalResultsTable).run(); + await tx.delete(evalsToPromptsTable).run(); + await tx.delete(evalsToDatasetsTable).run(); + await tx.delete(evalsToTagsTable).run(); + await tx.delete(evalsTable).run(); + }); +} + +export type StandaloneEval = CompletedPrompt & { + evalId: string; + description: string | null; + datasetId: string | null; + promptId: string | null; + isRedteam: boolean; + createdAt: number; + + pluginFailCount: Record<string, number>; + pluginPassCount: Record<string, number>; +}; + +const standaloneEvalCache = new NodeCache({ stdTTL: 60 * 60 * 2 }); // Cache for 2 hours + +export async function getStandaloneEvals({ + limit = DEFAULT_QUERY_LIMIT, + tag, + description, +}: { + limit?: number; + tag?: { key: string; value: string }; + description?: string; +} = {}): Promise<StandaloneEval[]> { + const cacheKey = `standalone_evals_${limit}_${tag?.key}_${tag?.value}`;
Include the 'description' parameter in the cache key for getStandaloneEvals to avoid returning stale data for different queries. ```suggestion const cacheKey = `standalone_evals_${limit}_${tag?.key}_${tag?.value}_${description}`; ```
promptfoo
github_2023
typescript
3,184
promptfoo
ellipsis-dev[bot]
@@ -0,0 +1,623 @@ +import { desc, eq, like, and, sql, not } from 'drizzle-orm'; +import NodeCache from 'node-cache'; +import { getDb } from '../database'; +import { + datasetsTable, + evalsTable, + evalsToDatasetsTable, + evalsToPromptsTable, + evalsToTagsTable, + promptsTable, + tagsTable, + evalResultsTable, +} from '../database/tables'; +import { getAuthor } from '../globalConfig/accounts'; +import logger from '../logger'; +import Eval, { createEvalId, getSummaryOfLatestEvals } from '../models/eval'; +import { generateIdFromPrompt } from '../models/prompt'; +import { + type EvalWithMetadata, + type EvaluateTable, + type PromptWithMetadata, + type ResultsFile, + type TestCase, + type TestCasesWithMetadata, + type TestCasesWithMetadataPrompt, + type UnifiedConfig, + type CompletedPrompt, + type ResultLightweight, + type EvaluateSummaryV2, +} from '../types'; +import invariant from '../util/invariant'; +import { sha256 } from './createHash'; + +const DEFAULT_QUERY_LIMIT = 100; + +export async function writeResultsToDatabase( + results: EvaluateSummaryV2, + config: Partial<UnifiedConfig>, + createdAt: Date = new Date(), +): Promise<string> { + createdAt = createdAt || (results.timestamp ? new Date(results.timestamp) : new Date()); + const evalId = createEvalId(createdAt); + const db = getDb(); + + const promises = []; + promises.push( + db + .insert(evalsTable) + .values({ + id: evalId, + createdAt: createdAt.getTime(), + author: getAuthor(), + description: config.description, + config, + results, + }) + .onConflictDoNothing() + .run(), + ); + + logger.debug(`Inserting eval ${evalId}`); + + // Record prompt relation + invariant(results.table, 'Table is required'); + + for (const prompt of results.table.head.prompts) { + const label = prompt.label || prompt.display || prompt.raw; + const promptId = generateIdFromPrompt(prompt); + + promises.push( + db + .insert(promptsTable) + .values({ + id: promptId, + prompt: label, + }) + .onConflictDoNothing() + .run(), + ); + + promises.push( + db + .insert(evalsToPromptsTable) + .values({ + evalId, + promptId, + }) + .onConflictDoNothing() + .run(), + ); + + logger.debug(`Inserting prompt ${promptId}`); + } + + // Record dataset relation + const datasetId = sha256(JSON.stringify(config.tests || [])); + promises.push( + db + .insert(datasetsTable) + .values({ + id: datasetId, + tests: config.tests, + }) + .onConflictDoNothing() + .run(), + ); + + promises.push( + db + .insert(evalsToDatasetsTable) + .values({ + evalId, + datasetId, + }) + .onConflictDoNothing() + .run(), + ); + + logger.debug(`Inserting dataset ${datasetId}`); + + // Record tags + if (config.tags) { + for (const [tagKey, tagValue] of Object.entries(config.tags)) { + const tagId = sha256(`${tagKey}:${tagValue}`); + + promises.push( + db + .insert(tagsTable) + .values({ + id: tagId, + name: tagKey, + value: tagValue, + }) + .onConflictDoNothing() + .run(), + ); + + promises.push( + db + .insert(evalsToTagsTable) + .values({ + evalId, + tagId, + }) + .onConflictDoNothing() + .run(), + ); + + logger.debug(`Inserting tag ${tagId}`); + } + } + + logger.debug(`Awaiting ${promises.length} promises to database...`); + await Promise.all(promises); + + return evalId; +} + +/** + * + * @returns Last n evals in descending order. + */ +export async function listPreviousResults( + limit: number = DEFAULT_QUERY_LIMIT, + filterDescription?: string, + datasetId?: string, +): Promise<ResultLightweight[]> { + const db = getDb(); + const startTime = performance.now(); + + const query = db + .select({ + evalId: evalsTable.id, + createdAt: evalsTable.createdAt, + description: evalsTable.description, + numTests: sql<number>`json_array_length(${evalsTable.results}->'table'->'body')`, + datasetId: evalsToDatasetsTable.datasetId, + isRedteam: sql<boolean>`json_type(${evalsTable.config}, '$.redteam') IS NOT NULL`, + }) + .from(evalsTable) + .leftJoin(evalsToDatasetsTable, eq(evalsTable.id, evalsToDatasetsTable.evalId)) + .where( + and( + datasetId ? eq(evalsToDatasetsTable.datasetId, datasetId) : undefined, + filterDescription ? like(evalsTable.description, `%${filterDescription}%`) : undefined, + not(eq(evalsTable.results, {})), + ), + ); + + const results = query.orderBy(desc(evalsTable.createdAt)).limit(limit).all(); + const mappedResults = results.map((result) => ({ + evalId: result.evalId, + createdAt: result.createdAt, + description: result.description, + numTests: result.numTests, + datasetId: result.datasetId, + isRedteam: result.isRedteam, + })); + + const endTime = performance.now(); + const executionTime = endTime - startTime; + const evalResults = await getSummaryOfLatestEvals(undefined, filterDescription, datasetId); + logger.debug(`listPreviousResults execution time: ${executionTime.toFixed(2)}ms`); + const combinedResults = [...evalResults, ...mappedResults]; + return combinedResults; +} + +export async function readResult( + id: string, +): Promise<{ id: string; result: ResultsFile; createdAt: Date } | undefined> { + try { + const eval_ = await Eval.findById(id); + invariant(eval_, `Eval with ID ${id} not found.`); + return { + id, + result: await eval_.toResultsFile(), + createdAt: new Date(eval_.createdAt), + }; + } catch (err) { + logger.error(`Failed to read result with ID ${id} from database:\n${err}`); + } +} + +export async function updateResult( + id: string, + newConfig?: Partial<UnifiedConfig>, + newTable?: EvaluateTable, +): Promise<void> { + try { + // Fetch the existing eval data from the database + const existingEval = await Eval.findById(id); + + if (!existingEval) { + logger.error(`Eval with ID ${id} not found.`); + return; + } + + if (newConfig) { + existingEval.config = newConfig; + } + if (newTable) { + existingEval.setTable(newTable); + } + + await existingEval.save(); + + logger.info(`Updated eval with ID ${id}`); + } catch (err) { + logger.error(`Failed to update eval with ID ${id}:\n${err}`); + } +} + +export async function getLatestEval(filterDescription?: string): Promise<ResultsFile | undefined> { + const eval_ = await Eval.latest(); + return await eval_?.toResultsFile(); +} + +export async function getPromptsWithPredicate(
Consider using Promise.all to parallelize async operations in getPromptsWithPredicate for better performance.
promptfoo
github_2023
typescript
3,184
promptfoo
ellipsis-dev[bot]
@@ -0,0 +1,623 @@ +import { desc, eq, like, and, sql, not } from 'drizzle-orm'; +import NodeCache from 'node-cache'; +import { getDb } from '../database'; +import { + datasetsTable, + evalsTable, + evalsToDatasetsTable, + evalsToPromptsTable, + evalsToTagsTable, + promptsTable, + tagsTable, + evalResultsTable, +} from '../database/tables'; +import { getAuthor } from '../globalConfig/accounts'; +import logger from '../logger'; +import Eval, { createEvalId, getSummaryOfLatestEvals } from '../models/eval'; +import { generateIdFromPrompt } from '../models/prompt'; +import { + type EvalWithMetadata, + type EvaluateTable, + type PromptWithMetadata, + type ResultsFile, + type TestCase, + type TestCasesWithMetadata, + type TestCasesWithMetadataPrompt, + type UnifiedConfig, + type CompletedPrompt, + type ResultLightweight, + type EvaluateSummaryV2, +} from '../types'; +import invariant from '../util/invariant'; +import { sha256 } from './createHash'; + +const DEFAULT_QUERY_LIMIT = 100; + +export async function writeResultsToDatabase( + results: EvaluateSummaryV2, + config: Partial<UnifiedConfig>, + createdAt: Date = new Date(), +): Promise<string> { + createdAt = createdAt || (results.timestamp ? new Date(results.timestamp) : new Date()); + const evalId = createEvalId(createdAt); + const db = getDb(); + + const promises = []; + promises.push( + db + .insert(evalsTable) + .values({ + id: evalId, + createdAt: createdAt.getTime(), + author: getAuthor(), + description: config.description, + config, + results, + }) + .onConflictDoNothing() + .run(), + ); + + logger.debug(`Inserting eval ${evalId}`); + + // Record prompt relation + invariant(results.table, 'Table is required'); + + for (const prompt of results.table.head.prompts) { + const label = prompt.label || prompt.display || prompt.raw; + const promptId = generateIdFromPrompt(prompt); + + promises.push( + db + .insert(promptsTable) + .values({ + id: promptId, + prompt: label, + }) + .onConflictDoNothing() + .run(), + ); + + promises.push( + db + .insert(evalsToPromptsTable) + .values({ + evalId, + promptId, + }) + .onConflictDoNothing() + .run(), + ); + + logger.debug(`Inserting prompt ${promptId}`); + } + + // Record dataset relation + const datasetId = sha256(JSON.stringify(config.tests || [])); + promises.push( + db + .insert(datasetsTable) + .values({ + id: datasetId, + tests: config.tests, + }) + .onConflictDoNothing() + .run(), + ); + + promises.push( + db + .insert(evalsToDatasetsTable) + .values({ + evalId, + datasetId, + }) + .onConflictDoNothing() + .run(), + ); + + logger.debug(`Inserting dataset ${datasetId}`); + + // Record tags + if (config.tags) { + for (const [tagKey, tagValue] of Object.entries(config.tags)) { + const tagId = sha256(`${tagKey}:${tagValue}`); + + promises.push( + db + .insert(tagsTable) + .values({ + id: tagId, + name: tagKey, + value: tagValue, + }) + .onConflictDoNothing() + .run(), + ); + + promises.push( + db + .insert(evalsToTagsTable) + .values({ + evalId, + tagId, + }) + .onConflictDoNothing() + .run(), + ); + + logger.debug(`Inserting tag ${tagId}`); + } + } + + logger.debug(`Awaiting ${promises.length} promises to database...`); + await Promise.all(promises); + + return evalId; +} + +/** + * + * @returns Last n evals in descending order. + */ +export async function listPreviousResults( + limit: number = DEFAULT_QUERY_LIMIT, + filterDescription?: string, + datasetId?: string, +): Promise<ResultLightweight[]> { + const db = getDb(); + const startTime = performance.now(); + + const query = db + .select({ + evalId: evalsTable.id, + createdAt: evalsTable.createdAt, + description: evalsTable.description, + numTests: sql<number>`json_array_length(${evalsTable.results}->'table'->'body')`, + datasetId: evalsToDatasetsTable.datasetId, + isRedteam: sql<boolean>`json_type(${evalsTable.config}, '$.redteam') IS NOT NULL`, + }) + .from(evalsTable) + .leftJoin(evalsToDatasetsTable, eq(evalsTable.id, evalsToDatasetsTable.evalId)) + .where( + and( + datasetId ? eq(evalsToDatasetsTable.datasetId, datasetId) : undefined, + filterDescription ? like(evalsTable.description, `%${filterDescription}%`) : undefined, + not(eq(evalsTable.results, {})), + ), + ); + + const results = query.orderBy(desc(evalsTable.createdAt)).limit(limit).all(); + const mappedResults = results.map((result) => ({ + evalId: result.evalId, + createdAt: result.createdAt, + description: result.description, + numTests: result.numTests, + datasetId: result.datasetId, + isRedteam: result.isRedteam, + })); + + const endTime = performance.now(); + const executionTime = endTime - startTime; + const evalResults = await getSummaryOfLatestEvals(undefined, filterDescription, datasetId); + logger.debug(`listPreviousResults execution time: ${executionTime.toFixed(2)}ms`); + const combinedResults = [...evalResults, ...mappedResults]; + return combinedResults; +} + +export async function readResult( + id: string, +): Promise<{ id: string; result: ResultsFile; createdAt: Date } | undefined> { + try { + const eval_ = await Eval.findById(id); + invariant(eval_, `Eval with ID ${id} not found.`); + return { + id, + result: await eval_.toResultsFile(), + createdAt: new Date(eval_.createdAt), + }; + } catch (err) { + logger.error(`Failed to read result with ID ${id} from database:\n${err}`); + } +} + +export async function updateResult( + id: string, + newConfig?: Partial<UnifiedConfig>, + newTable?: EvaluateTable, +): Promise<void> { + try {
In updateResult, consider propagating errors instead of just logging them, so that calling code can handle failures appropriately.
promptfoo
github_2023
others
3,183
promptfoo
ellipsis-dev[bot]
@@ -35,6 +35,21 @@ The results of the evaluation are returned as an [`EvaluateSummary` object](/doc A `ProviderFunction` is a Javascript function that implements an LLM API call. It takes a prompt string and a context. It returns the LLM response or an error. See [`ProviderFunction` type](/docs/configuration/reference#providerfunction). +You can load providers using the `loadApiProvider` function: + +```ts
Consider updating the snippet to include an explicit import example for loadApiProvider (e.g. `import { loadApiProvider } from 'promptfoo';`) for clearer guidance. ```suggestion import { loadApiProvider } from 'promptfoo'; ```
promptfoo
github_2023
typescript
3,176
promptfoo
ellipsis-dev[bot]
@@ -13,73 +13,64 @@ const DATASET_URL = interface HarmbenchInput { Behavior: string; - ContextString?: string; // Optional since it may not always be present + ContextString?: string; } -export async function fetchDataset(limit: number): Promise<TestCase[]> { +interface HarmbenchMetadata { + harmbenchBehavior: string; +} + +// Private function - only used within this file +async function fetchDataset(limit: number): Promise<HarmbenchInput[]> { try { const response = await fetchWithTimeout(DATASET_URL, {}, REQUEST_TIMEOUT_MS); if (!response.ok) { - throw new Error(`[harmbench] HTTP status: ${response.status} ${response.statusText}`); + throw new Error(`HTTP status: ${response.status} ${response.statusText}`);
The thrown error omits the '[harmbench]' prefix that previously helped with identification. Ensure consistency in error messages for easier debugging. ```suggestion throw new Error(`[harmbench] HTTP status: ${response.status} ${response.statusText}`); ```
promptfoo
github_2023
typescript
3,176
promptfoo
ellipsis-dev[bot]
@@ -13,73 +13,59 @@ const DATASET_URL = interface HarmbenchInput { Behavior: string; - ContextString?: string; // Optional since it may not always be present + ContextString?: string; } -export async function fetchDataset(limit: number): Promise<TestCase[]> { +async function fetchDataset(limit: number): Promise<HarmbenchInput[]> { try { const response = await fetchWithTimeout(DATASET_URL, {}, REQUEST_TIMEOUT_MS); if (!response.ok) { - throw new Error(`[harmbench] HTTP status: ${response.status} ${response.statusText}`); + throw new Error(`HTTP status: ${response.status} ${response.statusText}`); } const text = await response.text(); - - // Use csvParse to parse the CSV data - const records = csvParse(text, { columns: true }); + const records: HarmbenchInput[] = csvParse(text, { columns: true }); logger.debug(`[harmbench] Parsed ${records.length} entries from CSV`); - // Convert the raw data to test cases and shuffle them - const testCases = records - .map( - (record: HarmbenchInput): TestCase => ({ - vars: { - behavior: record.Behavior, - contextString: record.ContextString || '', - }, - }), - ) - .sort(() => Math.random() - 0.5) // Shuffle the array - .slice(0, limit); // Take the first n items after shuffling - - logger.debug(`[harmbench] Generated ${testCases.length} test cases`); - if (testCases.length === 0) { - throw new Error(`[harmbench] No test cases generated`); + // Shuffle and limit the records + const shuffledRecords = records.sort(() => Math.random() - 0.5).slice(0, limit); + + if (shuffledRecords.length === 0) { + throw new Error('No records generated'); } - return testCases; + logger.debug(`[harmbench] Selected ${shuffledRecords.length} records`); + return shuffledRecords; } catch (error) { - logger.error( - `[harmbench] Error fetching dataset: [harmbench] No test cases generated: ${error}`, - ); + if (error instanceof TypeError) { + logger.error(`[harmbench] Network error: ${error.message}`); + } else { + logger.error(`[harmbench] Error fetching dataset: ${error}`); + } return []; } } -// Stub for the plugin class export class HarmbenchPlugin extends RedteamPluginBase { async getTemplate(): Promise<string> { throw new Error('Not implemented'); } - async generateTests(n: number, delayMs = 0): Promise<TestCase[]> { - const testCases = await fetchDataset(n); + async generateTests(n: number, delayMs: number = 0): Promise<TestCase[]> {
The 'delayMs' parameter is introduced but not used. Consider implementing the delay or removing it if unnecessary. ```suggestion async generateTests(n: number): Promise<TestCase[]> { ```
promptfoo
github_2023
typescript
3,175
promptfoo
ellipsis-dev[bot]
@@ -75,7 +75,7 @@ redteamRouter.post('/run', async (req: Request, res: Response): Promise<void> => } }) .catch((error) => { - console.error('Error running redteam:', error); + logger.error(`Error running redteam: ${error}`);
Consider passing the error object directly (e.g. logger.error('Error running redteam:', error)) to preserve full error details and stack trace instead of using string interpolation. ```suggestion logger.error('Error running redteam:', error); ```
promptfoo
github_2023
typescript
3,175
promptfoo
ellipsis-dev[bot]
@@ -194,7 +194,7 @@ export function createApp() { await telemetry.recordAndSend(event, properties); res.status(200).json({ success: true }); } catch (error) { - console.error('Error processing telemetry request:', error); + logger.error(`Error processing telemetry request: ${error}`);
Consider logging the error object directly (e.g. logger.error('Error processing telemetry request:', error)) instead of interpolating the error, to ensure detailed error info and stack trace are captured. ```suggestion logger.error('Error processing telemetry request:', error); ```
promptfoo
github_2023
typescript
3,175
promptfoo
ellipsis-dev[bot]
@@ -28,7 +29,7 @@ async function fetchAndParseUrl(url: string): Promise<string[]> { .filter(Boolean) .filter((section) => section.includes('\n')); } catch (error) { - console.error(`Error fetching ${url}:`, error); + logger.error(`Error fetching ${url}: ${error}`);
Consider passing the error object as a separate argument to preserve stack traces: e.g. logger.error(`Error fetching ${url}`, error). ```suggestion logger.error(`Error fetching ${url}`, error); ```
promptfoo
github_2023
typescript
3,163
promptfoo
ellipsis-dev[bot]
@@ -1091,7 +1091,14 @@ export function maybeLoadFromExternalFile(filePath: string | object | Function | const contents = fs.readFileSync(finalPath, 'utf8'); if (finalPath.endsWith('.json')) { - return JSON.parse(contents); + // First render any Nunjucks templates in the JSON content + const renderedContents = getNunjucksEngine().renderString(contents, {}); + try { + return JSON.parse(renderedContents); + } catch {
Consider logging a warning or error if JSON parsing fails in maybeLoadFromExternalFile to aid debugging of invalid templated JSON content. ```suggestion } catch (error) { logger.warn(`Failed to parse JSON: ${error}`); ```
promptfoo
github_2023
typescript
3,127
promptfoo
ellipsis-dev[bot]
@@ -0,0 +1,322 @@ +import path from 'path'; +import { providerMap } from '../../src/providers/registry'; +import type { LoadApiProviderContext } from '../../src/types'; +import type { ProviderOptions } from '../../src/types/providers'; + +jest.mock('../../src/providers/adaline.gateway', () => ({ + AdalineGatewayChatProvider: jest.fn().mockImplementation((providerName, modelName) => ({ + id: () => `adaline:${providerName}:chat:${modelName}`, + })), + AdalineGatewayEmbeddingProvider: jest.fn().mockImplementation((providerName, modelName) => ({ + id: () => `adaline:${providerName}:embedding:${modelName}`, + })), +})); + +jest.mock('../../src/providers/pythonCompletion', () => { + return { + PythonProvider: jest.fn().mockImplementation(() => ({ + id: () => 'python:script.py:default', + })), + }; +}); + +describe('Provider Registry', () => { + describe('Provider Factories', () => { + const mockProviderOptions: ProviderOptions = { + id: 'test-provider', + label: 'Test Provider', + config: { + basePath: '/test', + apiKey: 'test-key', + }, + }; + + const mockContext: LoadApiProviderContext = { + basePath: '/test', + options: mockProviderOptions, + }; + + const registry = { + create: async (path: string, context?: any) => { + const factory = providerMap.find((f) => f.test(path)); + if (!factory) { + throw new Error(`Could not find provider for path: ${path}`); + } + return factory.create(path, context?.options || {}, context || mockContext); + }, + }; + + beforeEach(() => { + jest.clearAllMocks(); + }); + + it('should handle adaline provider paths correctly', async () => { + const factory = providerMap.find((f) => f.test('adaline:openai:chat:gpt-4')); + expect(factory).toBeDefined(); + + const chatProvider = await factory!.create( + 'adaline:openai:chat:gpt-4', + mockProviderOptions, + mockContext, + ); + expect(chatProvider.id()).toBe('adaline:openai:chat:gpt-4'); + + const embeddingProvider = await factory!.create( + 'adaline:openai:embedding:text-embedding-3-large', + mockProviderOptions, + mockContext, + ); + expect(embeddingProvider.id()).toBe('adaline:openai:embedding:text-embedding-3-large'); + + await expect( + factory!.create('adaline:invalid', mockProviderOptions, mockContext), + ).rejects.toThrow('Invalid adaline provider path'); + }); + + it('should handle echo provider correctly', async () => { + const factory = providerMap.find((f) => f.test('echo')); + expect(factory).toBeDefined(); + + const provider = await factory!.create('echo', mockProviderOptions, mockContext); + expect(provider.id()).toBe('echo'); + + const result = await provider.callApi('test input'); + expect(result.output).toBe('test input'); + }); + + it('should handle python provider correctly', async () => { + const factory = providerMap.find((f) => f.test('python:script.py')); + expect(factory).toBeDefined(); + + const provider = await factory!.create('python:script.py', mockProviderOptions, { + ...mockContext, + basePath: path.resolve(__dirname, '../fixtures'), + }); + expect(provider).toBeDefined(); + expect(provider.id()).toBe('python:script.py:default'); + }); + + it('should handle huggingface providers correctly', async () => { + const factory = providerMap.find((f) => f.test('huggingface:text-generation:gpt2')); + expect(factory).toBeDefined(); + + const provider = await factory!.create( + 'huggingface:text-generation:gpt2', + mockProviderOptions, + mockContext, + ); + expect(provider).toBeDefined(); + + await expect( + factory!.create('huggingface:invalid:gpt2', mockProviderOptions, mockContext), + ).rejects.toThrow('Invalid Huggingface provider path'); + }); + + it('should handle http/websocket providers correctly', async () => {
Add assertions verifying that any custom configuration passed in the provider options is correctly applied.
promptfoo
github_2023
typescript
3,127
promptfoo
ellipsis-dev[bot]
@@ -0,0 +1,322 @@ +import path from 'path'; +import { providerMap } from '../../src/providers/registry'; +import type { LoadApiProviderContext } from '../../src/types'; +import type { ProviderOptions } from '../../src/types/providers'; + +jest.mock('../../src/providers/adaline.gateway', () => ({ + AdalineGatewayChatProvider: jest.fn().mockImplementation((providerName, modelName) => ({ + id: () => `adaline:${providerName}:chat:${modelName}`, + })), + AdalineGatewayEmbeddingProvider: jest.fn().mockImplementation((providerName, modelName) => ({ + id: () => `adaline:${providerName}:embedding:${modelName}`, + })), +})); + +jest.mock('../../src/providers/pythonCompletion', () => { + return { + PythonProvider: jest.fn().mockImplementation(() => ({ + id: () => 'python:script.py:default', + })), + }; +}); + +describe('Provider Registry', () => { + describe('Provider Factories', () => { + const mockProviderOptions: ProviderOptions = { + id: 'test-provider', + label: 'Test Provider', + config: { + basePath: '/test', + apiKey: 'test-key', + }, + }; + + const mockContext: LoadApiProviderContext = { + basePath: '/test', + options: mockProviderOptions, + }; + + const registry = { + create: async (path: string, context?: any) => { + const factory = providerMap.find((f) => f.test(path)); + if (!factory) { + throw new Error(`Could not find provider for path: ${path}`); + } + return factory.create(path, context?.options || {}, context || mockContext); + }, + }; + + beforeEach(() => { + jest.clearAllMocks(); + }); + + it('should handle adaline provider paths correctly', async () => { + const factory = providerMap.find((f) => f.test('adaline:openai:chat:gpt-4')); + expect(factory).toBeDefined(); + + const chatProvider = await factory!.create( + 'adaline:openai:chat:gpt-4', + mockProviderOptions, + mockContext, + ); + expect(chatProvider.id()).toBe('adaline:openai:chat:gpt-4'); + + const embeddingProvider = await factory!.create( + 'adaline:openai:embedding:text-embedding-3-large', + mockProviderOptions, + mockContext, + ); + expect(embeddingProvider.id()).toBe('adaline:openai:embedding:text-embedding-3-large'); + + await expect( + factory!.create('adaline:invalid', mockProviderOptions, mockContext), + ).rejects.toThrow('Invalid adaline provider path'); + }); + + it('should handle echo provider correctly', async () => { + const factory = providerMap.find((f) => f.test('echo')); + expect(factory).toBeDefined(); + + const provider = await factory!.create('echo', mockProviderOptions, mockContext); + expect(provider.id()).toBe('echo'); + + const result = await provider.callApi('test input'); + expect(result.output).toBe('test input'); + }); + + it('should handle python provider correctly', async () => { + const factory = providerMap.find((f) => f.test('python:script.py')); + expect(factory).toBeDefined(); + + const provider = await factory!.create('python:script.py', mockProviderOptions, { + ...mockContext, + basePath: path.resolve(__dirname, '../fixtures'), + }); + expect(provider).toBeDefined(); + expect(provider.id()).toBe('python:script.py:default'); + }); + + it('should handle huggingface providers correctly', async () => { + const factory = providerMap.find((f) => f.test('huggingface:text-generation:gpt2')); + expect(factory).toBeDefined(); + + const provider = await factory!.create( + 'huggingface:text-generation:gpt2', + mockProviderOptions, + mockContext, + ); + expect(provider).toBeDefined(); + + await expect( + factory!.create('huggingface:invalid:gpt2', mockProviderOptions, mockContext), + ).rejects.toThrow('Invalid Huggingface provider path'); + }); + + it('should handle http/websocket providers correctly', async () => { + const httpProvider = await registry.create('http://example.com', { + options: { + config: { + url: 'http://example.com', + body: { prompt: '{{input}}' }, + }, + }, + }); + expect(httpProvider.id()).toBe('http://example.com'); + + const wsProvider = await registry.create('ws://example.com', { + options: { + config: { + url: 'ws://example.com', + messageTemplate: '{"message": "{{input}}"}', + body: { prompt: '{{input}}' }, + }, + }, + }); + expect(wsProvider.id()).toBe('ws://example.com'); + }); + + it('should handle redteam providers correctly', async () => { + const redteamPaths = [ + 'promptfoo:redteam:best-of-n', + 'promptfoo:redteam:crescendo', + 'promptfoo:redteam:goat', + 'promptfoo:redteam:iterative', + 'promptfoo:redteam:iterative:image', + 'promptfoo:redteam:iterative:tree', + 'promptfoo:redteam:pandamonium', + ]; + + const redteamConfig = { + ...mockProviderOptions, + config: { + ...mockProviderOptions.config, + injectVar: 'test', + maxRounds: 3, + maxBacktracks: 2, + redteamProvider: 'test-provider', + }, + }; + + for (const path of redteamPaths) { + const factory = providerMap.find((f) => f.test(path)); + expect(factory).toBeDefined(); + + const provider = await factory!.create(path, redteamConfig, mockContext); + expect(provider).toBeDefined(); + expect(provider.id()).toEqual(path); + } + }); + + it('should handle anthropic providers correctly', async () => { + const factory = providerMap.find((f) => f.test('anthropic:messages:claude-3')); + expect(factory).toBeDefined(); + + const messagesProvider = await factory!.create( + 'anthropic:messages:claude-3', + mockProviderOptions, + mockContext, + ); + expect(messagesProvider).toBeDefined(); + + const completionProvider = await factory!.create( + 'anthropic:completion:claude-2', + mockProviderOptions, + mockContext, + ); + expect(completionProvider).toBeDefined(); + + await expect( + factory!.create('anthropic:invalid:model', mockProviderOptions, mockContext), + ).rejects.toThrow('Unknown Anthropic model type'); + }); + + it('should handle azure providers correctly', async () => { + const factory = providerMap.find((f) => f.test('azure:chat:gpt-4')); + expect(factory).toBeDefined(); + + const chatProvider = await factory!.create( + 'azure:chat:gpt-4', + mockProviderOptions, + mockContext, + ); + expect(chatProvider).toBeDefined(); + + const assistantProvider = await factory!.create( + 'azure:assistant:asst_123', + mockProviderOptions, + mockContext, + ); + expect(assistantProvider).toBeDefined(); + + const embeddingProvider = await factory!.create( + 'azure:embedding', + mockProviderOptions, + mockContext, + ); + expect(embeddingProvider).toBeDefined(); + + const completionProvider = await factory!.create( + 'azure:completion:davinci', + mockProviderOptions, + mockContext, + ); + expect(completionProvider).toBeDefined(); + + await expect( + factory!.create('azure:invalid:model', mockProviderOptions, mockContext), + ).rejects.toThrow('Unknown Azure model type'); + }); + + it('should handle bedrock providers correctly', async () => { + const factory = providerMap.find((f) => f.test('bedrock:completion:anthropic.claude-v2')); + expect(factory).toBeDefined(); + + const completionProvider = await factory!.create( + 'bedrock:completion:anthropic.claude-v2', + mockProviderOptions, + mockContext, + ); + expect(completionProvider).toBeDefined(); + + const embeddingProvider = await factory!.create( + 'bedrock:embedding:amazon.titan-embed-text-v1', + mockProviderOptions, + mockContext, + ); + expect(embeddingProvider).toBeDefined(); + + // Test backwards compatibility + const legacyProvider = await factory!.create( + 'bedrock:anthropic.claude-v2', + mockProviderOptions, + mockContext, + ); + expect(legacyProvider).toBeDefined(); + }); + + it('should handle cloudflare-ai providers correctly', async () => { + const factory = providerMap.find((f) => + f.test('cloudflare-ai:chat:@cf/meta/llama-2-7b-chat-fp16'), + ); + expect(factory).toBeDefined(); + + const chatProvider = await factory!.create( + 'cloudflare-ai:chat:@cf/meta/llama-2-7b-chat-fp16', + mockProviderOptions, + mockContext, + ); + expect(chatProvider).toBeDefined(); + + const embeddingProvider = await factory!.create( + 'cloudflare-ai:embedding:@cf/baai/bge-base-en-v1.5', + mockProviderOptions, + mockContext, + ); + expect(embeddingProvider).toBeDefined(); + + const completionProvider = await factory!.create( + 'cloudflare-ai:completion:@cf/meta/llama-2-7b-chat-fp16', + mockProviderOptions, + mockContext, + ); + expect(completionProvider).toBeDefined(); + + await expect( + factory!.create('cloudflare-ai:invalid:model', mockProviderOptions, mockContext), + ).rejects.toThrow('Unknown Cloudflare AI model type'); + }); + + it('should handle ollama providers correctly', async () => { + const factory = providerMap.find((f) => f.test('ollama:llama-3.3')); + expect(factory).toBeDefined(); + + const defaultProvider = await factory!.create( + 'ollama:llama-3.3', + mockProviderOptions, + mockContext, + ); + expect(defaultProvider).toBeDefined(); + + const chatProvider = await factory!.create( + 'ollama:chat:llama-3.3', + mockProviderOptions, + mockContext, + ); + expect(chatProvider).toBeDefined(); + + const completionProvider = await factory!.create( + 'ollama:completion:llama-3.3', + mockProviderOptions, + mockContext, + ); + expect(completionProvider).toBeDefined(); + + const embeddingProvider = await factory!.create( + 'ollama:embedding:llama-3.3',
Add tests for any remaining provider factories (e.g. for replicate, togetherai, vertex, xai) to ensure full coverage.
promptfoo
github_2023
typescript
3,127
promptfoo
typpo
@@ -0,0 +1,237 @@ +import chalk from 'chalk'; +import dedent from 'dedent'; +import fs from 'fs'; +import yaml from 'js-yaml'; +import path from 'path'; +import cliState from '../cliState'; +import logger from '../logger'; +import type { LoadApiProviderContext, TestSuiteConfig } from '../types'; +import type { EnvOverrides } from '../types/env'; +import type { ApiProvider, ProviderOptions, ProviderOptionsMap } from '../types/providers'; +import invariant from '../util/invariant'; +import { getNunjucksEngine } from '../util/templates'; +import { AI21ChatCompletionProvider } from './ai21'; +import { AnthropicCompletionProvider, AnthropicMessagesProvider } from './anthropic'; +import { + AzureAssistantProvider, + AzureChatCompletionProvider, + AzureCompletionProvider, + AzureEmbeddingProvider, +} from './azure'; +import { BAMChatProvider, BAMEmbeddingProvider } from './bam'; +import { AwsBedrockCompletionProvider, AwsBedrockEmbeddingProvider } from './bedrock'; +import { BrowserProvider } from './browser'; +import { ClouderaAiChatCompletionProvider } from './cloudera'; +import { CohereChatCompletionProvider, CohereEmbeddingProvider } from './cohere'; +import { FalImageGenerationProvider } from './fal'; +import { GolangProvider } from './golangCompletion'; +import { GoogleChatProvider } from './google'; +import { GroqProvider } from './groq'; +import { HttpProvider } from './http'; +import { + HuggingfaceFeatureExtractionProvider, + HuggingfaceSentenceSimilarityProvider, + HuggingfaceTextClassificationProvider, + HuggingfaceTextGenerationProvider, + HuggingfaceTokenExtractionProvider, +} from './huggingface'; +import { LlamaProvider } from './llama'; +import { + LocalAiCompletionProvider, + LocalAiChatProvider, + LocalAiEmbeddingProvider, +} from './localai'; +import { ManualInputProvider } from './manualInput'; +import { MistralChatCompletionProvider, MistralEmbeddingProvider } from './mistral';
Nice change. Instead of importing everything here _and_ in the registry, is there a one or two-line approach where the registry does the exports and we just pass them through?
promptfoo
github_2023
typescript
3,154
promptfoo
ellipsis-dev[bot]
@@ -12,192 +14,398 @@ import TableHead from '@mui/material/TableHead'; import TableRow from '@mui/material/TableRow'; import TableSortLabel from '@mui/material/TableSortLabel'; import Tooltip from '@mui/material/Tooltip'; +import Typography from '@mui/material/Typography'; +import { visuallyHidden } from '@mui/utils'; import type { TestCase, TestCasesWithMetadata } from '@promptfoo/types'; import DatasetDialog from './DatasetDialog'; -const rowsPerPage = 10; +const ROWS_PER_PAGE = 10; -export default function Datasets() { - const [searchParams] = useSearchParams(); +type SortableField = 'id' | 'raw' | 'date' | 'count' | 'evalId' | null; + +interface DatasetsProps { + data: (TestCasesWithMetadata & { recentEvalDate: string })[]; + isLoading: boolean; + error: string | null; +} + +// Custom hooks to separate concerns +const useSortableData = (data: DatasetsProps['data']) => { + const [sortField, setSortField] = React.useState<SortableField>('date'); + const [sortOrder, setSortOrder] = React.useState<'asc' | 'desc'>('desc'); + + const handleSort = React.useCallback( + (field: SortableField) => { + setSortOrder((prevOrder) => (sortField === field && prevOrder === 'asc' ? 'desc' : 'asc')); + setSortField(field); + }, + [sortField], + ); + + const sortedData = React.useMemo(() => { + if (!sortField) { + return data; + } - const [testCases, setTestCases] = useState< - (TestCasesWithMetadata & { recentEvalDate: string })[] - >([]); - const [sortField, setSortField] = useState<string | null>('date'); - const [sortOrder, setSortOrder] = useState<'asc' | 'desc'>('desc'); - const [page, setPage] = useState(1); - const [openDialog, setOpenDialog] = useState(false); - const [dialogTestCaseIndex, setDialogTestCaseIndex] = useState(0); - const [isLoading, setIsLoading] = useState(true); - const hasShownPopup = useRef(false); - - const handleSort = (field: string) => { - const order = sortField === field && sortOrder === 'asc' ? 'desc' : 'asc'; - setSortField(field); - setSortOrder(order); - }; - - useEffect(() => { - (async () => { - setIsLoading(true); - try { - const response = await callApi(`/datasets`); - const data = await response.json(); - const sortedData = [...data.data].sort((a, b) => { - if (sortField === null) { - return 0; - } - if (sortOrder === 'asc') { - return a[sortField] > b[sortField] ? 1 : -1; - } - return a[sortField] < b[sortField] ? 1 : -1; - }); - setTestCases(sortedData); - } finally { - setIsLoading(false); + return [...data].sort((a, b) => { + let aValue: string | number; + let bValue: string | number; + + switch (sortField) { + case 'date': + aValue = a.recentEvalDate || ''; + bValue = b.recentEvalDate || ''; + break; + case 'count': + aValue = a.count || 0; + bValue = b.count || 0; + break; + case 'evalId': + aValue = a.recentEvalId || ''; + bValue = b.recentEvalId || ''; + break; + case 'id': + aValue = a.id; + bValue = b.id; + break; + case 'raw': + aValue = a.testCases.length.toString();
Use numeric comparison for 'raw' sort instead of converting lengths to string; string compare may mis-order numbers.
promptfoo
github_2023
typescript
3,150
promptfoo
ellipsis-dev[bot]
@@ -7,56 +7,220 @@ import useMediaQuery from '@mui/material/useMediaQuery'; const createAppTheme = (darkMode: boolean) => createTheme({ typography: { - fontFamily: 'inherit', + fontFamily: '"Inter", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif', + /* + // TODO(ian): Uncomment once we've standardized on Typography + h1: { + fontWeight: 700, + fontSize: '2.5rem', + }, + h2: { + fontWeight: 600, + fontSize: '2rem', + }, + h3: { + fontWeight: 600, + fontSize: '1.5rem', + }, + h4: { + fontWeight: 600, + fontSize: '1.25rem', + }, + */ + button: { + textTransform: 'none', + fontWeight: 500, + }, + }, + shape: { + borderRadius: 12, }, palette: { mode: darkMode ? 'dark' : 'light', + primary: { + main: '#2563eb', // Modern blue + light: '#3b82f6', + dark: '#1d4ed8', + contrastText: '#ffffff', + }, + secondary: { + main: '#8b5cf6', // Modern purple + light: '#a78bfa', + dark: '#7c3aed', + contrastText: '#ffffff', + }, background: { - default: '#ffffff', // Set all MUI components to have a white background + default: darkMode ? '#0f172a' : '#f8fafc', + paper: darkMode ? '#1e293b' : '#ffffff', + }, + text: { + primary: darkMode ? '#f1f5f9' : '#0f172a', + secondary: darkMode ? '#94a3b8' : '#475569', }, }, components: { + MuiButton: { + styleOverrides: { + root: { + borderRadius: '8px', + textTransform: 'none', + fontWeight: 500, + padding: '8px 16px', + transition: 'all 0.2s ease-in-out',
Extract common transition values (duration and easing) into theme constants to ensure consistency across components and simplify future adjustments.
promptfoo
github_2023
typescript
3,145
promptfoo
ellipsis-dev[bot]
@@ -225,8 +225,8 @@ export async function fetchWithRetries( const waitTime = Math.pow(2, i) * (backoff + 1000 * Math.random()); await sleep(waitTime); } - lastError = error; + lastError = errorMessage;
Update stores errorMessage (a string) instead of the raw error. Consider renaming the variable (e.g. lastErrorMessage) to reflect that it's a string, for clarity.