class_docstr: Enables text generation using OpenAI's large language models (LLMs). It supports gpt-4 and gpt-3.5-turbo
  family of models.
  
  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 import OpenAIGenerator
  client = OpenAIGenerator()
  response = client.run("What's Natural Language Processing? Be brief.")
  print(response)
  
  >> {'replies': ['Natural Language Processing (NLP) is a branch of artificial intelligence that focuses on
  >> the interaction between computers and human language. It involves enabling computers to understand, interpret,
  >> and respond to natural human language in a way that is both meaningful and useful.'], 'meta': [{'model':
  >> 'gpt-3.5-turbo-0613', 'index': 0, 'finish_reason': 'stop', 'usage': {'prompt_tokens': 16,
  >> 'completion_tokens': 49, 'total_tokens': 65}}]}
  ```
  
   Key Features and Compatibility:
       - **Primary Compatibility**: Designed to work seamlessly with gpt-4, gpt-3.5-turbo family of models.
       - **Streaming Support**: Supports streaming responses from the OpenAI API.
       - **Customizability**: Supports all parameters supported by the OpenAI API.
  
   Input and Output Format:
       - **String Format**: This component uses the strings for both input and output.
docstr: Invoke the text generation inference based on the provided messages and generation parameters.
  
  :param prompt: The string prompt to use for text generation.
  :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 of strings containing the generated responses and a list of dictionaries containing the metadata
  for each response.
docstr_tok: ["Invoke","the","text","generation","inference","based","on","the","provided","messages","and","generation","parameters",".",":","param","prompt",":","The","string","prompt","to","use","for","text","generation",".",":","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","of","strings","containing","the","generated","responses","and","a","list","of","dictionaries","containing","the","metadata","for","each","response","."]
code: def run(
      self,
      prompt: str,
      generation_kwargs: Optional[Dict[str, Any]] = None,
  ):
      """
      Invoke the text generation inference based on the provided messages and generation parameters.
  
      :param prompt: The string prompt to use for text generation.
      :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 of strings containing the generated responses and a list of dictionaries containing the metadata
      for each response.
      """
      message = ChatMessage.from_user(prompt)
      if self.system_prompt:
          messages = [
              ChatMessage.from_system(self.system_prompt),
              message,
          ]
      else:
          messages = [message]
  
      # 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
      )
  
      completion: Union[
          Stream[ChatCompletionChunk], ChatCompletion
      ] = self.client.chat.completions.create(
          model=self.model,
          messages=openai_formatted_messages,  # type: ignore
          stream=self.streaming_callback is not None,
          **generation_kwargs,
      )
  
      completions: List[ChatMessage] = []
      if isinstance(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 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)]
      elif isinstance(completion, ChatCompletion):
          completions = [
              self._build_message(completion, choice)
              for choice in completion.choices
          ]
  
      # before returning, do post-processing of the completions
      for response in completions:
          self._check_finish_reason(response)
  
      return {
          "replies": [message.content for message in completions],
          "meta": [message.meta for message in completions],
      }
  
imports: import dataclasses
  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
  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 OpenAIGenerator obj's underlying member method code with example usage: obj.run(prompt, generation_kwargs) and returns: dict