Skip to content

OpenAIChatCompletionsLLM

BONUS Material: OpenAI-compatible Chat Completions LLM.

OpenAIChatCompletionsLLM

Bases: LLM

LLM integration for OpenAI-compatible Chat Completions endpoints.

Talks to /v1/chat/completions, the API that local and self-hosted servers such as vLLM, llama.cpp server, LM Studio and Ollama's OpenAI-compatible endpoint implement. Point it at a server with base_url. For OpenAI's own models, OpenAILLM (Responses API) is the other option.

Examples:

llm = OpenAIChatCompletionsLLM(
    "my-model",
    api_key="EMPTY",
    base_url="http://localhost:8000/v1",
    default_request_kwargs={"temperature": 0.0, "max_tokens": 1024},
)
Source code in src/llm_agents_from_scratch/llms/openai_chat_completions/llm.py
class OpenAIChatCompletionsLLM(LLM):
    """LLM integration for OpenAI-compatible Chat Completions endpoints.

    Talks to `/v1/chat/completions`, the API that local and self-hosted
    servers such as vLLM, llama.cpp server, LM Studio and Ollama's
    OpenAI-compatible endpoint implement. Point it at a server with
    `base_url`. For OpenAI's own models, `OpenAILLM` (Responses API) is the
    other option.

    Examples:
        ```python
        llm = OpenAIChatCompletionsLLM(
            "my-model",
            api_key="EMPTY",
            base_url="http://localhost:8000/v1",
            default_request_kwargs={"temperature": 0.0, "max_tokens": 1024},
        )
        ```
    """

    def __init__(
        self,
        model: str,
        *,
        api_key: str | None = None,
        default_request_kwargs: dict[str, Any] | None = None,
        **kwargs: Any,
    ) -> None:
        """Create an OpenAIChatCompletionsLLM instance.

        Args:
            model (str): The name of the model, as the server knows it.
            api_key (str | None, optional): An api key. Defaults to None.
                If None, will fallback to OpenAI's api key resolution, looking
                for an OPENAI_API_KEY env var. The client requires a key even
                for a server that does not check one: pass any non-empty
                string, e.g. "EMPTY".
            default_request_kwargs (dict[str, Any] | None, optional): Request
                params (e.g. `temperature`, `seed`, `max_tokens`,
                `extra_body`) applied to every request, unless a call
                explicitly passes its own value for the same param. The
                merge is shallow: a per-call `extra_body`, for example,
                replaces the default one whole rather than being merged
                into it. The params each method sets itself (`model`,
                `messages`, and `tools` or `response_format` where the
                method has them) always win over a default or per-call
                value of the same name. Defaults to None, which leaves the
                server's own defaults in place.
            **kwargs (Any): Additional keyword arguments. Passed to the
                construction of an ~openai.AsyncOpenAI, e.g. `base_url`.
        """
        check_extra_was_installed(extra="openai", packages="openai")
        from openai import AsyncOpenAI  # noqa: PLC0415

        self.model = model
        self.default_request_kwargs = dict(default_request_kwargs or {})
        self.client = AsyncOpenAI(api_key=api_key, **kwargs)

    def _request_kwargs(
        self,
        kwargs: dict[str, Any],
        **required: Any,
    ) -> dict[str, Any]:
        """Builds the keyword arguments of a request.

        Later sources win: `default_request_kwargs`, then the per-call
        `kwargs`, then the `required` params the calling method sets
        itself. Merging them into one dict, rather than passing `required`
        as keywords next to `**kwargs`, means a default or per-call param
        of the same name is overridden instead of raising a `TypeError`
        for a duplicate keyword.
        """
        return {**self.default_request_kwargs, **kwargs, **required}

    async def complete(self, prompt: str, **kwargs: Any) -> CompleteResult:
        """Implements complete LLM interaction mode."""
        response: "ChatCompletion" = await self.client.chat.completions.create(
            **self._request_kwargs(
                kwargs,
                model=self.model,
                messages=[{"role": "user", "content": prompt}],
            ),
        )
        return CompleteResult(
            response=first_choice_message(response).content or "",
            prompt=prompt,
        )

    async def structured_output(
        self,
        prompt: str,
        mdl: type[StructuredOutputType],
        **kwargs: Any,
    ) -> StructuredOutputType:
        """Implements structured output LLM interaction mode.

        Uses Chat Completions structured outputs: `mdl`'s JSON schema is
        sent as the `response_format`, so the server must support the
        `json_schema` response format.

        Args:
            prompt (str): The prompt to elicit the structured output response.
            mdl (type[StructuredOutputType]): The ~pydantic.BaseModel to output.
            **kwargs (Any): Additional keyword arguments.

        Returns:
            StructuredOutputType: The structured output as the specified `mdl`
                type.

        Raises:
            StructuredOutputError: If the model returned nothing parseable
                as `mdl`: a refusal or an empty reply, a reply that is not
                valid for `mdl`'s schema (e.g. plain text from a server that
                ignores the response format), a reply cut off by the token
                limit or by a content filter, or a response with no
                choices. Where the SDK or pydantic raised first, that
                error is the `__cause__`.
        """
        from openai import (  # noqa: PLC0415
            ContentFilterFinishReasonError,
            LengthFinishReasonError,
        )

        response: "ParsedChatCompletion[StructuredOutputType]"
        try:
            response = await self.client.chat.completions.parse(
                **self._request_kwargs(
                    kwargs,
                    model=self.model,
                    messages=[{"role": "user", "content": prompt}],
                    response_format=mdl,
                ),
            )
        except (
            ValidationError,
            LengthFinishReasonError,
            ContentFilterFinishReasonError,
        ) as e:
            # the reply's content is kept out of the message; it is on `e`
            msg = (
                f"No {mdl.__name__} could be parsed from the response "
                f"({type(e).__name__})."
            )
            raise StructuredOutputError(msg) from e
        if not response.choices:
            raise StructuredOutputError(
                f"No {mdl.__name__} could be parsed from the response: "
                "it has no choices.",
            )
        parsed = response.choices[0].message.parsed
        if parsed is None:
            raise StructuredOutputError(
                f"No {mdl.__name__} could be parsed from the response.",
            )
        return parsed

    def _prepare_messages_from_history(
        self,
        chat_history: Sequence[ChatMessage],
    ) -> list["ChatCompletionMessageParam"]:
        """Prepare Chat Completions messages from the chat history.

        Unlike the Responses API, Chat Completions takes system messages
        in the list of messages, so the history converts one to one.
        """
        return [
            chat_message_to_chat_completion_message_param(cm)
            for cm in chat_history
        ]

    async def chat(
        self,
        input: str,
        chat_history: Sequence[ChatMessage] | None = None,
        tools: Sequence[Tool] | None = None,
        **kwargs: Any,
    ) -> tuple[ChatMessage, ChatMessage]:
        """Implements chat LLM interaction mode.

        Args:
            input (str): The user's current input.
            chat_history (list[ChatMessage] | None, optional): The chat
                history.
            tools (list[BaseTool] | None, optional): The tools available to the
                LLM.
            **kwargs (Any): Additional keyword arguments.

        Returns:
            tuple[ChatMessage, ChatMessage]: A tuple of ChatMessage with the
                first message corresponding to the ChatMessage created from the
                supplied input string, and the second ChatMessage is the
                response from the LLM.
        """
        # prepare messages
        messages = self._prepare_messages_from_history(chat_history or [])
        user_message = ChatMessage(role="user", content=input)
        messages.append(
            chat_message_to_chat_completion_message_param(user_message),
        )

        # prepare tools
        from openai import omit  # noqa: PLC0415

        openai_tools = (
            [tool_to_chat_completion_tool(t) for t in tools] if tools else omit
        )

        response: "ChatCompletion" = await self.client.chat.completions.create(
            **self._request_kwargs(
                kwargs,
                model=self.model,
                messages=messages,
                tools=openai_tools,
            ),
        )
        return user_message, chat_completion_message_to_chat_message(
            first_choice_message(response),
        )

    async def continue_chat_with_tool_results(
        self,
        tool_call_results: Sequence[ToolCallResult],
        chat_history: Sequence[ChatMessage],
        tools: Sequence[Tool] | None = None,
        **kwargs: Any,
    ) -> tuple[list[ChatMessage], ChatMessage]:
        """Implements continue chat with tool results.

        Args:
            tool_call_results (Sequence[ToolCallResult]): The tool call results.
            chat_history (Sequence[ChatMessage]): The chat history.
            tools (Sequence[BaseTool]|None, optional): tools that the LLM
                can call.
            **kwargs (Any): Additional keyword arguments.

        Returns:
            tuple[list[ChatMessage], ChatMessage]: A tuple whose first element
                is a list of ChatMessage objects corresponding to the
                supplied ToolCallResult converted objects. The second element
                is the response ChatMessage from the LLM.
        """
        # prepare messages from chat history and tool call results
        tool_messages = [
            ChatMessage.from_tool_call_result(tc) for tc in tool_call_results
        ]
        messages = self._prepare_messages_from_history(
            [*(chat_history or []), *tool_messages],
        )

        # prepare tools
        from openai import omit  # noqa: PLC0415

        openai_tools = (
            [tool_to_chat_completion_tool(t) for t in tools] if tools else omit
        )

        response: "ChatCompletion" = await self.client.chat.completions.create(
            **self._request_kwargs(
                kwargs,
                model=self.model,
                messages=messages,
                tools=openai_tools,
            ),
        )

        return tool_messages, chat_completion_message_to_chat_message(
            first_choice_message(response),
        )

__init__

__init__(
    model,
    *,
    api_key=None,
    default_request_kwargs=None,
    **kwargs,
)

Create an OpenAIChatCompletionsLLM instance.

Parameters:

Name Type Description Default
model str

The name of the model, as the server knows it.

required
api_key str | None

An api key. Defaults to None. If None, will fallback to OpenAI's api key resolution, looking for an OPENAI_API_KEY env var. The client requires a key even for a server that does not check one: pass any non-empty string, e.g. "EMPTY".

None
default_request_kwargs dict[str, Any] | None

Request params (e.g. temperature, seed, max_tokens, extra_body) applied to every request, unless a call explicitly passes its own value for the same param. The merge is shallow: a per-call extra_body, for example, replaces the default one whole rather than being merged into it. The params each method sets itself (model, messages, and tools or response_format where the method has them) always win over a default or per-call value of the same name. Defaults to None, which leaves the server's own defaults in place.

None
**kwargs Any

Additional keyword arguments. Passed to the construction of an ~openai.AsyncOpenAI, e.g. base_url.

{}
Source code in src/llm_agents_from_scratch/llms/openai_chat_completions/llm.py
def __init__(
    self,
    model: str,
    *,
    api_key: str | None = None,
    default_request_kwargs: dict[str, Any] | None = None,
    **kwargs: Any,
) -> None:
    """Create an OpenAIChatCompletionsLLM instance.

    Args:
        model (str): The name of the model, as the server knows it.
        api_key (str | None, optional): An api key. Defaults to None.
            If None, will fallback to OpenAI's api key resolution, looking
            for an OPENAI_API_KEY env var. The client requires a key even
            for a server that does not check one: pass any non-empty
            string, e.g. "EMPTY".
        default_request_kwargs (dict[str, Any] | None, optional): Request
            params (e.g. `temperature`, `seed`, `max_tokens`,
            `extra_body`) applied to every request, unless a call
            explicitly passes its own value for the same param. The
            merge is shallow: a per-call `extra_body`, for example,
            replaces the default one whole rather than being merged
            into it. The params each method sets itself (`model`,
            `messages`, and `tools` or `response_format` where the
            method has them) always win over a default or per-call
            value of the same name. Defaults to None, which leaves the
            server's own defaults in place.
        **kwargs (Any): Additional keyword arguments. Passed to the
            construction of an ~openai.AsyncOpenAI, e.g. `base_url`.
    """
    check_extra_was_installed(extra="openai", packages="openai")
    from openai import AsyncOpenAI  # noqa: PLC0415

    self.model = model
    self.default_request_kwargs = dict(default_request_kwargs or {})
    self.client = AsyncOpenAI(api_key=api_key, **kwargs)

complete async

complete(prompt, **kwargs)

Implements complete LLM interaction mode.

Source code in src/llm_agents_from_scratch/llms/openai_chat_completions/llm.py
async def complete(self, prompt: str, **kwargs: Any) -> CompleteResult:
    """Implements complete LLM interaction mode."""
    response: "ChatCompletion" = await self.client.chat.completions.create(
        **self._request_kwargs(
            kwargs,
            model=self.model,
            messages=[{"role": "user", "content": prompt}],
        ),
    )
    return CompleteResult(
        response=first_choice_message(response).content or "",
        prompt=prompt,
    )

structured_output async

structured_output(prompt, mdl, **kwargs)

Implements structured output LLM interaction mode.

Uses Chat Completions structured outputs: mdl's JSON schema is sent as the response_format, so the server must support the json_schema response format.

Parameters:

Name Type Description Default
prompt str

The prompt to elicit the structured output response.

required
mdl type[StructuredOutputType]

The ~pydantic.BaseModel to output.

required
**kwargs Any

Additional keyword arguments.

{}

Returns:

Name Type Description
StructuredOutputType StructuredOutputType

The structured output as the specified mdl type.

Raises:

Type Description
StructuredOutputError

If the model returned nothing parseable as mdl: a refusal or an empty reply, a reply that is not valid for mdl's schema (e.g. plain text from a server that ignores the response format), a reply cut off by the token limit or by a content filter, or a response with no choices. Where the SDK or pydantic raised first, that error is the __cause__.

Source code in src/llm_agents_from_scratch/llms/openai_chat_completions/llm.py
async def structured_output(
    self,
    prompt: str,
    mdl: type[StructuredOutputType],
    **kwargs: Any,
) -> StructuredOutputType:
    """Implements structured output LLM interaction mode.

    Uses Chat Completions structured outputs: `mdl`'s JSON schema is
    sent as the `response_format`, so the server must support the
    `json_schema` response format.

    Args:
        prompt (str): The prompt to elicit the structured output response.
        mdl (type[StructuredOutputType]): The ~pydantic.BaseModel to output.
        **kwargs (Any): Additional keyword arguments.

    Returns:
        StructuredOutputType: The structured output as the specified `mdl`
            type.

    Raises:
        StructuredOutputError: If the model returned nothing parseable
            as `mdl`: a refusal or an empty reply, a reply that is not
            valid for `mdl`'s schema (e.g. plain text from a server that
            ignores the response format), a reply cut off by the token
            limit or by a content filter, or a response with no
            choices. Where the SDK or pydantic raised first, that
            error is the `__cause__`.
    """
    from openai import (  # noqa: PLC0415
        ContentFilterFinishReasonError,
        LengthFinishReasonError,
    )

    response: "ParsedChatCompletion[StructuredOutputType]"
    try:
        response = await self.client.chat.completions.parse(
            **self._request_kwargs(
                kwargs,
                model=self.model,
                messages=[{"role": "user", "content": prompt}],
                response_format=mdl,
            ),
        )
    except (
        ValidationError,
        LengthFinishReasonError,
        ContentFilterFinishReasonError,
    ) as e:
        # the reply's content is kept out of the message; it is on `e`
        msg = (
            f"No {mdl.__name__} could be parsed from the response "
            f"({type(e).__name__})."
        )
        raise StructuredOutputError(msg) from e
    if not response.choices:
        raise StructuredOutputError(
            f"No {mdl.__name__} could be parsed from the response: "
            "it has no choices.",
        )
    parsed = response.choices[0].message.parsed
    if parsed is None:
        raise StructuredOutputError(
            f"No {mdl.__name__} could be parsed from the response.",
        )
    return parsed

chat async

chat(input, chat_history=None, tools=None, **kwargs)

Implements chat LLM interaction mode.

Parameters:

Name Type Description Default
input str

The user's current input.

required
chat_history list[ChatMessage] | None

The chat history.

None
tools list[BaseTool] | None

The tools available to the LLM.

None
**kwargs Any

Additional keyword arguments.

{}

Returns:

Type Description
tuple[ChatMessage, ChatMessage]

tuple[ChatMessage, ChatMessage]: A tuple of ChatMessage with the first message corresponding to the ChatMessage created from the supplied input string, and the second ChatMessage is the response from the LLM.

Source code in src/llm_agents_from_scratch/llms/openai_chat_completions/llm.py
async def chat(
    self,
    input: str,
    chat_history: Sequence[ChatMessage] | None = None,
    tools: Sequence[Tool] | None = None,
    **kwargs: Any,
) -> tuple[ChatMessage, ChatMessage]:
    """Implements chat LLM interaction mode.

    Args:
        input (str): The user's current input.
        chat_history (list[ChatMessage] | None, optional): The chat
            history.
        tools (list[BaseTool] | None, optional): The tools available to the
            LLM.
        **kwargs (Any): Additional keyword arguments.

    Returns:
        tuple[ChatMessage, ChatMessage]: A tuple of ChatMessage with the
            first message corresponding to the ChatMessage created from the
            supplied input string, and the second ChatMessage is the
            response from the LLM.
    """
    # prepare messages
    messages = self._prepare_messages_from_history(chat_history or [])
    user_message = ChatMessage(role="user", content=input)
    messages.append(
        chat_message_to_chat_completion_message_param(user_message),
    )

    # prepare tools
    from openai import omit  # noqa: PLC0415

    openai_tools = (
        [tool_to_chat_completion_tool(t) for t in tools] if tools else omit
    )

    response: "ChatCompletion" = await self.client.chat.completions.create(
        **self._request_kwargs(
            kwargs,
            model=self.model,
            messages=messages,
            tools=openai_tools,
        ),
    )
    return user_message, chat_completion_message_to_chat_message(
        first_choice_message(response),
    )

continue_chat_with_tool_results async

continue_chat_with_tool_results(
    tool_call_results, chat_history, tools=None, **kwargs
)

Implements continue chat with tool results.

Parameters:

Name Type Description Default
tool_call_results Sequence[ToolCallResult]

The tool call results.

required
chat_history Sequence[ChatMessage]

The chat history.

required
tools Sequence[BaseTool] | None

tools that the LLM can call.

None
**kwargs Any

Additional keyword arguments.

{}

Returns:

Type Description
tuple[list[ChatMessage], ChatMessage]

tuple[list[ChatMessage], ChatMessage]: A tuple whose first element is a list of ChatMessage objects corresponding to the supplied ToolCallResult converted objects. The second element is the response ChatMessage from the LLM.

Source code in src/llm_agents_from_scratch/llms/openai_chat_completions/llm.py
async def continue_chat_with_tool_results(
    self,
    tool_call_results: Sequence[ToolCallResult],
    chat_history: Sequence[ChatMessage],
    tools: Sequence[Tool] | None = None,
    **kwargs: Any,
) -> tuple[list[ChatMessage], ChatMessage]:
    """Implements continue chat with tool results.

    Args:
        tool_call_results (Sequence[ToolCallResult]): The tool call results.
        chat_history (Sequence[ChatMessage]): The chat history.
        tools (Sequence[BaseTool]|None, optional): tools that the LLM
            can call.
        **kwargs (Any): Additional keyword arguments.

    Returns:
        tuple[list[ChatMessage], ChatMessage]: A tuple whose first element
            is a list of ChatMessage objects corresponding to the
            supplied ToolCallResult converted objects. The second element
            is the response ChatMessage from the LLM.
    """
    # prepare messages from chat history and tool call results
    tool_messages = [
        ChatMessage.from_tool_call_result(tc) for tc in tool_call_results
    ]
    messages = self._prepare_messages_from_history(
        [*(chat_history or []), *tool_messages],
    )

    # prepare tools
    from openai import omit  # noqa: PLC0415

    openai_tools = (
        [tool_to_chat_completion_tool(t) for t in tools] if tools else omit
    )

    response: "ChatCompletion" = await self.client.chat.completions.create(
        **self._request_kwargs(
            kwargs,
            model=self.model,
            messages=messages,
            tools=openai_tools,
        ),
    )

    return tool_messages, chat_completion_message_to_chat_message(
        first_choice_message(response),
    )