Skip to content

Build and run agents you can see, understand and trust.

feat(dashscope): support to load headers from the environment (#1096)

DavdGao40a108915259
diff --git a/src/agentscope/model/_dashscope_model.py b/src/agentscope/model/_dashscope_model.py
index 062642042..d26c02819 100644
--- a/src/agentscope/model/_dashscope_model.py
+++ b/src/agentscope/model/_dashscope_model.py
@@ -1,6 +1,8 @@
# -*- coding: utf-8 -*-
"""The dashscope API model classes."""
import collections
+import json
+import os
import warnings
from datetime import datetime
from http import HTTPStatus
@@ -100,6 +102,25 @@ class DashScopeChatModel(ChatModelBase):
dashscope.base_http_api_url = base_http_api_url
+ # Load headers from environment variable if exists
+ headers = os.getenv("DASHSCOPE_API_HEADERS")
+ if headers:
+ try:
+ headers = json.loads(str(headers))
+ if not isinstance(headers, dict):
+ raise json.JSONDecodeError("", "", 0)
+
+ if self.generate_kwargs.get("headers"):
+ headers.update(self.generate_kwargs["headers"])
+
+ self.generate_kwargs["headers"] = headers
+
+ except json.JSONDecodeError:
+ logger.warning(
+ "Failed to parse DASHSCOPE_API_HEADERS environment "
+ "variable as JSON. It should be a JSON object.",
+ )
+
@trace_llm
async def __call__(
self,