beta-parser.mjs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import { AnthropicError } from "../core/error.mjs";
  2. function getOutputFormat(params) {
  3. // Prefer output_format (deprecated) over output_config.format for backward compatibility
  4. return params?.output_format ?? params?.output_config?.format;
  5. }
  6. export function maybeParseBetaMessage(message, params, opts) {
  7. const outputFormat = getOutputFormat(params);
  8. if (!params || !('parse' in (outputFormat ?? {}))) {
  9. return {
  10. ...message,
  11. content: message.content.map((block) => {
  12. if (block.type === 'text') {
  13. const parsedBlock = Object.defineProperty({ ...block }, 'parsed_output', {
  14. value: null,
  15. enumerable: false,
  16. });
  17. return Object.defineProperty(parsedBlock, 'parsed', {
  18. get() {
  19. opts.logger.warn('The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead.');
  20. return null;
  21. },
  22. enumerable: false,
  23. });
  24. }
  25. return block;
  26. }),
  27. parsed_output: null,
  28. };
  29. }
  30. return parseBetaMessage(message, params, opts);
  31. }
  32. export function parseBetaMessage(message, params, opts) {
  33. let firstParsedOutput = null;
  34. const content = message.content.map((block) => {
  35. if (block.type === 'text') {
  36. const parsedOutput = parseBetaOutputFormat(params, block.text);
  37. if (firstParsedOutput === null) {
  38. firstParsedOutput = parsedOutput;
  39. }
  40. const parsedBlock = Object.defineProperty({ ...block }, 'parsed_output', {
  41. value: parsedOutput,
  42. enumerable: false,
  43. });
  44. return Object.defineProperty(parsedBlock, 'parsed', {
  45. get() {
  46. opts.logger.warn('The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead.');
  47. return parsedOutput;
  48. },
  49. enumerable: false,
  50. });
  51. }
  52. return block;
  53. });
  54. return {
  55. ...message,
  56. content,
  57. parsed_output: firstParsedOutput,
  58. };
  59. }
  60. function parseBetaOutputFormat(params, content) {
  61. const outputFormat = getOutputFormat(params);
  62. if (outputFormat?.type !== 'json_schema') {
  63. return null;
  64. }
  65. try {
  66. if ('parse' in outputFormat) {
  67. return outputFormat.parse(content);
  68. }
  69. return JSON.parse(content);
  70. }
  71. catch (error) {
  72. throw new AnthropicError(`Failed to parse structured output: ${error}`);
  73. }
  74. }
  75. //# sourceMappingURL=beta-parser.mjs.map