messages.mjs 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  1. // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
  2. import { AnthropicError } from "../../../error.mjs";
  3. import { APIResource } from "../../../core/resource.mjs";
  4. import { MODEL_NONSTREAMING_TOKENS } from "../../../internal/constants.mjs";
  5. import { buildHeaders } from "../../../internal/headers.mjs";
  6. import { stainlessHelperHeader } from "../../../lib/stainless-helper-header.mjs";
  7. import { parseBetaMessage, } from "../../../lib/beta-parser.mjs";
  8. import { BetaMessageStream } from "../../../lib/BetaMessageStream.mjs";
  9. import { BetaToolRunner, } from "../../../lib/tools/BetaToolRunner.mjs";
  10. import { ToolError } from "../../../lib/tools/ToolError.mjs";
  11. import * as BatchesAPI from "./batches.mjs";
  12. import { Batches, } from "./batches.mjs";
  13. const DEPRECATED_MODELS = {
  14. 'claude-1.3': 'November 6th, 2024',
  15. 'claude-1.3-100k': 'November 6th, 2024',
  16. 'claude-instant-1.1': 'November 6th, 2024',
  17. 'claude-instant-1.1-100k': 'November 6th, 2024',
  18. 'claude-instant-1.2': 'November 6th, 2024',
  19. 'claude-3-sonnet-20240229': 'July 21st, 2025',
  20. 'claude-3-opus-20240229': 'January 5th, 2026',
  21. 'claude-2.1': 'July 21st, 2025',
  22. 'claude-2.0': 'July 21st, 2025',
  23. 'claude-3-7-sonnet-latest': 'February 19th, 2026',
  24. 'claude-3-7-sonnet-20250219': 'February 19th, 2026',
  25. };
  26. const MODELS_TO_WARN_WITH_THINKING_ENABLED = ['claude-opus-4-6'];
  27. export class Messages extends APIResource {
  28. constructor() {
  29. super(...arguments);
  30. this.batches = new BatchesAPI.Batches(this._client);
  31. }
  32. create(params, options) {
  33. // Transform deprecated output_format to output_config.format
  34. const modifiedParams = transformOutputFormat(params);
  35. const { betas, ...body } = modifiedParams;
  36. if (body.model in DEPRECATED_MODELS) {
  37. console.warn(`The model '${body.model}' is deprecated and will reach end-of-life on ${DEPRECATED_MODELS[body.model]}\nPlease migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);
  38. }
  39. if (body.model in MODELS_TO_WARN_WITH_THINKING_ENABLED &&
  40. body.thinking &&
  41. body.thinking.type === 'enabled') {
  42. console.warn(`Using Claude with ${body.model} and 'thinking.type=enabled' is deprecated. Use 'thinking.type=adaptive' instead which results in better model performance in our testing: https://platform.claude.com/docs/en/build-with-claude/adaptive-thinking`);
  43. }
  44. let timeout = this._client._options.timeout;
  45. if (!body.stream && timeout == null) {
  46. const maxNonstreamingTokens = MODEL_NONSTREAMING_TOKENS[body.model] ?? undefined;
  47. timeout = this._client.calculateNonstreamingTimeout(body.max_tokens, maxNonstreamingTokens);
  48. }
  49. // Collect helper info from tools and messages
  50. const helperHeader = stainlessHelperHeader(body.tools, body.messages);
  51. return this._client.post('/v1/messages?beta=true', {
  52. body,
  53. timeout: timeout ?? 600000,
  54. ...options,
  55. headers: buildHeaders([
  56. { ...(betas?.toString() != null ? { 'anthropic-beta': betas?.toString() } : undefined) },
  57. helperHeader,
  58. options?.headers,
  59. ]),
  60. stream: modifiedParams.stream ?? false,
  61. });
  62. }
  63. /**
  64. * Send a structured list of input messages with text and/or image content, along with an expected `output_format` and
  65. * the response will be automatically parsed and available in the `parsed_output` property of the message.
  66. *
  67. * @example
  68. * ```ts
  69. * const message = await client.beta.messages.parse({
  70. * model: 'claude-3-5-sonnet-20241022',
  71. * max_tokens: 1024,
  72. * messages: [{ role: 'user', content: 'What is 2+2?' }],
  73. * output_format: zodOutputFormat(z.object({ answer: z.number() }), 'math'),
  74. * });
  75. *
  76. * console.log(message.parsed_output?.answer); // 4
  77. * ```
  78. */
  79. parse(params, options) {
  80. options = {
  81. ...options,
  82. headers: buildHeaders([
  83. { 'anthropic-beta': [...(params.betas ?? []), 'structured-outputs-2025-12-15'].toString() },
  84. options?.headers,
  85. ]),
  86. };
  87. return this.create(params, options).then((message) => parseBetaMessage(message, params, { logger: this._client.logger ?? console }));
  88. }
  89. /**
  90. * Create a Message stream
  91. */
  92. stream(body, options) {
  93. return BetaMessageStream.createMessage(this, body, options);
  94. }
  95. /**
  96. * Count the number of tokens in a Message.
  97. *
  98. * The Token Count API can be used to count the number of tokens in a Message,
  99. * including tools, images, and documents, without creating it.
  100. *
  101. * Learn more about token counting in our
  102. * [user guide](https://docs.claude.com/en/docs/build-with-claude/token-counting)
  103. *
  104. * @example
  105. * ```ts
  106. * const betaMessageTokensCount =
  107. * await client.beta.messages.countTokens({
  108. * messages: [{ content: 'string', role: 'user' }],
  109. * model: 'claude-opus-4-6',
  110. * });
  111. * ```
  112. */
  113. countTokens(params, options) {
  114. // Transform deprecated output_format to output_config.format
  115. const modifiedParams = transformOutputFormat(params);
  116. const { betas, ...body } = modifiedParams;
  117. return this._client.post('/v1/messages/count_tokens?beta=true', {
  118. body,
  119. ...options,
  120. headers: buildHeaders([
  121. { 'anthropic-beta': [...(betas ?? []), 'token-counting-2024-11-01'].toString() },
  122. options?.headers,
  123. ]),
  124. });
  125. }
  126. toolRunner(body, options) {
  127. return new BetaToolRunner(this._client, body, options);
  128. }
  129. }
  130. /**
  131. * Transform deprecated output_format to output_config.format
  132. * Returns a modified copy of the params without mutating the original
  133. */
  134. function transformOutputFormat(params) {
  135. if (!params.output_format) {
  136. return params;
  137. }
  138. if (params.output_config?.format) {
  139. throw new AnthropicError('Both output_format and output_config.format were provided. ' +
  140. 'Please use only output_config.format (output_format is deprecated).');
  141. }
  142. const { output_format, ...rest } = params;
  143. return {
  144. ...rest,
  145. output_config: {
  146. ...params.output_config,
  147. format: output_format,
  148. },
  149. };
  150. }
  151. export { BetaToolRunner } from "../../../lib/tools/BetaToolRunner.mjs";
  152. export { ToolError } from "../../../lib/tools/ToolError.mjs";
  153. Messages.Batches = Batches;
  154. Messages.BetaToolRunner = BetaToolRunner;
  155. Messages.ToolError = ToolError;
  156. //# sourceMappingURL=messages.mjs.map