class_docstr: Enables text generation using OpenAI's large language models (LLMs). It supports gpt-4 and gpt-3.5-turbo
  family of models accessed through the chat completions API endpoint.
  
  Users can pass any text generation parameters valid for the `openai.ChatCompletion.create` method
  directly to this component via the `**generation_kwargs` parameter in __init__ or the `**generation_kwargs`
  parameter in `run` method.
  
  For more details on the parameters supported by the OpenAI API, refer to the OpenAI
  [documentation](https://platform.openai.com/docs/api-reference/chat).
  
  ```python
  from haystack.components.generators.chat import OpenAIChatGenerator
  from haystack.dataclasses import ChatMessage
  
  messages = [ChatMessage.from_user("What's Natural Language Processing?")]
  
  client = OpenAIChatGenerator()
  response = client.run(messages)
  print(response)
  
  >>{'replies': [ChatMessage(content='Natural Language Processing (NLP) is a branch of artificial intelligence
  >>that focuses on enabling computers to understand, interpret, and generate human language in a way that is
  >>meaningful and useful.', role=<ChatRole.ASSISTANT: 'assistant'>, name=None,
  >>meta={'model': 'gpt-3.5-turbo-0613', 'index': 0, 'finish_reason': 'stop',
  >>'usage': {'prompt_tokens': 15, 'completion_tokens': 36, 'total_tokens': 51}})]}
  
  ```
  
   Key Features and Compatibility:
       - **Primary Compatibility**: Designed to work seamlessly with the OpenAI API Chat Completion endpoint
          and gpt-4 and gpt-3.5-turbo family of models.
       - **Streaming Support**: Supports streaming responses from the OpenAI API Chat Completion endpoint.
       - **Customizability**: Supports all parameters supported by the OpenAI API Chat Completion endpoint.
  
   Input and Output Format:
       - **ChatMessage Format**: This component uses the ChatMessage format for structuring both input and output,
         ensuring coherent and contextually relevant responses in chat-based text generation scenarios. Details on the
         ChatMessage format can be found at: https://github.com/openai/openai-python/blob/main/chatml.md.
class_docstr_tok: ["Enables","text","generation","using","OpenAI","'s","large","language","models","(","LLMs",")",".","It","supports","gpt-4","and","gpt-3.5-turbo","family","of","models","accessed","through","the","chat","completions","API","endpoint",".","Users","can","pass","any","text","generation","parameters","valid","for","the","`","openai.ChatCompletion.create","`","method","directly","to","this","component","via","the","`","*","*","generation_kwargs","`","parameter","in","__init__","or","the","`","*","*","generation_kwargs","`","parameter","in","`","run","`","method",".","For","more","details","on","the","parameters","supported","by","the","OpenAI","API",",","refer","to","the","OpenAI","[","documentation","]","(","https",":","\/\/platform.openai.com\/docs\/api-reference\/chat",")",".","``","`","python","from","haystack.components.generators.chat","import","OpenAIChatGenerator","from","haystack.dataclasses","import","ChatMessage","messages","=","[","ChatMessage.from_user","(","``","What","'s","Natural","Language","Processing","?","''",")","]","client","=","OpenAIChatGenerator","(",")","response","=","client.run","(","messages",")","print","(","response",")",">",">","{","'replies","'",":","[","ChatMessage","(","content='Natural","Language","Processing","(","NLP",")","is","a","branch","of","artificial","intelligence",">",">","that","focuses","on","enabling","computers","to","understand",",","interpret",",","and","generate","human","language","in","a","way","that","is",">",">","meaningful","and","useful",".","'",",","role=","<","ChatRole.ASSISTANT",":","'assistant","'",">",",","name=None",",",">",">","meta=","{","'model","'",":","'gpt-3.5-turbo-0613","'",",","'index","'",":","0",",","'finish_reason","'",":","'stop","'",",",">",">","'usage","'",":","{","'prompt_tokens","'",":","15",",","'completion_tokens","'",":","36",",","'total_tokens","'",":","51","}","}",")","]","}","``","`","Key","Features","and","Compatibility",":","-","*","*","Primary","Compatibility","*","*",":","Designed","to","work","seamlessly","with","the","OpenAI","API","Chat","Completion","endpoint","and","gpt-4","and","gpt-3.5-turbo","family","of","models",".","-","*","*","Streaming","Support","*","*",":","Supports","streaming","responses","from","the","OpenAI","API","Chat","Completion","endpoint",".","-","*","*","Customizability","*","*",":","Supports","all","parameters","supported","by","the","OpenAI","API","Chat","Completion","endpoint",".","Input","and","Output","Format",":","-","*","*","ChatMessage","Format","*","*",":","This","component","uses","the","ChatMessage","format","for","structuring","both","input","and","output",",","ensuring","coherent","and","contextually","relevant","responses","in","chat-based","text","generation","scenarios",".","Details","on","the","ChatMessage","format","can","be","found","at",":","https",":","\/\/github.com\/openai\/openai-python\/blob\/main\/chatml.md","."]
docstr: Invoke the text generation inference based on the provided messages and generation parameters.
  
  :param messages: A list of ChatMessage instances representing the input messages.
  :param generation_kwargs: Additional keyword arguments for text generation. These parameters will
  potentially override the parameters passed in the __init__ method.
  For more details on the parameters supported by the OpenAI API, refer to the
  OpenAI [documentation](https://platform.openai.com/docs/api-reference/chat/create).
  :return: A list containing the generated responses as ChatMessage instances.
docstr_tok: ["Invoke","the","text","generation","inference","based","on","the","provided","messages","and","generation","parameters",".",":","param","messages",":","A","list","of","ChatMessage","instances","representing","the","input","messages",".",":","param","generation_kwargs",":","Additional","keyword","arguments","for","text","generation",".","These","parameters","will","potentially","override","the","parameters","passed","in","the","__init__","method",".","For","more","details","on","the","parameters","supported","by","the","OpenAI","API",",","refer","to","the","OpenAI","[","documentation","]","(","https",":","\/\/platform.openai.com\/docs\/api-reference\/chat\/create",")",".",":","return",":","A","list","containing","the","generated","responses","as","ChatMessage","instances","."]
code: def run(
      self,
      messages: List[ChatMessage],
      generation_kwargs: Optional[Dict[str, Any]] = None,
  ):
      """
      Invoke the text generation inference based on the provided messages and generation parameters.
  
      :param messages: A list of ChatMessage instances representing the input messages.
      :param generation_kwargs: Additional keyword arguments for text generation. These parameters will
      potentially override the parameters passed in the __init__ method.
      For more details on the parameters supported by the OpenAI API, refer to the
      OpenAI [documentation](https://platform.openai.com/docs/api-reference/chat/create).
      :return: A list containing the generated responses as ChatMessage instances.
      """
  
      # update generation kwargs by merging with the generation kwargs passed to the run method
      generation_kwargs = {
          **self.generation_kwargs,
          **(generation_kwargs or {}),
      }
  
      # adapt ChatMessage(s) to the format expected by the OpenAI API
      openai_formatted_messages = self._convert_to_openai_format(
          messages
      )
  
      chat_completion: Union[
          Stream[ChatCompletionChunk], ChatCompletion
      ] = self.client.chat.completions.create(
          model=self.model,
          messages=openai_formatted_messages,  # type: ignore # openai expects list of specific message types
          stream=self.streaming_callback is not None,
          **generation_kwargs,
      )
  
      completions: List[ChatMessage] = []
      # if streaming is enabled, the completion is a Stream of ChatCompletionChunk
      if isinstance(chat_completion, Stream):
          num_responses = generation_kwargs.pop("n", 1)
          if num_responses > 1:
              raise ValueError(
                  "Cannot stream multiple responses, please set n=1."
              )
          chunks: List[StreamingChunk] = []
          chunk = None
  
          # pylint: disable=not-an-iterable
          for chunk in chat_completion:
              if chunk.choices and self.streaming_callback:
                  chunk_delta: StreamingChunk = self._build_chunk(chunk)
                  chunks.append(chunk_delta)
                  self.streaming_callback(
                      chunk_delta
                  )  # invoke callback with the chunk_delta
          completions = [self._connect_chunks(chunk, chunks)]
      # if streaming is disabled, the completion is a ChatCompletion
      elif isinstance(chat_completion, ChatCompletion):
          completions = [
              self._build_message(chat_completion, choice)
              for choice in chat_completion.choices
          ]
  
      # before returning, do post-processing of the completions
      for message in completions:
          self._check_finish_reason(message)
  
      return {"replies": completions}
  
imports: import copy
  import dataclasses
  import json
  import logging
  import warnings
  from typing import Optional, List, Callable, Dict, Any, Union
  from openai import OpenAI, Stream
  from openai.types.chat import ChatCompletionChunk, ChatCompletion, ChatCompletionMessage
  from openai.types.chat.chat_completion import Choice
  from openai.types.chat.chat_completion_chunk import Choice
  from haystack import component, default_from_dict, default_to_dict
  from haystack.components.generators.utils import serialize_callback_handler, deserialize_callback_handler
  from haystack.dataclasses import StreamingChunk, ChatMessage
label_desc: Use image node_id 5 for calling the OpenAIChatGenerator obj's underlying member method code with example usage: obj.run(messages, generation_kwargs) and returns: dict