Jump to content

Connect SuperML | Leeroopedia MCP: Equip your AI agents with best practices, code verification, and debugging knowledge. Powered by Leeroo — building Organizational Superintelligence. Contact us at founders@leeroo.com.

Implementation:Openai Openai python Completions Resource

From Leeroopedia
Knowledge Sources
Domains SDK_Infrastructure, Python
Last Updated 2026-02-15 00:00 GMT

Overview

Concrete tool for the legacy Completions API resource provided by the openai-python SDK.

Description

The Completions Resource module provides Completions (synchronous) and AsyncCompletions (asynchronous) resource classes for the OpenAI legacy completions endpoint (/completions). The create() method generates text completions for a given prompt using models such as gpt-3.5-turbo-instruct, davinci-002, and babbage-002. The method supports three overloaded signatures: non-streaming (returns a Completion object), streaming (returns a Stream[Completion] or AsyncStream[Completion]), and a general form accepting a boolean stream parameter. Key generation parameters include temperature, top_p, max_tokens, frequency_penalty, presence_penalty, best_of, logprobs, and stop sequences. The @required_args decorator enforces that model and prompt are always provided at runtime. Both classes expose with_raw_response and with_streaming_response properties for alternative response handling modes.

Usage

Use the Completions Resource when you need to generate text completions using OpenAI's legacy completion models. This is the non-chat completion interface, suitable for prompt-based text generation tasks with instruct-tuned models. For chat-based interactions, use the Chat Completions resource instead.

Code Reference

Source Location

Signature

Completions.create() (non-streaming)

def create(
    self,
    *,
    model: Union[str, Literal["gpt-3.5-turbo-instruct", "davinci-002", "babbage-002"]],
    prompt: Union[str, SequenceNotStr[str], Iterable[int], Iterable[Iterable[int]], None],
    best_of: Optional[int] | Omit = omit,
    echo: Optional[bool] | Omit = omit,
    frequency_penalty: Optional[float] | Omit = omit,
    logit_bias: Optional[Dict[str, int]] | Omit = omit,
    logprobs: Optional[int] | Omit = omit,
    max_tokens: Optional[int] | Omit = omit,
    n: Optional[int] | Omit = omit,
    presence_penalty: Optional[float] | Omit = omit,
    seed: Optional[int] | Omit = omit,
    stop: Union[Optional[str], SequenceNotStr[str], None] | Omit = omit,
    stream: Optional[Literal[False]] | Omit = omit,
    stream_options: Optional[ChatCompletionStreamOptionsParam] | Omit = omit,
    suffix: Optional[str] | Omit = omit,
    temperature: Optional[float] | Omit = omit,
    top_p: Optional[float] | Omit = omit,
    user: str | Omit = omit,
    extra_headers: Headers | None = None,
    extra_query: Query | None = None,
    extra_body: Body | None = None,
    timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> Completion: ...

Completions.create() (streaming)

def create(
    self,
    *,
    model: Union[str, Literal["gpt-3.5-turbo-instruct", "davinci-002", "babbage-002"]],
    prompt: Union[str, SequenceNotStr[str], Iterable[int], Iterable[Iterable[int]], None],
    stream: Literal[True],
    # ... same optional parameters ...
) -> Stream[Completion]: ...

Import

from openai.resources.completions import Completions, AsyncCompletions

I/O Contract

Inputs (create)

Name Type Required Description
model Union[str, Literal["gpt-3.5-turbo-instruct", "davinci-002", "babbage-002"]] Yes ID of the model to use.
prompt Union[str, SequenceNotStr[str], Iterable[int], Iterable[Iterable[int]], None] Yes The prompt(s) to generate completions for. Can be a string, list of strings, token array, or array of token arrays.
stream bool or None No Whether to stream back partial progress via server-sent events.
best_of Optional[int] No Generates this many completions server-side and returns the best one. Cannot be used with streaming.
echo Optional[bool] No Echo back the prompt in addition to the completion.
frequency_penalty Optional[float] No Penalizes tokens based on existing frequency (-2.0 to 2.0).
logit_bias Optional[Dict[str, int]] No Modify the likelihood of specified tokens appearing (-100 to 100).
logprobs Optional[int] No Include log probabilities on the top N most likely tokens (max 5).
max_tokens Optional[int] No Maximum number of tokens to generate.
n Optional[int] No How many completions to generate for each prompt.
presence_penalty Optional[float] No Penalizes tokens based on whether they appear in the text (-2.0 to 2.0).
seed Optional[int] No Seed for deterministic sampling (best effort).
stop Union[str, SequenceNotStr[str], None] No Up to 4 sequences where the API will stop generating.
suffix Optional[str] No The suffix after a completion of inserted text (gpt-3.5-turbo-instruct only).
temperature Optional[float] No Sampling temperature (0 to 2).
top_p Optional[float] No Nucleus sampling parameter.

Outputs

Name Type Description
return (non-streaming) Completion A completion object containing generated text, usage stats, and model info.
return (streaming) Stream[Completion] / AsyncStream[Completion] An iterable stream of completion chunks delivered via server-sent events.

Usage Examples

Basic Completion

from openai import OpenAI

client = OpenAI()

completion = client.completions.create(
    model="gpt-3.5-turbo-instruct",
    prompt="Write a haiku about programming:",
    max_tokens=50,
    temperature=0.7,
)
print(completion.choices[0].text)

Streaming Completion

stream = client.completions.create(
    model="gpt-3.5-turbo-instruct",
    prompt="Once upon a time",
    max_tokens=100,
    stream=True,
)
for chunk in stream:
    print(chunk.choices[0].text, end="", flush=True)

Async Usage

from openai import AsyncOpenAI

client = AsyncOpenAI()

completion = await client.completions.create(
    model="gpt-3.5-turbo-instruct",
    prompt="Translate to French: Hello, world!",
    max_tokens=30,
)
print(completion.choices[0].text)

Multiple Completions

completion = client.completions.create(
    model="gpt-3.5-turbo-instruct",
    prompt="Suggest a name for a cat:",
    n=3,
    max_tokens=10,
)
for choice in completion.choices:
    print(choice.text.strip())

Related Pages

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment