Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions docs/promptfoo-plugin.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ crab pf "curl -X POST http://localhost:8080/chat -d '{\"message\":\"hi\"}'"
crab pf --file api-spec.json --output ./my-config

# Use Anthropic instead of OpenAI
crab pf --file target.txt --provider anthropic:claude-sonnet-4-20250514
crab pf --file target.txt --provider anthropic:claude-sonnet-5-5

# Verbose output (see agent reasoning)
crab pf --file target.txt --verbose
Expand Down Expand Up @@ -101,7 +101,7 @@ promptfoo eval
|----------|-------------|
| `OPENAI_API_KEY` | OpenAI API key |
| `ANTHROPIC_API_KEY` | Anthropic API key |
| `DISCOVERY_PROVIDER` | Default provider (e.g., `anthropic:claude-sonnet-4-20250514`) |
| `DISCOVERY_PROVIDER` | Default provider (e.g., `anthropic:claude-sonnet-5-5`) |

## Uninstall

Expand Down
7 changes: 6 additions & 1 deletion plugins/promptfoo/src/agent/loop.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,11 @@ Steps:
console.log('Agent:', response.content);
}
state.logs.push(`Turn ${turn}: ${response.content.slice(0, 100)}...`);
messages.push({ role: 'assistant', content: response.content });
messages.push({
role: 'assistant',
content: response.content,
anthropicContent: response.anthropicContent,
});

if (response.finishReason === 'stop') {
messages.push({
Expand Down Expand Up @@ -152,6 +156,7 @@ Steps:
role: 'assistant',
content: response.content || '',
toolCalls: response.toolCalls,
anthropicContent: response.anthropicContent,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Retry truncated thinking instead of replaying it as a prefill

If adaptive thinking exhausts the provider's 4096-token default before producing text or tool calls, Anthropic returns max_tokens, response.content is null, and toolCalls is empty. This branch then stores the thinking-only assistant message without adding a subsequent user or tool-result turn. The next request consequently ends with that assistant message, which Anthropic rejects because assistant prefilling is unsupported with thinking enabled, aborting discovery. Handle finishReason === 'length' by retrying with a larger token budget, or explicitly disable thinking, rather than replaying the truncated thinking-only response.

Useful? React with 👍 / 👎.

});

// 5. Add tool results — include error in content so LLM can reason about failures
Expand Down
27 changes: 20 additions & 7 deletions plugins/promptfoo/src/agent/providers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,18 @@
* Allows the agent to work with OpenAI or Anthropic.
*/

type AnthropicContentBlock =
| { type: 'text'; text: string }
| { type: 'tool_use'; id: string; name: string; input: Record<string, unknown> }
| { type: 'thinking'; thinking: string; signature: string }
| { type: 'redacted_thinking'; data: string };

export interface Message {
role: 'system' | 'user' | 'assistant' | 'tool';
content: string;
toolCallId?: string;
toolCalls?: ToolCall[];
anthropicContent?: AnthropicContentBlock[];
}

export interface ToolCall {
Expand All @@ -28,6 +35,7 @@ export interface ChatOptions {
export interface ChatResponse {
content: string | null;
toolCalls: ToolCall[];
anthropicContent?: AnthropicContentBlock[];
finishReason: 'stop' | 'tool_calls' | 'length' | 'error';
}

Expand Down Expand Up @@ -154,7 +162,7 @@ export class AnthropicProvider implements LLMProvider {

constructor(options: { apiKey?: string; model?: string; baseUrl?: string }) {
this.apiKey = options.apiKey || process.env.ANTHROPIC_API_KEY || '';
this.model = options.model || 'claude-sonnet-4-20250514';
this.model = options.model || 'claude-sonnet-5-5';

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Preserve thinking blocks before adopting the thinking-enabled default

When Sonnet 5.5 uses its default adaptive thinking before a tool call, the existing response parser discards its thinking/redacted_thinking blocks, and runDiscoveryAgent reconstructs an assistant message containing only the tool calls. toAnthropicMessage() consequently sends only tool_use blocks on the next request. Anthropic requires the original signed thinking blocks when continuing with the corresponding tool results, so this causes the next /messages request to be rejected and aborts multi-turn discovery. Either explicitly disable thinking for this provider or preserve the untouched thinking blocks through ChatResponse, Message, and assistant-message serialization before making this the default.

Useful? React with 👍 / 👎.

this.baseUrl = options.baseUrl || 'https://api.anthropic.com/v1';

if (!this.apiKey) {
Expand All @@ -179,7 +187,10 @@ export class AnthropicProvider implements LLMProvider {
messages: nonSystemMessages.map((m) => this.toAnthropicMessage(m)),
tools: options.tools,
max_tokens: options.maxTokens || 4096,
temperature: options.temperature ?? 0.7,
// Claude Sonnet 5.5 rejects sampling parameters even when explicitly set.
...(this.model !== 'claude-sonnet-5-5' && options.temperature !== undefined
? { temperature: options.temperature }
: {}),
}),
});

Expand All @@ -189,10 +200,7 @@ export class AnthropicProvider implements LLMProvider {
}

const data = (await response.json()) as {
content: Array<
| { type: 'text'; text: string }
| { type: 'tool_use'; id: string; name: string; input: Record<string, unknown> }
>;
content: AnthropicContentBlock[];
stop_reason: string;
};

Expand All @@ -214,6 +222,7 @@ export class AnthropicProvider implements LLMProvider {
return {
content: textContent || null,
toolCalls,
anthropicContent: data.content,
finishReason: this.mapFinishReason(data.stop_reason),
};
}
Expand All @@ -231,6 +240,10 @@ export class AnthropicProvider implements LLMProvider {
],
};
}
if (m.role === 'assistant' && m.anthropicContent?.length) {
// Anthropic requires the original signed blocks in their original order.
return { role: 'assistant', content: m.anthropicContent };
}
if (m.role === 'assistant' && m.toolCalls?.length) {
return {
role: 'assistant',
Expand Down Expand Up @@ -269,7 +282,7 @@ export function createProvider(provider: string, options?: { reasoningEffort?: s
case 'openai':
return new OpenAIProvider({ model: model || 'gpt-5', reasoningEffort: options?.reasoningEffort });
case 'anthropic':
return new AnthropicProvider({ model: model || 'claude-sonnet-4-20250514' });
return new AnthropicProvider({ model: model || 'claude-sonnet-5-5' });
default:
throw new Error(`Unknown provider: ${type}. Supported: openai, anthropic`);
}
Expand Down
4 changes: 2 additions & 2 deletions plugins/promptfoo/src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ Supported input formats:
Environment variables:
OPENAI_API_KEY OpenAI API key
ANTHROPIC_API_KEY Anthropic API key
DISCOVERY_PROVIDER Default provider (e.g., anthropic:claude-sonnet-4-20250514)
DISCOVERY_PROVIDER Default provider (e.g., anthropic:claude-sonnet-5-5)

Examples:
# From curl command
Expand All @@ -165,7 +165,7 @@ Examples:
crab pf --file betty-api.txt --output ./betty-config

# Using Anthropic
crab pf --file target.txt --provider anthropic:claude-sonnet-4-20250514
crab pf --file target.txt --provider anthropic:claude-sonnet-5-5

Subcommands:
serve Run Slack polling daemon
Expand Down
97 changes: 97 additions & 0 deletions plugins/promptfoo/test/providers.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
import { afterEach, expect, test, vi } from 'vitest';
import { runDiscoveryAgent } from '../src/agent/loop.js';
import { AnthropicProvider, createProvider } from '../src/agent/providers.js';

afterEach(() => {
vi.unstubAllGlobals();
vi.unstubAllEnvs();
});

async function sentBody(chat: () => Promise<unknown>, fetchMock: ReturnType<typeof vi.fn>) {
await chat();
return JSON.parse(fetchMock.mock.calls[0][1].body);
}

function stubAnthropic() {
const fetchMock = vi.fn(async () =>
new Response(JSON.stringify({ content: [{ type: 'text', text: 'ok' }], stop_reason: 'end_turn' })),
);
vi.stubGlobal('fetch', fetchMock);
vi.stubEnv('ANTHROPIC_API_KEY', 'fixture-key');
return fetchMock;
}

test.each([
['createProvider', () => createProvider('anthropic')],
['AnthropicProvider', () => new AnthropicProvider({})],
])('%s defaults to a supported model without sampling parameters', async (_name, build) => {
const fetchMock = stubAnthropic();
const body = await sentBody(() => build().chat({ messages: [], tools: [] }), fetchMock);
expect(body.model).toBe('claude-sonnet-5-5');
expect(body).not.toHaveProperty('temperature');
});

test('forwards an explicit temperature to Anthropic', async () => {
const fetchMock = stubAnthropic();
const body = await sentBody(
() => createProvider('anthropic:claude-sonnet-4-6').chat({ messages: [], tools: [], temperature: 0 }),
fetchMock,
);
expect(body.temperature).toBe(0);
});

test('omits explicit temperature on Sonnet 5.5 and keeps the requested output limit', async () => {
const fetchMock = stubAnthropic();
const body = await sentBody(
() => createProvider('anthropic:claude-sonnet-5-5').chat({
messages: [],
tools: [],
temperature: 0,
maxTokens: 8192,
}),
fetchMock,
);
expect(body).not.toHaveProperty('temperature');
expect(body.max_tokens).toBe(8192);
});

test('replays signed thinking with Anthropic tool results on the next discovery turn', async () => {
const content = [
{ type: 'thinking', thinking: '', signature: 'fixture-signature' },
{ type: 'text', text: 'I will try a tool.' },
{ type: 'tool_use', id: 'toolu_first', name: 'unknown_fixture_tool', input: {} },
];
const fetchMock = stubAnthropic();
fetchMock
.mockResolvedValueOnce(new Response(JSON.stringify({ content, stop_reason: 'tool_use' })))
.mockResolvedValueOnce(new Response(JSON.stringify({
content: [{
type: 'tool_use',
id: 'toolu_done',
name: 'done',
input: { summary: 'Complete', verified: true },
}],
stop_reason: 'tool_use',
})));

const result = await runDiscoveryAgent({
context: 'Fixture target',
provider: createProvider('anthropic'),
maxTurns: 2,
});

expect(result.success).toBe(true);
expect(fetchMock).toHaveBeenCalledTimes(2);
const body = JSON.parse(fetchMock.mock.calls[1][1].body);
expect(body.messages.slice(-2)).toEqual([
{ role: 'assistant', content },
{
role: 'user',
content: [{
type: 'tool_result',
tool_use_id: 'toolu_first',
content: JSON.stringify({ error: 'Unknown tool: unknown_fixture_tool' }),
}],
},
]);
});