Completions Resource Reference

Purpose and Scope

The completions resource is the SDK surface for the legacy Text Completions API. It exists for applications that already send completion-style prompts and need to keep those integrations stable while planning a migration to the Messages API. In practical SDK terms, the resource is reached from an Anthropic client as the completions collection, and the main operation is create. The public API documentation identifies the underlying HTTP operation as a legacy text completion request and recommends Messages for new development because future models and features are not expected to be compatible with Text Completions. This page therefore treats completions as maintenance-oriented reference material rather than a starting point for new Claude applications.

Sources: tests/api-resources/completions.test.ts, src/resources/index.ts, api.md

The key distinction for maintainers is that Text Completions uses a single prompt string rather than the structured conversation array used by Messages. The official API guidance calls out the expected prompt shape: alternating human and assistant turns, with the assistant turn often left open so the model can continue it. That behavior is visible in the SDK test fixture, which sends a prompt beginning with a human turn and ending with an assistant marker. If an older integration stores prompts in this format, the completions resource lets the application continue using the same request shape while the team validates a Messages migration separately.

Sources: tests/api-resources/completions.test.ts, api.md

Relevant Source Files

  • tests/api-resources/completions.test.ts — Exercises the public client.completions.create method with required parameters, optional parameters, and response wrapper helpers.
  • src/resources/index.ts — Re-exports the Completions class and the completion request and response types from the generated resource module.
  • api.md — Serves as the generated API reference artifact for repository consumers who want to inspect the public API surface alongside TypeScript exports.

Public SDK Surface

The exported TypeScript contract is intentionally small at the index level. The generated resource barrel exports the Completions resource class, the Completion response type, and three parameter types: CompletionCreateParams, CompletionCreateParamsNonStreaming, and CompletionCreateParamsStreaming. Those names matter because they are the stable public entry points a TypeScript user imports when they want compile-time coverage for a legacy completion request. The split between streaming and non-streaming parameter types also signals that the create operation can be modeled differently depending on whether the caller requests a stream, even when the high-level method name remains the same.

Sources: src/resources/index.ts

Most users do not construct the resource class directly. Instead, they instantiate the Anthropic client and call the completions resource that is attached to the client. The test creates a client with an API key and a base URL, then invokes create through that client. In normal application code the same method is used against the hosted API, while tests can redirect the base URL to a mock OpenAPI server. This pattern is important for maintainers because it means existing client configuration, middleware, retries, and response handling patterns can remain centralized on the main client while only the resource-specific request body changes.

Sources: tests/api-resources/completions.test.ts, src/resources/index.ts

import Anthropic from '@anthropic-ai/sdk';
 
const client = new Anthropic({
  apiKey: process.env['ANTHROPIC_API_KEY'],
});
 
const completion = await client.completions.create({
  model: 'claude-2.1',
  max_tokens_to_sample: 256,
  prompt: '\n\nHuman: Hello, world!\n\nAssistant:',
});

Create Operation and Parameters

The required create parameters shown by the SDK tests are model, max tokens to sample, and prompt. The model chooses the Claude model that will complete the prompt, max tokens to sample sets an upper bound on generated tokens, and prompt supplies the legacy conversational text. The token setting is an absolute cap rather than a guarantee that generation will always reach that length; the model can stop earlier. For older integrations, this means application code should continue to handle shorter completions, stop reasons, and any downstream assumptions about response length rather than treating the requested maximum as the expected response size.

Sources: tests/api-resources/completions.test.ts, api.md

The optional parameters exercised in the resource test provide a compact checklist for compatibility reviews. Metadata can carry a user identifier for request attribution. Stop sequences add caller-defined text boundaries that halt generation. Temperature adjusts randomness. Top-k and top-p provide sampling controls. The stream flag selects non-streaming or streaming behavior at the request level. The betas field is also accepted in the tested request, corresponding to the API header mechanism for selecting Anthropic beta capabilities. Even though completions itself is legacy, the presence of beta selection in the request shape means maintainers should audit whether old code depends on beta headers before refactoring.

Sources: tests/api-resources/completions.test.ts

await client.completions.create({
  max_tokens_to_sample: 256,
  model: 'claude-2.1',
  prompt: '\n\nHuman: Hello, world!\n\nAssistant:',
  metadata: { user_id: '13803d75-b4b5-4c3e-b2a2-6f21399b021b' },
  stop_sequences: ['string'],
  stream: false,
  temperature: 1,
  top_k: 5,
  top_p: 0.7,
  betas: ['message-batches-2024-09-24'],
});

Response Handling Patterns

The completion create call returns more than a bare promise in the generated SDK. The test demonstrates three consumption modes on the same operation: awaiting the operation for parsed data, calling asResponse to access the raw Response object, and calling withResponse to receive both parsed data and the raw response together. This is useful in production maintenance work because legacy integrations often log headers, status codes, or request identifiers while still passing parsed completion data into application logic. The test verifies that the raw response is a Response instance and that the parsed data is not itself the raw HTTP response.

Sources: tests/api-resources/completions.test.ts

The withResponse helper is especially useful when migrating because it lets a team compare behavior without losing observability. A migration harness can preserve the same request metadata, inspect transport-level details, and compare the parsed completion output with a Messages response produced by a parallel call. The test also verifies object identity between the parsed data returned by awaiting the request and the data member returned by withResponse. That detail gives callers confidence that choosing the helper form does not change the parsed payload; it only adds access to the underlying response object.

Sources: tests/api-resources/completions.test.ts

const responsePromise = client.completions.create({
  max_tokens_to_sample: 256,
  model: 'claude-2.1',
  prompt: '\n\nHuman: Hello, world!\n\nAssistant:',
});
 
const rawResponse = await responsePromise.asResponse();
const completion = await responsePromise;
const dataAndResponse = await responsePromise.withResponse();

Source-to-Code Mapping

The completions resource fits into the generated SDK in the same way as other API resources: the package exposes a top-level client, the client exposes a named resource collection, and the generated resource index exports both runtime classes and TypeScript types. For completions, src/resources/index.ts is the public barrel that makes the Completions class and parameter types available from the package. The resource test then validates that a real Anthropic client instance has a completions member with a working create method. Together, those files map package exports to the method a user writes in application code.

Sources: src/resources/index.ts, tests/api-resources/completions.test.ts

api.md complements the TypeScript surface by acting as a generated reference artifact. When a developer is deciding whether a field is part of the public API, the best workflow is to compare the generated TypeScript export names with the API reference entry and then confirm runtime usage in tests. In this page’s source set, that means using src/resources/index.ts for names, tests/api-resources/completions.test.ts for observed method behavior, and api.md for reference-oriented API documentation. That three-way mapping helps avoid relying on private implementation details that may be regenerated by Stainless.

Sources: src/resources/index.ts, tests/api-resources/completions.test.ts, api.md

Maintenance and Migration Guidance

Use completions when preserving an existing integration that already formats prompts with human and assistant text markers, has operational dashboards tied to the legacy endpoint, or needs a staged migration plan. Do not choose it as the default for new work. The official API documentation labels Text Completions as legacy and points new development toward Messages. In code review, that should translate into a simple rule: new Claude features, tool use, richer content blocks, and modern conversation flows should be built on Messages, while completions changes should be limited to compatibility fixes, migration instrumentation, or controlled legacy support.

Sources: tests/api-resources/completions.test.ts, api.md

A safe migration starts by inventorying the exact create parameters the application uses. Required fields map to the core behavior: model selection, output length bound, and prompt content. Optional fields reveal operational behavior that may need an equivalent in Messages or in surrounding application code: sampling controls, stop conditions, metadata, streaming mode, and beta headers. After that inventory, build side-by-side tests that call completions and Messages with representative user prompts. Keep raw response access during the comparison period so logging, rate-limit handling, and error workflows can be checked alongside semantic output quality.

Sources: tests/api-resources/completions.test.ts

Compact Reference

ItemReference detail
Client pathclient.completions.create
Resource exportCompletions
Response type exportCompletion
Parameter type exportsCompletionCreateParams, CompletionCreateParamsNonStreaming, CompletionCreateParamsStreaming
Required tested body fieldsmax_tokens_to_sample, model, prompt
Optional tested body fieldsmetadata, stop_sequences, stream, temperature, top_k, top_p, betas
Raw response helperasResponse
Data plus response helperwithResponse
API statusLegacy Text Completions surface; prefer Messages for new work

Testing Signals

The completions test is valuable because it validates both the minimal and expanded request shapes against the generated SDK surface. The required-parameters test confirms that only the essential legacy fields are needed for create. The optional-parameters test confirms that common sampling, metadata, streaming, and beta-selection fields are accepted together. The same test file also verifies response wrapper behavior, which is part of the SDK’s ergonomic contract and not merely an API payload detail. If a future regeneration changes exported names or request helper behavior, this test is one of the first places maintainers should inspect.

Sources: tests/api-resources/completions.test.ts, src/resources/index.ts

Next, read the Messages API and migration material before adding new functionality on top of completions. If you are only maintaining legacy code, keep imports tied to the exported Completions and CompletionCreateParams names, preserve the required prompt format, and add tests around any optional fields your application depends on. If you are modernizing, use this page as an inventory checklist: capture the old create request, decide which parameters still matter, map the conversation into Messages, and keep raw response access until observability and error-handling behavior are equivalent.