langchain.chat_models.azure_openai.AzureChatOpenAI¶

class langchain.chat_models.azure_openai.AzureChatOpenAI(*, cache: Optional[bool] = None, verbose: bool = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, callback_manager: Optional[BaseCallbackManager] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, client: Any = None, model: str = 'gpt-3.5-turbo', temperature: float = 0.7, model_kwargs: Dict[str, Any] = None, openai_api_key: str = '', openai_api_base: str = '', openai_organization: str = '', openai_proxy: str = '', request_timeout: Optional[Union[float, Tuple[float, float]]] = None, max_retries: int = 6, streaming: bool = False, n: int = 1, max_tokens: Optional[int] = None, tiktoken_model_name: Optional[str] = None, deployment_name: str = '', openai_api_type: str = 'azure', openai_api_version: str = '')[source]¶

Bases: ChatOpenAI

Wrapper around Azure OpenAI Chat Completion API.

To use this class you must have a deployed model on Azure OpenAI. Use deployment_name in the constructor to refer to the “Model deployment name” in the Azure portal.

In addition, you should have the openai python package installed, and the following environment variables set or passed in constructor in lower case: - OPENAI_API_TYPE (default: azure) - OPENAI_API_KEY - OPENAI_API_BASE - OPENAI_API_VERSION - OPENAI_PROXY

For example, if you have gpt-35-turbo deployed, with the deployment name 35-turbo-dev, the constructor should look like:

AzureChatOpenAI(
    deployment_name="35-turbo-dev",
    openai_api_version="2023-05-15",
)

Be aware the API version may change.

Any parameters that are valid to be passed to the openai.create call can be passed in, even if not explicitly saved on this class.

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

param cache: Optional[bool] = None¶

Whether to cache the response.

param callback_manager: Optional[BaseCallbackManager] = None¶

Callback manager to add to the run trace.

param callbacks: Callbacks = None¶

Callbacks to add to the run trace.

param deployment_name: str = ''¶
param max_retries: int = 6¶

Maximum number of retries to make when generating.

param max_tokens: Optional[int] = None¶

Maximum number of tokens to generate.

param metadata: Optional[Dict[str, Any]] = None¶

Metadata to add to the run trace.

param model_kwargs: Dict[str, Any] [Optional]¶

Holds any model parameters valid for create call not explicitly specified.

param model_name: str = 'gpt-3.5-turbo' (alias 'model')¶

Model name to use.

param n: int = 1¶

Number of chat completions to generate for each prompt.

param openai_api_base: str = ''¶
param openai_api_key: str = ''¶

Base URL path for API requests, leave blank if not using a proxy or service emulator.

param openai_api_type: str = 'azure'¶
param openai_api_version: str = ''¶
param openai_organization: str = ''¶
param openai_proxy: str = ''¶
param request_timeout: Optional[Union[float, Tuple[float, float]]] = None¶

Timeout for requests to OpenAI completion API. Default is 600 seconds.

param streaming: bool = False¶

Whether to stream the results or not.

param tags: Optional[List[str]] = None¶

Tags to add to the run trace.

param temperature: float = 0.7¶

What sampling temperature to use.

param tiktoken_model_name: Optional[str] = None¶

The model name to pass to tiktoken when using this class. Tiktoken is used to count the number of tokens in documents to constrain them to be under a certain limit. By default, when set to None, this will be the same as the embedding model name. However, there are some cases where you may want to use this Embedding class with a model name not supported by tiktoken. This can include when using Azure embeddings or when using one of the many model providers that expose an OpenAI-like API but with different models. In those cases, in order to avoid erroring when tiktoken is called, you can specify a model name to use here.

param verbose: bool [Optional]¶

Whether to print out response text.

__call__(messages: List[BaseMessage], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) BaseMessage¶

Call self as a function.

async agenerate(messages: List[List[BaseMessage]], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) LLMResult¶

Top Level call

async agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) LLMResult¶

Asynchronously pass a sequence of prompts and return model generations.

This method should make use of batched calls for models that expose a batched API.

Use this method when you want to:
  1. take advantage of batched calls,

  2. need more output from the model than just the top generated value,

  3. are building chains that are agnostic to the underlying language model

    type (e.g., pure text completion models vs chat models).

Parameters
  • prompts – List of PromptValues. A PromptValue is an object that can be converted to match the format of any language model (string for pure text generation models and BaseMessages for chat models).

  • stop – Stop words to use when generating. Model output is cut off at the first occurrence of any of these substrings.

  • callbacks – Callbacks to pass through. Used for executing additional functionality, such as logging or streaming, throughout generation.

  • **kwargs – Arbitrary additional keyword arguments. These are usually passed to the model provider API call.

Returns

An LLMResult, which contains a list of candidate Generations for each input

prompt and additional model provider-specific output.

async ainvoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) BaseMessageChunk¶
async apredict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) str¶

Asynchronously pass a string to the model and return a string prediction.

Use this method when calling pure text generation models and only the top

candidate generation is needed.

Parameters
  • text – String input to pass to the model.

  • stop – Stop words to use when generating. Model output is cut off at the first occurrence of any of these substrings.

  • **kwargs – Arbitrary additional keyword arguments. These are usually passed to the model provider API call.

Returns

Top model prediction as a string.

async apredict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) BaseMessage¶

Asynchronously pass messages to the model and return a message prediction.

Use this method when calling chat models and only the top

candidate generation is needed.

Parameters
  • messages – A sequence of chat messages corresponding to a single model input.

  • stop – Stop words to use when generating. Model output is cut off at the first occurrence of any of these substrings.

  • **kwargs – Arbitrary additional keyword arguments. These are usually passed to the model provider API call.

Returns

Top model prediction as a message.

async astream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) AsyncIterator[BaseMessageChunk]¶
validator build_extra  »  all fields¶

Build extra kwargs from additional params that were passed in.

call_as_llm(message: str, stop: Optional[List[str]] = None, **kwargs: Any) str¶
completion_with_retry(run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any) Any¶

Use tenacity to retry the completion call.

dict(**kwargs: Any) Dict¶

Return a dictionary of the LLM.

generate(messages: List[List[BaseMessage]], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) LLMResult¶

Top Level call

generate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) LLMResult¶

Pass a sequence of prompts to the model and return model generations.

This method should make use of batched calls for models that expose a batched API.

Use this method when you want to:
  1. take advantage of batched calls,

  2. need more output from the model than just the top generated value,

  3. are building chains that are agnostic to the underlying language model

    type (e.g., pure text completion models vs chat models).

Parameters
  • prompts – List of PromptValues. A PromptValue is an object that can be converted to match the format of any language model (string for pure text generation models and BaseMessages for chat models).

  • stop – Stop words to use when generating. Model output is cut off at the first occurrence of any of these substrings.

  • callbacks – Callbacks to pass through. Used for executing additional functionality, such as logging or streaming, throughout generation.

  • **kwargs – Arbitrary additional keyword arguments. These are usually passed to the model provider API call.

Returns

An LLMResult, which contains a list of candidate Generations for each input

prompt and additional model provider-specific output.

get_num_tokens(text: str) int¶

Get the number of tokens present in the text.

Useful for checking if an input will fit in a model’s context window.

Parameters

text – The string input to tokenize.

Returns

The integer number of tokens in the text.

get_num_tokens_from_messages(messages: List[BaseMessage]) int¶

Calculate num tokens for gpt-3.5-turbo and gpt-4 with tiktoken package.

Official documentation: https://github.com/openai/openai-cookbook/blob/ main/examples/How_to_format_inputs_to_ChatGPT_models.ipynb

get_token_ids(text: str) List[int]¶

Get the tokens present in the text with tiktoken package.

invoke(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) BaseMessageChunk¶
predict(text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any) str¶

Pass a single string input to the model and return a string prediction.

Use this method when passing in raw text. If you want to pass in specific

types of chat messages, use predict_messages.

Parameters
  • text – String input to pass to the model.

  • stop – Stop words to use when generating. Model output is cut off at the first occurrence of any of these substrings.

  • **kwargs – Arbitrary additional keyword arguments. These are usually passed to the model provider API call.

Returns

Top model prediction as a string.

predict_messages(messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: Any) BaseMessage¶

Pass a message sequence to the model and return a message prediction.

Use this method when passing in chat messages. If you want to pass in raw text,

use predict.

Parameters
  • messages – A sequence of chat messages corresponding to a single model input.

  • stop – Stop words to use when generating. Model output is cut off at the first occurrence of any of these substrings.

  • **kwargs – Arbitrary additional keyword arguments. These are usually passed to the model provider API call.

Returns

Top model prediction as a message.

validator raise_deprecation  »  all fields¶

Raise deprecation warning if callback_manager is used.

stream(input: Union[PromptValue, str, List[BaseMessage]], config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) Iterator[BaseMessageChunk]¶
to_json() Union[SerializedConstructor, SerializedNotImplemented]¶
to_json_not_implemented() SerializedNotImplemented¶
validator validate_environment  »  all fields[source]¶

Validate that api key and python package exists in environment.

property lc_attributes: Dict¶

Return a list of attribute names that should be included in the serialized kwargs. These attributes must be accepted by the constructor.

property lc_namespace: List[str]¶

Return the namespace of the langchain object. eg. [“langchain”, “llms”, “openai”]

property lc_secrets: Dict[str, str]¶

Return a map of constructor argument names to secret ids. eg. {“openai_api_key”: “OPENAI_API_KEY”}

property lc_serializable: bool¶

Return whether or not the class is serializable.

model Config¶

Bases: object

Configuration for this pydantic object.

allow_population_by_field_name = True¶

Examples using AzureChatOpenAI¶