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
F... |
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 [Goo... | 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(f... | 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.... |
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 {
... | 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: 'inheri... |
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 {
... | 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 {
... | 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(): ... | 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:
+ ... | 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 '../..... | 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 '../..... | 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.
+No... | 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... | 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... | 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... | 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/e... | 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/e... | 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/e... | 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_ENDPOI... | 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 ===... | ```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 } fro... | 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 } fro... | 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 } fro... | 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 } fro... | 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
+ ... | 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.... |
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 a... | 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 provi... | 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(pr... |
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 a... | 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 mockFetchWithPro... | ## 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/provi... | 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()... | 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('PA... | 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
);
+ ... | 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 configura... | 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 ... | 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');
+ ... | 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 ... | 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... |
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... | 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) {
... | 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 titl... |
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:
+ temper... | 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://p... | 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://p... | 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... | 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, ''));
- }... | 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', '... | 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'] },
+ ... | 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 =... | 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:
... | 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> {
... | 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 = { ...parsedCachedResp... | 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 ... | 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.
```sug... |
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 genera... | 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 {
... | 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 CircularProgre... | 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 CircularProgre... | 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 CircularProgre... | 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 ... | 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}}'"
+
+provid... | 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 tr... | 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 th... |
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 agains... | Inconsistent image reference: document title and content refer to Claude 3.7, but the image now shows Claude 3.5.
```suggestion

``` |
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';
+
+jes... | 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 fil... | 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,
... | 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,
... | 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,
... | 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,
... | 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/referen... | 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 {
+ harmbenchBehavi... | 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): Prom... | 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 renderedCon... | 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', () => ({
+ AdalineGatewayChatPr... | 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', () => ({
+ AdalineGatewayChatPr... | 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 { EnvOverr... | 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... | 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): Unc... | 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. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.