parser.mjs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import { AnthropicError } from "../core/error.mjs";
  2. function getOutputFormat(params) {
  3. return params?.output_config?.format;
  4. }
  5. export function maybeParseMessage(message, params, opts) {
  6. const outputFormat = getOutputFormat(params);
  7. if (!params || !('parse' in (outputFormat ?? {}))) {
  8. return {
  9. ...message,
  10. content: message.content.map((block) => {
  11. if (block.type === 'text') {
  12. const parsedBlock = Object.defineProperty({ ...block }, 'parsed_output', {
  13. value: null,
  14. enumerable: false,
  15. });
  16. return parsedBlock;
  17. }
  18. return block;
  19. }),
  20. parsed_output: null,
  21. };
  22. }
  23. return parseMessage(message, params, opts);
  24. }
  25. export function parseMessage(message, params, opts) {
  26. let firstParsedOutput = null;
  27. const content = message.content.map((block) => {
  28. if (block.type === 'text') {
  29. const parsedOutput = parseOutputFormat(params, block.text);
  30. if (firstParsedOutput === null) {
  31. firstParsedOutput = parsedOutput;
  32. }
  33. const parsedBlock = Object.defineProperty({ ...block }, 'parsed_output', {
  34. value: parsedOutput,
  35. enumerable: false,
  36. });
  37. return parsedBlock;
  38. }
  39. return block;
  40. });
  41. return {
  42. ...message,
  43. content,
  44. parsed_output: firstParsedOutput,
  45. };
  46. }
  47. function parseOutputFormat(params, content) {
  48. const outputFormat = getOutputFormat(params);
  49. if (outputFormat?.type !== 'json_schema') {
  50. return null;
  51. }
  52. try {
  53. if ('parse' in outputFormat) {
  54. return outputFormat.parse(content);
  55. }
  56. return JSON.parse(content);
  57. }
  58. catch (error) {
  59. throw new AnthropicError(`Failed to parse structured output: ${error}`);
  60. }
  61. }
  62. //# sourceMappingURL=parser.mjs.map