Skip to content

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

refactor(config): support thread and async safe configuration by using `ContextVar` (#933)

zhijianma9a6f4522f089
diff --git a/.github/workflows/unittest.yml b/.github/workflows/unittest.yml
index 3de7c64a6..bce8effe1 100644
--- a/.github/workflows/unittest.yml
+++ b/.github/workflows/unittest.yml
@@ -8,7 +8,7 @@ jobs:
runs-on: ${{ matrix.os }}
strategy:
matrix:
- os: [ubuntu-latest, windows-latest, macos-13]
+ os: [ubuntu-latest, windows-latest, macos-15]
python-version: ['3.10', '3.11', '3.12']
env:
OS: ${{ matrix.os }}
diff --git a/src/agentscope/__init__.py b/src/agentscope/__init__.py
index 67cb54076..d102fdce6 100644
--- a/src/agentscope/__init__.py
+++ b/src/agentscope/__init__.py
@@ -1,8 +1,45 @@
# -*- coding: utf-8 -*-
+# flake8: noqa: E402
+# pylint: disable=wrong-import-position
"""The agentscope serialization module"""
import os
+from contextvars import ContextVar
+from datetime import datetime
import requests
+import shortuuid
+
+from ._run_config import _ConfigCls
+
+
+def _generate_random_suffix(length: int) -> str:
+ """Generate a random suffix."""
+ return shortuuid.uuid()[:length]
+
+
+# A thread and async safe global configuration instance
+_config = _ConfigCls(
+ run_id=ContextVar("run_id", default=shortuuid.uuid()),
+ project=ContextVar(
+ "project",
+ default="UnnamedProject_At" + datetime.now().strftime("%Y%m%d"),
+ ),
+ name=ContextVar(
+ "name",
+ default=datetime.now().strftime("%H%M%S_")
+ + _generate_random_suffix(4),
+ ),
+ created_at=ContextVar(
+ "created_at",
+ default=datetime.now().strftime("%H%M%S_")
+ + _generate_random_suffix(4),
+ ),
+ trace_enabled=ContextVar(
+ "trace_enabled",
+ default=False,
+ ),
+)
+
from . import exception
from . import module
@@ -31,6 +68,7 @@ from ._version import __version__
def init(
project: str | None = None,
name: str | None = None,
+ run_id: str | None = None,
logging_path: str | None = None,
logging_level: str = "INFO",
studio_url: str | None = None,
@@ -43,6 +81,10 @@ def init(
The project name.
name (`str | None`, optional):
The name of the run.
+ run_id (`str | None`, optional):
+ The identity of a running instance, which can be an agent, or a
+ multi-agent system. The `run_id` is used in AgentScope-Studio to
+ distinguish different runs.
logging_path (`str | None`, optional):
The path to saving the log file. If not provided, logs will not be
saved.
@@ -57,14 +99,15 @@ def init(
to the AgentScope Studio's tracing endpoint.
"""
- from . import _config
-
if project:
_config.project = project
if name:
_config.name = name
+ if run_id:
+ _config.run_id = run_id
+
setup_logger(logging_level, logging_path)
if studio_url:
@@ -106,6 +149,7 @@ def init(
from .tracing import setup_tracing
setup_tracing(endpoint=endpoint)
+ _config.trace_enabled = True
__all__ = [
diff --git a/src/agentscope/_config.py b/src/agentscope/_config.py
deleted file mode 100644
index 1311e2299..000000000
--- a/src/agentscope/_config.py
+++ /dev/null
@@ -1,23 +0,0 @@
-# -*- coding: utf-8 -*-
-"""The runtime configuration in agentscope.
-
-.. note:: You should import this module as ``import ._config``, then use the
- variables defined in this module, instead of ``from ._config import xxx``.
- Because when the variables are changed, the changes will not be reflected in
- the imported module.
-"""
-from datetime import datetime
-
-import shortuuid
-
-
-def _generate_random_suffix(length: int) -> str:
- """Generate a random suffix."""
- return shortuuid.uuid()[:length]
-
-
-project = "UnnamedProject_At" + datetime.now().strftime("%Y%m%d")
-name = datetime.now().strftime("%H%M%S_") + _generate_random_suffix(4)
-run_id: str = shortuuid.uuid()
-created_at: str = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
-trace_enabled: bool = False
diff --git a/src/agentscope/_run_config.py b/src/agentscope/_run_config.py
new file mode 100644
index 000000000..8f8303117
--- /dev/null
+++ b/src/agentscope/_run_config.py
@@ -0,0 +1,73 @@
+# -*- coding: utf-8 -*-
+"""The run instance configuration in agentscope."""
+from contextvars import ContextVar
+
+
+class _ConfigCls:
+ """The run instance configuration in agentscope."""
+
+ def __init__(
+ self,
+ run_id: ContextVar[str],
+ project: ContextVar[str],
+ name: ContextVar[str],
+ created_at: ContextVar[str],
+ trace_enabled: ContextVar[bool],
+ ) -> None:
+ """The constructor for _Config class."""
+ # Copy the default context variables
+ self._run_id = run_id
+ self._created_at = created_at
+ self._project = project
+ self._name = name
+ self._trace_enabled = trace_enabled
+
+ @property
+ def run_id(self) -> str:
+ """Get the run ID."""
+ return self._run_id.get()
+
+ @run_id.setter
+ def run_id(self, value: str) -> None:
+ """Set the run ID."""
+ self._run_id.set(value)
+
+ @property
+ def created_at(self) -> str:
+ """Get the creation time."""
+ return self._created_at.get()
+
+ @created_at.setter
+ def created_at(self, value: str) -> None:
+ """Set the creation time."""
+ self._created_at.set(value)
+
+ @property
+ def project(self) -> str:
+ """Get the project name."""
+ return self._project.get()
+
+ @project.setter
+ def project(self, value: str) -> None:
+ """Set the project name."""
+ self._project.set(value)
+
+ @property
+ def name(self) -> str:
+ """Get the run name."""
+ return self._name.get()
+
+ @name.setter
+ def name(self, value: str) -> None:
+ """Set the run name."""
+ self._name.set(value)
+
+ @property
+ def trace_enabled(self) -> bool:
+ """Get whether tracing is enabled."""
+ return self._trace_enabled.get()
+
+ @trace_enabled.setter
+ def trace_enabled(self, value: bool) -> None:
+ """Set whether tracing is enabled."""
+ self._trace_enabled.set(value)
diff --git a/src/agentscope/tracing/_setup.py b/src/agentscope/tracing/_setup.py
index 33835f23e..be815a930 100644
--- a/src/agentscope/tracing/_setup.py
+++ b/src/agentscope/tracing/_setup.py
@@ -1,6 +1,5 @@
# -*- coding: utf-8 -*-
"""The tracing interface class in agentscope."""
-from agentscope import _config
def setup_tracing(endpoint: str) -> None:
@@ -23,5 +22,3 @@ def setup_tracing(endpoint: str) -> None:
span_processor = BatchSpanProcessor(exporter)
tracer_provider.add_span_processor(span_processor)
trace.set_tracer_provider(tracer_provider)
-
- _config.trace_enabled = True
diff --git a/tests/config_test.py b/tests/config_test.py
new file mode 100644
index 000000000..4844a634b
--- /dev/null
+++ b/tests/config_test.py
@@ -0,0 +1,74 @@
+# -*- coding: utf-8 -*-
+"""Unittests for the config module."""
+import asyncio
+import threading
+from unittest.async_case import IsolatedAsyncioTestCase
+
+import agentscope
+from agentscope import _config
+
+
+result = {}
+
+
+async def async_task(field: str) -> str:
+ """A sample async task to demonstrate context variable usage."""
+ prefix = "async_task"
+ agentscope.init(
+ run_id=f"{prefix}_run_id",
+ project=f"{prefix}_project",
+ name=f"{prefix}_name",
+ )
+ if field == "run_id":
+ return _config.run_id
+ elif field == "project":
+ return _config.project
+ elif field == "name":
+ return _config.name
+ else:
+ return ""
+
+
+def sync_task(field: str) -> None:
+ """A sample sync task to demonstrate context variable usage."""
+ prefix = "sync_task"
+ agentscope.init(
+ run_id=f"{prefix}_run_id",
+ project=f"{prefix}_project",
+ name=f"{prefix}_name",
+ )
+ if field == "run_id":
+ result["value"] = _config.run_id
+ elif field == "project":
+ result["value"] = _config.project
+ elif field == "name":
+ result["value"] = _config.name
+ else:
+ result["value"] = None
+
+
+class ConfigTest(IsolatedAsyncioTestCase):
+ """Unittests for the config module."""
+
+ async def test_config_attributes(self) -> None:
+ """Test the config attributes."""
+ agentscope.init(
+ project="root_project",
+ name="root_name",
+ run_id="root_run_id",
+ )
+
+ for field in ["project", "name", "run_id"]:
+ # Test root context
+ self.assertEqual(getattr(_config, field), f"root_{field}")
+
+ # Test asynchronous task
+ res = await asyncio.create_task(async_task(field))
+ self.assertEqual(res, f"async_task_{field}")
+
+ # Test synchronous task in a separate thread
+ thread = threading.Thread(target=sync_task, args=(field,))
+ thread.start()
+ thread.join()
+
+ self.assertEqual(result["value"], f"sync_task_{field}")