Repository: deepset-ai/haystack
Pull request: feat: Configure `max_retries` and timeout for `AzureOpenAIChatGenerator`
max_retries: if not set is read from the OPENAI_MAX_RETRIES env variable or set to 5.

timeout: if not set is read from the OPENAI_TIMEOUT env variable or set to 30.

### Related Issues

- fixes #7945 

### Proposed Changes:

AzureOpenAIChatGenerator can be initiated using max_retries.
timeout can also be set using the env variable `OPENAI_TIMEOUT`


### How did you test it?

unit tests

### Notes for the reviewer

<!-- E.g. point out section where the reviewer  -->
There are a few other similar PRs for the issue. This is the 2/4 PR.

### Checklist

- I have read the [contributors guidelines](https://github.com/deepset-ai/haystack/blob/main/CONTRIBUTING.md) and the [code of conduct](https://github.com/deepset-ai/haystack/blob/main/code_of_conduct.txt)
- I have updated the related issue with new insights and changes
- I added unit tests and updated the docstrings
- I've used one of the [conventional commit types](https://www.conventionalcommits.org/en/v1.0.0/) for my PR title: `fix:`, `feat:`, `build:`, `chore:`, `ci:`, `docs:`, `style:`, `refactor:`, `perf:`, `test:`.
- I documented my code
- I ran [pre-commit hooks](https://github.com/deepset-ai/haystack/blob/main/CONTRIBUTING.md#installation) and fixed any issue


Problem statement:
Add `max_retries` and `timeout` params to all `AzureOpenAI` classes
**Is your feature request related to a problem? Please describe.**

Currently all `OpenAI` related classes (e.g. `OpenAIDocumentEmbedder`, `OpenAIChatGenerator`) can be initialised by setting `max_retries` and `timeout` params.

The corresponding `AzureOpenAI` don't always have the same params.

**Describe the solution you'd like**

It would be nice to have these params in the `AzureOpenAI` classes

**Describe alternatives you've considered**

Subclass `AzureOpenAI` and create custom components.

**Additional context**

cc @anakin87 :)

Hints from issue discussion:
Thanks @EdoardoAbatiTR!

I'm also opening this for contributions. In case anyone is interested, let's discuss it here.
Hey, 

I am new here. Can I assign this to myself? 
@nvzard feel free to work on this. Take a look at the [guidelines for contributors](https://github.com/deepset-ai/haystack/blob/main/CONTRIBUTING.md).

I would suggest creating one PR for each component to be changed.
E.g., start with [`AzureOpenAIGenerator`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/generators/azure.py) and use [`OpenAIGenerator`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/generators/openai.py) as an inspiration.
@anakin87 thanks for the references 😄 

I've made the [first PR](https://github.com/deepset-ai/haystack/pull/7983) for `AzureOpenAIGenerator`, let me know if I missed anything. 

Pending: `AzureOpenAIDocumentEmbedder`, `AzureOpenAITextEmbedder`, `AzureOpenAIChatGenerator`

Commit message: feat: Configure max_retries & timeout for AzureOpenAIChatGenerator

max_retries: if not set is read from the OPENAI_MAX_RETRIES
env variable or set to 5.

timeout: if not set is read from the OPENAI_TIMEOUT
env variable or set to 30.

Signed-off-by: Nitanshu Vashistha <nitanshu.vzard@gmail.com>

Patch to review:
diff --git a/haystack/components/generators/chat/azure.py b/haystack/components/generators/chat/azure.py
index 06da6095ae..daadf94be8 100644
--- a/haystack/components/generators/chat/azure.py
+++ b/haystack/components/generators/chat/azure.py
@@ -81,6 +81,7 @@ def __init__(
         organization: Optional[str] = None,
         streaming_callback: Optional[Callable[[StreamingChunk], None]] = None,
         timeout: Optional[float] = None,
+        max_retries: Optional[int] = None,
         generation_kwargs: Optional[Dict[str, Any]] = None,
     ):
         """
@@ -95,6 +96,10 @@ def __init__(
         [production best practices](https://platform.openai.com/docs/guides/production-best-practices/setting-up-your-organization).
         :param streaming_callback: A callback function that is called when a new token is received from the stream.
             The callback function accepts StreamingChunk as an argument.
+        :param timeout: The timeout to be passed to the underlying `AzureOpenAI` client, if not set it is
+            inferred from the `OPENAI_TIMEOUT` environment variable or set to 30.
+        :param max_retries: Maximum retries to establish contact with AzureOpenAI if it returns an internal error,
+            if not set it is inferred from the `OPENAI_MAX_RETRIES` environment variable or set to 5.
         :param generation_kwargs: Other parameters to use for the model. These parameters are all sent directly to
             the OpenAI endpoint. See OpenAI [documentation](https://platform.openai.com/docs/api-reference/chat) for
             more details.
@@ -140,7 +145,8 @@ def __init__(
         self.azure_deployment = azure_deployment
         self.organization = organization
         self.model = azure_deployment or "gpt-35-turbo"
-        self.timeout = timeout
+        self.timeout = timeout or float(os.environ.get("OPENAI_TIMEOUT", 30.0))
+        self.max_retries = max_retries or int(os.environ.get("OPENAI_MAX_RETRIES", 5))
 
         self.client = AzureOpenAI(
             api_version=api_version,
@@ -149,6 +155,8 @@ def __init__(
             api_key=api_key.resolve_value() if api_key is not None else None,
             azure_ad_token=azure_ad_token.resolve_value() if azure_ad_token is not None else None,
             organization=organization,
+            timeout=self.timeout,
+            max_retries=self.max_retries,
         )
 
     def to_dict(self) -> Dict[str, Any]:
@@ -168,6 +176,7 @@ def to_dict(self) -> Dict[str, Any]:
             streaming_callback=callback_name,
             generation_kwargs=self.generation_kwargs,
             timeout=self.timeout,
+            max_retries=self.max_retries,
             api_key=self.api_key.to_dict() if self.api_key is not None else None,
             azure_ad_token=self.azure_ad_token.to_dict() if self.azure_ad_token is not None else None,
         )
diff --git a/releasenotes/notes/max_retries-for-AzureOpenAIChatGenerator-9e49b4c7bec5c72b.yaml b/releasenotes/notes/max_retries-for-AzureOpenAIChatGenerator-9e49b4c7bec5c72b.yaml
new file mode 100644
index 0000000000..2004ed3904
--- /dev/null
+++ b/releasenotes/notes/max_retries-for-AzureOpenAIChatGenerator-9e49b4c7bec5c72b.yaml
@@ -0,0 +1,9 @@
+---
+enhancements:
+  - |
+    Add max_retries to AzureOpenAIChatGenerator.
+    AzureOpenAIChatGenerator can now be initialised by setting max_retries.
+    If not set, it is inferred from the `OPENAI_MAX_RETRIES`
+    environment variable or set to 5.
+    The timeout for AzureOpenAIChatGenerator, if not set, it is inferred
+    from the `OPENAI_TIMEOUT` environment variable or set to 30.
diff --git a/test/components/generators/chat/test_azure.py b/test/components/generators/chat/test_azure.py
index 80ffb95641..80a290a65c 100644
--- a/test/components/generators/chat/test_azure.py
+++ b/test/components/generators/chat/test_azure.py
@@ -55,7 +55,8 @@ def test_to_dict_default(self, monkeypatch):
                 "organization": None,
                 "streaming_callback": None,
                 "generation_kwargs": {},
-                "timeout": None,
+                "timeout": 30.0,
+                "max_retries": 5,
             },
         }
 
@@ -66,6 +67,7 @@ def test_to_dict_with_parameters(self, monkeypatch):
             azure_ad_token=Secret.from_env_var("ENV_VAR1", strict=False),
             azure_endpoint="some-non-existing-endpoint",
             timeout=2.5,
+            max_retries=10,
             generation_kwargs={"max_tokens": 10, "some_test_param": "test-params"},
         )
         data = component.to_dict()
@@ -80,6 +82,7 @@ def test_to_dict_with_parameters(self, monkeypatch):
                 "organization": None,
                 "streaming_callback": None,
                 "timeout": 2.5,
+                "max_retries": 10,
                 "generation_kwargs": {"max_tokens": 10, "some_test_param": "test-params"},
             },
         }


Code review comments:
diff_hunk: @@ -95,6 +96,10 @@ def __init__(
         [production best practices](https://platform.openai.com/docs/guides/production-best-practices/setting-up-your-organization).
         :param streaming_callback: A callback function that is called when a new token is received from the stream.
             The callback function accepts StreamingChunk as an argument.
+        :param timeout: The timeout to be passed to the underlying `AzureOpenAI` client, if not set it is
+            inferred from the `OPENAI_TIMEOUT` environment variable or set to 30.
+        :param max_retries: Maximum retries to establish contact with AzureOpenAI if it returns an internal error,
path: haystack/components/generators/chat/azure.py
text: @user1:
```suggestion
        :param max_retries: Maximum retries to establish a connection with AzureOpenAI if it returns an internal error,
```

diff_hunk: @@ -95,6 +96,10 @@ def __init__(
         [production best practices](https://platform.openai.com/docs/guides/production-best-practices/setting-up-your-organization).
         :param streaming_callback: A callback function that is called when a new token is received from the stream.
             The callback function accepts StreamingChunk as an argument.
+        :param timeout: The timeout to be passed to the underlying `AzureOpenAI` client, if not set it is
path: haystack/components/generators/chat/azure.py
text: @user1:
```suggestion
        :param timeout: The timeout in seconds to be passed to the underlying `AzureOpenAI` client, if not set it is
```