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
5 changes: 4 additions & 1 deletion js/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,10 @@
},
"pnpm": {
"overrides": {
"cross-spawn": "^7.0.5"
"cross-spawn": "^7.0.5",
"@genkit-ai/vertexai>@anthropic-ai/sdk": "^0.24.3",
"@anthropic-ai/vertex-sdk>@anthropic-ai/sdk": "^0.24.3",
"@genkit-ai/anthropic>@anthropic-ai/sdk": "^0.71.2"
}
},
"packageManager": "pnpm@10.26.0+sha512.3b3f6c725ebe712506c0ab1ad4133cf86b1f4b687effce62a9b38b4d72e3954242e643190fc51fa1642949c735f403debd44f5cb0edd657abe63a8b6a7e1e402"
Expand Down
3 changes: 2 additions & 1 deletion js/plugins/anthropic/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
"genkit": "workspace:^"
},
"dependencies": {
"@anthropic-ai/sdk": "^0.68.0"
"@anthropic-ai/sdk": "^0.71.2"
},
"devDependencies": {
"@types/node": "^20.11.16",
Expand Down Expand Up @@ -64,6 +64,7 @@
"build": "npm-run-all build:clean check compile",
"build:watch": "tsup-node --watch",
"test": "tsx --test tests/*_test.ts",
"test:live": "tsx --test tests/live_test.ts",
"test:file": "tsx --test",
"test:live": "tsx --test tests/live_test.ts",
"test:coverage": "check-node-version --node '>=22' && tsx --test --experimental-test-coverage --test-coverage-include='src/**/*.ts' ./tests/**/*_test.ts"
Expand Down
56 changes: 49 additions & 7 deletions js/plugins/anthropic/src/models.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,19 +91,59 @@ export const KNOWN_CLAUDE_MODELS: Record<
'claude-opus-4': commonRef('claude-opus-4', AnthropicThinkingConfigSchema),
'claude-sonnet-4-5': commonRef(
'claude-sonnet-4-5',
AnthropicThinkingConfigSchema
AnthropicThinkingConfigSchema,
{
supports: {
multiturn: true,
tools: true,
media: true,
systemRole: true,
output: ['text', 'json'],
constrained: 'all',
},
}
),
'claude-haiku-4-5': commonRef(
'claude-haiku-4-5',
AnthropicThinkingConfigSchema
AnthropicThinkingConfigSchema,
{
supports: {
multiturn: true,
tools: true,
media: true,
systemRole: true,
output: ['text', 'json'],
constrained: 'all',
},
}
),
'claude-opus-4-5': commonRef(
'claude-opus-4-5',
AnthropicThinkingConfigSchema
AnthropicThinkingConfigSchema,
{
supports: {
multiturn: true,
tools: true,
media: true,
systemRole: true,
output: ['text', 'json'],
constrained: 'all',
},
}
),
'claude-opus-4-1': commonRef(
'claude-opus-4-1',
AnthropicThinkingConfigSchema
AnthropicThinkingConfigSchema,
{
supports: {
multiturn: true,
tools: true,
media: true,
systemRole: true,
output: ['text', 'json'],
constrained: 'all',
},
}
),
};

Expand Down Expand Up @@ -232,9 +272,11 @@ export function claudeModel(
defaultApiVersion: apiVersion,
} = params;
// Use supported model ref if available, otherwise create generic model ref
const modelRef = KNOWN_CLAUDE_MODELS[name];
const modelInfo = modelRef ? modelRef.info : GENERIC_CLAUDE_MODEL_INFO;
const configSchema = modelRef?.configSchema ?? AnthropicConfigSchema;
const knownModelRef = KNOWN_CLAUDE_MODELS[name];
let modelInfo = knownModelRef
? knownModelRef.info
: GENERIC_CLAUDE_MODEL_INFO;
const configSchema = knownModelRef?.configSchema ?? AnthropicConfigSchema;

return model<
AnthropicBaseConfigSchemaType | AnthropicThinkingConfigSchemaType
Expand Down
84 changes: 75 additions & 9 deletions js/plugins/anthropic/src/runner/beta.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,57 @@ const BETA_UNSUPPORTED_SERVER_TOOL_BLOCK_TYPES = new Set<string>([
'container_upload',
]);

const BETA_APIS = [
// 'message-batches-2024-09-24',
// 'prompt-caching-2024-07-31',
// 'computer-use-2025-01-24',
// 'pdfs-2024-09-25',
// 'token-counting-2024-11-01',
// 'token-efficient-tools-2025-02-19',
// 'output-128k-2025-02-19',
// 'files-api-2025-04-14',
// 'mcp-client-2025-04-04',
// 'dev-full-thinking-2025-05-14',
// 'interleaved-thinking-2025-05-14',
// 'code-execution-2025-05-22',
// 'extended-cache-ttl-2025-04-11',
// 'context-1m-2025-08-07',
// 'context-management-2025-06-27',
// 'model-context-window-exceeded-2025-08-26',
// 'skills-2025-10-02',
// 'effort-param-2025-11-24',
// 'advanced-tool-use-2025-11-20',
'structured-outputs-2025-11-13',
];

/**
* Transforms a JSON schema to be compatible with Anthropic's structured output requirements.
* Anthropic requires `additionalProperties: false` on all object types.
Copy link
Collaborator

Choose a reason for hiding this comment

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

really? interesting...

Copy link
Contributor Author

Choose a reason for hiding this comment

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

* @see https://docs.anthropic.com/en/docs/build-with-claude/structured-outputs#json-schema-limitations
*/
function toAnthropicSchema(
schema: Record<string, unknown>
): Record<string, unknown> {
const out = structuredClone(schema);

// Remove $schema if present
delete out.$schema;

// Add additionalProperties: false to objects
if (out.type === 'object') {
out.additionalProperties = false;
}

// Recursively process nested objects
for (const key in out) {
if (typeof out[key] === 'object' && out[key] !== null) {
out[key] = toAnthropicSchema(out[key] as Record<string, unknown>);
}
}

return out;
}

const unsupportedServerToolError = (blockType: string): string =>
`Anthropic beta runner does not yet support server-managed tool block '${blockType}'. Please retry against the stable API or wait for dedicated support.`;

Expand Down Expand Up @@ -254,6 +305,7 @@ export class BetaRunner extends BaseRunner<BetaRunnerTypes> {
max_tokens:
request.config?.maxOutputTokens ?? this.DEFAULT_MAX_OUTPUT_TOKENS,
messages,
betas: BETA_APIS,
};

if (betaSystem !== undefined) body.system = betaSystem;
Expand Down Expand Up @@ -281,10 +333,12 @@ export class BetaRunner extends BaseRunner<BetaRunnerTypes> {
body.thinking = thinkingConfig as BetaMessageCreateParams['thinking'];
}

if (request.output?.format && request.output.format !== 'text') {
throw new Error(
`Only text output format is supported for Claude models currently`
);
// Apply structured output when model supports it and constrained output is requested
if (this.isStructuredOutputEnabled(request)) {
body.output_format = {
type: 'json_schema',
schema: toAnthropicSchema(request.output!.schema!),
};
}

return body;
Expand Down Expand Up @@ -322,6 +376,7 @@ export class BetaRunner extends BaseRunner<BetaRunnerTypes> {
request.config?.maxOutputTokens ?? this.DEFAULT_MAX_OUTPUT_TOKENS,
messages,
stream: true,
betas: BETA_APIS,
};

if (betaSystem !== undefined) body.system = betaSystem;
Expand Down Expand Up @@ -349,12 +404,13 @@ export class BetaRunner extends BaseRunner<BetaRunnerTypes> {
body.thinking = thinkingConfig as BetaMessageCreateParams['thinking'];
}

if (request.output?.format && request.output.format !== 'text') {
throw new Error(
`Only text output format is supported for Claude models currently`
);
// Apply structured output when model supports it and constrained output is requested
if (this.isStructuredOutputEnabled(request)) {
body.output_format = {
type: 'json_schema',
schema: toAnthropicSchema(request.output!.schema!),
};
}

return body;
}

Expand Down Expand Up @@ -491,4 +547,14 @@ export class BetaRunner extends BaseRunner<BetaRunnerTypes> {
return 'other';
}
}

private isStructuredOutputEnabled(
request: GenerateRequest<typeof AnthropicConfigSchema>
): boolean {
return !!(
request.output?.schema &&
request.output.constrained &&
request.output.format === 'json'
);
}
}
48 changes: 47 additions & 1 deletion js/plugins/anthropic/tests/live_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
*/

import * as assert from 'assert';
import { genkit } from 'genkit';
import { genkit, z } from 'genkit';
import { describe, it } from 'node:test';
import { anthropic } from '../src/index.js';

Expand Down Expand Up @@ -80,4 +80,50 @@ describe('Live Anthropic API Tests', { skip: !API_KEY }, () => {

assert.ok(result.text.toLowerCase().includes('hello'));
});

it('should return structured output matching the schema', async () => {
const ai = genkit({
plugins: [anthropic({ apiKey: API_KEY, apiVersion: 'beta' })],
});

const schema = z.object({
name: z.string(),
age: z.number(),
city: z.string(),
isStudent: z.boolean(),
isEmployee: z.boolean(),
isRetired: z.boolean(),
isUnemployed: z.boolean(),
isDisabled: z.boolean(),
});

const result = await ai.generate({
model: 'anthropic/claude-sonnet-4-5',
prompt:
'Generate a fictional person with name "Alice", age 30, and city "New York". Return only the JSON.',
output: { schema, format: 'json', constrained: true },
});

const parsed = result.output;
assert.ok(parsed, 'Should have parsed output');
assert.deepStrictEqual(
{ name: parsed.name, age: parsed.age, city: parsed.city },
{ name: 'Alice', age: 30, city: 'New York' }
);

// Check that boolean fields are present and are actually booleans
for (const key of [
'isStudent',
'isEmployee',
'isRetired',
'isUnemployed',
'isDisabled',
]) {
assert.strictEqual(
typeof parsed[key],
'boolean',
`Field ${key} should be a boolean but got: ${typeof parsed[key]}`
);
}
});
});
2 changes: 1 addition & 1 deletion js/plugins/anthropic/tests/mocks/anthropic-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -379,7 +379,7 @@ function toBetaMessage(message: Message): BetaMessage {
server_tool_use: message.usage.server_tool_use as any,
service_tier: message.usage.service_tier,
},
};
} as BetaMessage;
}

function toBetaStreamEvent(
Expand Down
Loading