Skip to content

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

feat(utils): add configurable ID factory via `set_id_factory()` (#1839)

lajxwd80427e52d6e
diff --git a/src/agentscope/__init__.py b/src/agentscope/__init__.py
index 69dbdbf0e..f2ce72607 100644
--- a/src/agentscope/__init__.py
+++ b/src/agentscope/__init__.py
@@ -6,6 +6,7 @@ from ._logging import (
logger,
setup_logger,
)
+from ._utils._common import set_id_factory
from ._version import __version__
# Raise each warning only once
@@ -15,5 +16,6 @@ warnings.filterwarnings("once", category=DeprecationWarning)
__all__ = [
"logger",
"setup_logger",
+ "set_id_factory",
"__version__",
]
diff --git a/src/agentscope/_utils/_common.py b/src/agentscope/_utils/_common.py
index 37d326308..01ac9fbf1 100644
--- a/src/agentscope/_utils/_common.py
+++ b/src/agentscope/_utils/_common.py
@@ -11,13 +11,51 @@ import uuid
from datetime import datetime
from typing import Any, Callable
-import requests
-from json_repair import repair_json
-
from .._logging import logger
from ..exception import ToolJSONDecodeError
+def _default_id_factory() -> str:
+ return uuid.uuid4().hex
+
+
+_id_factory: Callable[[], str] = _default_id_factory
+
+
+def set_id_factory(factory: Callable[[], str]) -> None:
+ """Override the global ID factory used by all AgentScope entities.
+
+ Entity IDs default to ``uuid.uuid4().hex``. Call this once at
+ startup to substitute a different strategy.
+
+ .. note::
+ Security-sensitive tokens (gateway tokens, Redis lock tokens)
+ are **not** affected and always use ``uuid.uuid4().hex``.
+
+ Args:
+ factory (`Callable[[], str]`):
+ A no-arg callable returning a string ID.
+
+ Raises:
+ TypeError: If ``factory`` is not callable.
+
+ Example:
+ >>> from agentscope import set_id_factory
+ >>> set_id_factory(lambda: uuid7().hex)
+ """
+ if not callable(factory):
+ raise TypeError(
+ f"factory must be a callable, got {type(factory).__name__}",
+ )
+ global _id_factory
+ _id_factory = factory
+
+
+def _generate_id() -> str:
+ """Generate an ID string using the current global ID factory."""
+ return _id_factory()
+
+
def _json_loads_with_repair(
json_str: str,
schema: dict | None = None,
@@ -60,6 +98,8 @@ def _json_loads_with_repair(
try:
# Try to repair with json_repair
+ from json_repair import repair_json
+
repaired = repair_json(json_str, stream_stable=True, schema=schema)
res = json.loads(repaired)
if isinstance(res, dict):
@@ -162,6 +202,8 @@ def _get_bytes_from_web_url(
max_retries (`int`, defaults to `3`):
The maximum number of retries.
"""
+ import requests
+
for _ in range(max_retries):
try:
response = requests.get(url)
diff --git a/src/agentscope/agent/_agent.py b/src/agentscope/agent/_agent.py
index 8258fce80..32138a750 100644
--- a/src/agentscope/agent/_agent.py
+++ b/src/agentscope/agent/_agent.py
@@ -2,7 +2,6 @@
"""The unified agent class in AgentScope library."""
import asyncio
import inspect
-import uuid
from asyncio import Queue
from copy import deepcopy
@@ -21,7 +20,7 @@ from ._config import ContextConfig, ReActConfig, ModelConfig
from ..state import AgentState
from ._utils import _ToolCallBatch
from .._logging import logger
-from .._utils._common import _json_loads_with_repair
+from .._utils._common import _generate_id, _json_loads_with_repair
from ..event import (
AgentEvent,
ModelCallEndEvent,
@@ -579,7 +578,7 @@ class Agent:
else:
await self._handle_incoming_messages(msgs)
# Update the context with the incoming message and state
- self.state.reply_id = uuid.uuid4().hex
+ self.state.reply_id = _generate_id()
self.state.cur_iter = 0
yield ReplyStartEvent(
@@ -2434,7 +2433,7 @@ class Agent:
# If the current chunk has text blocks but no text block id,
# start with a start event
if not block_ids.get("text"):
- block_ids["text"] = uuid.uuid4().hex
+ block_ids["text"] = _generate_id()
yield TextBlockStartEvent(
reply_id=self.state.reply_id,
block_id=block_ids["text"],
@@ -2458,7 +2457,7 @@ class Agent:
if thinking_blocks:
# Generate a new thinking block id and start event
if not block_ids.get("thinking"):
- block_ids["thinking"] = uuid.uuid4().hex
+ block_ids["thinking"] = _generate_id()
yield ThinkingBlockStartEvent(
reply_id=self.state.reply_id,
block_id=block_ids["thinking"],
diff --git a/src/agentscope/app/_router/_session.py b/src/agentscope/app/_router/_session.py
index c7e4c4de5..3b72d790d 100644
--- a/src/agentscope/app/_router/_session.py
+++ b/src/agentscope/app/_router/_session.py
@@ -2,12 +2,12 @@
"""Session router — create, list, update, delete, stream, and get messages."""
import asyncio
import json
-import uuid
from typing import AsyncGenerator
from fastapi import APIRouter, Depends, HTTPException, Query, status
from fastapi.responses import StreamingResponse
+from ..._utils._common import _generate_id
from ..deps import (
get_current_user_id,
get_message_bus,
@@ -237,7 +237,7 @@ async def create_session(
user_id=user_id,
agent_id=body.agent_id,
config=SessionConfig(
- workspace_id=body.workspace_id or uuid.uuid4().hex,
+ workspace_id=body.workspace_id or _generate_id(),
chat_model_config=body.chat_model_config,
fallback_chat_model_config=body.fallback_chat_model_config,
tts_model_config=body.tts_model_config,
diff --git a/src/agentscope/app/storage/_model/_agent.py b/src/agentscope/app/storage/_model/_agent.py
index 709397631..6b1ed3bf9 100644
--- a/src/agentscope/app/storage/_model/_agent.py
+++ b/src/agentscope/app/storage/_model/_agent.py
@@ -1,10 +1,10 @@
# -*- coding: utf-8 -*-
"""The agent storage class."""
-import uuid
from typing import Literal
from pydantic import Field, BaseModel
+from ...._utils._common import _generate_id
from ._base import _RecordBase
from ....agent import ContextConfig, ReActConfig
@@ -14,7 +14,7 @@ class AgentData(BaseModel):
id: str = Field(
description="Unique agent id",
- default_factory=lambda: uuid.uuid4().hex,
+ default_factory=_generate_id,
)
"""The agent id."""
diff --git a/src/agentscope/app/storage/_model/_base.py b/src/agentscope/app/storage/_model/_base.py
index eb0cbd4a7..f9a5b761e 100644
--- a/src/agentscope/app/storage/_model/_base.py
+++ b/src/agentscope/app/storage/_model/_base.py
@@ -1,16 +1,17 @@
# -*- coding: utf-8 -*-
"""The base attributes used in storage."""
-import uuid
from datetime import datetime
from pydantic import BaseModel, Field
+from ...._utils._common import _generate_id
+
class _RecordBase(BaseModel):
"""The base class for all records."""
id: str = Field(
- default_factory=lambda: uuid.uuid4().hex,
+ default_factory=_generate_id,
description="Unique identifier for the credential.",
)
diff --git a/src/agentscope/app/storage/_model/_credential.py b/src/agentscope/app/storage/_model/_credential.py
index 42e97ee62..6462e6a76 100644
--- a/src/agentscope/app/storage/_model/_credential.py
+++ b/src/agentscope/app/storage/_model/_credential.py
@@ -1,9 +1,8 @@
# -*- coding: utf-8 -*-
"""The credential record."""
-import uuid
-
from pydantic import Field
+from ...._utils._common import _generate_id
from ._base import _RecordBase
@@ -11,7 +10,7 @@ class CredentialRecord(_RecordBase):
"""The credential model used for storing credentials."""
user_id: str = Field(
- default_factory=lambda: uuid.uuid4().hex,
+ default_factory=_generate_id,
)
data: dict
diff --git a/src/agentscope/credential/_base.py b/src/agentscope/credential/_base.py
index c8566acc8..906beab76 100644
--- a/src/agentscope/credential/_base.py
+++ b/src/agentscope/credential/_base.py
@@ -1,10 +1,11 @@
# -*- coding: utf-8 -*-
"""The credential base class."""
-import uuid
from typing import TYPE_CHECKING, Type
from pydantic import BaseModel, Field
+from .._utils._common import _generate_id
+
if TYPE_CHECKING:
from ..embedding import EmbeddingModelBase
from ..model import ChatModelBase, ModelCard
@@ -16,7 +17,7 @@ class CredentialBase(BaseModel):
"""The credential base class."""
id: str = Field(
- default_factory=lambda: uuid.uuid4().hex,
+ default_factory=_generate_id,
description="The credential id",
)
diff --git a/src/agentscope/event/_event.py b/src/agentscope/event/_event.py
index 922e3831a..ee52c97b6 100644
--- a/src/agentscope/event/_event.py
+++ b/src/agentscope/event/_event.py
@@ -1,12 +1,12 @@
# -*- coding: utf-8 -*-
"""Event types for agent execution."""
-import uuid
from datetime import datetime
from enum import StrEnum
from typing import Any, Dict, Literal, List, TypeAlias
from pydantic import BaseModel, Field, ConfigDict
+from .._utils._common import _generate_id
from ..message import (
DataBlock,
TextBlock,
@@ -65,7 +65,7 @@ class EventBase(BaseModel):
model_config = ConfigDict(use_enum_values=True)
- id: str = Field(default_factory=lambda: uuid.uuid4().hex)
+ id: str = Field(default_factory=_generate_id)
"""Unique event identifier."""
created_at: str = Field(default_factory=lambda: datetime.now().isoformat())
"""ISO 8601 timestamp of when the event was created."""
@@ -337,7 +337,7 @@ class ToolResultDataDeltaEvent(EventBase):
"""ID of the reply message this tool result belongs to."""
tool_call_id: str
"""ID of the corresponding tool call."""
- block_id: str = Field(default_factory=lambda: uuid.uuid4().hex)
+ block_id: str = Field(default_factory=_generate_id)
"""Unique identifier of the data block created by this event."""
media_type: str
"""MIME type of the binary content."""
diff --git a/src/agentscope/message/_base.py b/src/agentscope/message/_base.py
index 6dd2d08b1..1b5db757b 100644
--- a/src/agentscope/message/_base.py
+++ b/src/agentscope/message/_base.py
@@ -1,12 +1,12 @@
# -*- coding: utf-8 -*-
"""The message class in agentscope."""
import base64
-import uuid
from datetime import datetime
from typing import Literal, List, overload, Sequence, Self, TYPE_CHECKING, Any
from pydantic import BaseModel, Field, model_validator
+from .._utils._common import _generate_id
from ._block import (
TextBlock,
ThinkingBlock,
@@ -73,7 +73,7 @@ class Msg(BaseModel):
"""The message content as a list of content blocks."""
role: Literal["user", "assistant", "system"]
"""The role of the sender."""
- id: str = Field(default_factory=lambda: uuid.uuid4().hex)
+ id: str = Field(default_factory=_generate_id)
"""The message identifier."""
metadata: dict = Field(default_factory=dict)
"""The metadata of the message"""
@@ -504,7 +504,7 @@ def UserMsg(
metadata=metadata or {},
created_at=created_at,
finished_at=finished_at,
- id=id or uuid.uuid4().hex,
+ id=id or _generate_id(),
)
@@ -552,7 +552,7 @@ def AssistantMsg(
metadata=metadata or {},
created_at=created_at or datetime.now().isoformat(),
finished_at=finished_at,
- id=id or uuid.uuid4().hex,
+ id=id or _generate_id(),
usage=usage,
)
@@ -601,5 +601,5 @@ def SystemMsg(
metadata=metadata or {},
created_at=created_at,
finished_at=finished_at,
- id=id or uuid.uuid4().hex,
+ id=id or _generate_id(),
)
diff --git a/src/agentscope/message/_block.py b/src/agentscope/message/_block.py
index 5755c0bae..39b4cc57b 100644
--- a/src/agentscope/message/_block.py
+++ b/src/agentscope/message/_block.py
@@ -1,10 +1,10 @@
# -*- coding: utf-8 -*-
"""The content blocks of messages."""
-import uuid
from enum import StrEnum
from typing import Literal, List, TypeAlias
from pydantic import BaseModel, Field, AnyUrl, field_serializer, ConfigDict
+from .._utils._common import _generate_id
from ..permission import PermissionRule
@@ -15,7 +15,7 @@ class TextBlock(BaseModel):
"""The type of the text block, which is always 'text'."""
text: str
"""The text content of the block."""
- id: str = Field(default_factory=lambda: uuid.uuid4().hex)
+ id: str = Field(default_factory=_generate_id)
"""The unique identifier of the block."""
@@ -33,7 +33,7 @@ class ThinkingBlock(BaseModel):
"""The type of the thinking block, which is always 'thinking'."""
thinking: str
"""The thinking content of the block."""
- id: str = Field(default_factory=lambda: uuid.uuid4().hex)
+ id: str = Field(default_factory=_generate_id)
"""The unique identifier of the block."""
@@ -69,7 +69,7 @@ class DataBlock(BaseModel):
type: Literal["data"] = "data"
"""The type of the data block, which is always 'data'."""
- id: str = Field(default_factory=lambda: uuid.uuid4().hex)
+ id: str = Field(default_factory=_generate_id)
"""The unique identifier of the block."""
source: Base64Source | URLSource
"""The source of the data, which can be either a base64-encoded string or
@@ -93,7 +93,7 @@ class HintBlock(BaseModel):
hint: str | list[TextBlock | DataBlock]
"""The hint content — plain text or a list of content blocks for
multimodal data."""
- id: str = Field(default_factory=lambda: uuid.uuid4().hex)
+ id: str = Field(default_factory=_generate_id)
"""The unique identifier of the block."""
source: str | None = None
"""The sender or origin of this hint. For team messages this is the
diff --git a/src/agentscope/model/_dashscope/_model.py b/src/agentscope/model/_dashscope/_model.py
index 5de1941ad..b502b2e9b 100644
--- a/src/agentscope/model/_dashscope/_model.py
+++ b/src/agentscope/model/_dashscope/_model.py
@@ -2,7 +2,6 @@
"""The DashScope chat model class (OpenAI-compatible implementation)."""
import base64
import io
-import uuid
import warnings
import wave
from collections import OrderedDict
@@ -11,10 +10,11 @@ from typing import Any, AsyncGenerator, List, Literal, Type, TYPE_CHECKING
from pydantic import BaseModel, Field
+from ..._utils._audio import _build_streaming_wav_header
+from ..._utils._common import _generate_id
from .._base import ChatModelBase, _TOOL_CHOICE_LITERAL_MODES
from .._model_response import ChatResponse, StructuredResponse
from .._model_usage import ChatUsage
-from ..._utils._audio import _build_streaming_wav_header
from ...credential import DashScopeCredential
from ...formatter import FormatterBase, DashScopeChatFormatter
from ...message import (
@@ -349,7 +349,7 @@ class DashScopeChatModel(ChatModelBase):
audio_chunk = getattr(delta_audio, "data", "") or ""
if audio_chunk:
if audio_block_id is None:
- audio_block_id = uuid.uuid4().hex
+ audio_block_id = _generate_id()
pcm_bytes = base64.b64decode(audio_chunk)
acc_audio_data += pcm_bytes
if not audio_header_sent:
diff --git a/src/agentscope/model/_gemini/_model.py b/src/agentscope/model/_gemini/_model.py
index 0b491954e..0a1855e01 100644
--- a/src/agentscope/model/_gemini/_model.py
+++ b/src/agentscope/model/_gemini/_model.py
@@ -3,12 +3,12 @@
import base64
import copy
import json
-import uuid
from datetime import datetime
from typing import Literal, Any, AsyncGenerator, TYPE_CHECKING, List, Type
from pydantic import BaseModel, Field
+from ..._utils._common import _generate_id
from .._base import ChatModelBase, _TOOL_CHOICE_LITERAL_MODES
from .._model_response import ChatResponse
from .._model_usage import ChatUsage
@@ -386,7 +386,7 @@ class GeminiChatModel(ChatModelBase):
# Capture response_id from the first chunk that carries it
if response_id is None:
response_id = (
- getattr(chunk, "response_id", None) or uuid.uuid4().hex
+ getattr(chunk, "response_id", None) or _generate_id()
)
delta_content: list = []
@@ -419,7 +419,7 @@ class GeminiChatModel(ChatModelBase):
part.thought_signature,
).decode("utf-8")
else:
- call_id = part.function_call.id or uuid.uuid4().hex
+ call_id = part.function_call.id or _generate_id()
input_str = json.dumps(
keyword_args,
ensure_ascii=False,
@@ -457,7 +457,7 @@ class GeminiChatModel(ChatModelBase):
)
yield ChatResponse(
- id=response_id or uuid.uuid4().hex,
+ id=response_id or _generate_id(),
content=final_content,
is_last=True,
usage=usage,
@@ -503,7 +503,7 @@ class GeminiChatModel(ChatModelBase):
part.thought_signature,
).decode("utf-8")
else:
- call_id = part.function_call.id or uuid.uuid4().hex
+ call_id = part.function_call.id or _generate_id()
content_blocks.append(
ToolCallBlock(
id=call_id,
@@ -515,7 +515,7 @@ class GeminiChatModel(ChatModelBase):
usage = self._extract_usage(response.usage_metadata, start_datetime)
return ChatResponse(
- id=getattr(response, "response_id", None) or uuid.uuid4().hex,
+ id=getattr(response, "response_id", None) or _generate_id(),
content=content_blocks,
is_last=True,
usage=usage,
diff --git a/src/agentscope/model/_model_response.py b/src/agentscope/model/_model_response.py
index 569b8afe3..0d42d55b3 100644
--- a/src/agentscope/model/_model_response.py
+++ b/src/agentscope/model/_model_response.py
@@ -1,11 +1,11 @@
# -*- coding: utf-8 -*-
"""The model response module."""
-import uuid
from dataclasses import dataclass, field
from datetime import datetime
from typing import Literal, Sequence
from ._model_usage import ChatUsage
+from .._utils._common import _generate_id
from .._utils._mixin import DictMixin
from ..message import (
TextBlock,
@@ -28,7 +28,7 @@ class ChatResponse(DictMixin):
"""Whether this response is the last response, if `Ture`, the content will
be the complete response, otherwise the content is a partial response"""
- id: str = field(default_factory=lambda: uuid.uuid4().hex)
+ id: str = field(default_factory=_generate_id)
"""The unique identifier."""
created_at: str = field(default_factory=lambda: datetime.now().isoformat())
@@ -55,7 +55,7 @@ class StructuredResponse:
content: dict
"""The structured output of the model."""
- id: str = field(default_factory=lambda: uuid.uuid4().hex)
+ id: str = field(default_factory=_generate_id)
"""The unique identifier."""
created_at: str = field(default_factory=lambda: datetime.now().isoformat())
diff --git a/src/agentscope/model/_ollama/_model.py b/src/agentscope/model/_ollama/_model.py
index d507771dd..72987072b 100644
--- a/src/agentscope/model/_ollama/_model.py
+++ b/src/agentscope/model/_ollama/_model.py
@@ -1,12 +1,12 @@
# -*- coding: utf-8 -*-
"""The Ollama chat model implementation."""
import json
-import uuid
from datetime import datetime
from typing import Literal, Any, AsyncGenerator, TYPE_CHECKING, List, Type
from pydantic import BaseModel, Field
+from ..._utils._common import _generate_id
from .._base import ChatModelBase
from .._model_response import ChatResponse
from .._model_usage import ChatUsage
@@ -250,7 +250,7 @@ class OllamaChatModel(ChatModelBase):
# All delta should have the same block identifier.
# Ollama does not return a request id, so we generate one upfront
# to keep it stable.
- response_id = getattr(response, "id", None) or uuid.uuid4().hex
+ response_id = getattr(response, "id", None) or _generate_id()
acc_text = TextBlock(text="")
acc_thinking = ThinkingBlock(thinking="")
acc_tool_calls: dict = {}
@@ -367,7 +367,7 @@ class OllamaChatModel(ChatModelBase):
)
return ChatResponse(
- id=getattr(response, "id", None) or uuid.uuid4().hex,
+ id=getattr(response, "id", None) or _generate_id(),
content=content_blocks,
is_last=True,
usage=usage,
diff --git a/src/agentscope/model/_openai_chat/_model.py b/src/agentscope/model/_openai_chat/_model.py
index bb3864f88..c62c0f26f 100644
--- a/src/agentscope/model/_openai_chat/_model.py
+++ b/src/agentscope/model/_openai_chat/_model.py
@@ -3,7 +3,6 @@
import warnings
import base64
import io
-import uuid
import wave
from collections import OrderedDict
from datetime import datetime
@@ -11,10 +10,11 @@ from typing import Literal, Any, AsyncGenerator, TYPE_CHECKING, List, Type
from pydantic import BaseModel, Field
+from ..._utils._audio import _build_streaming_wav_header
+from ..._utils._common import _generate_id
from .._base import ChatModelBase, _TOOL_CHOICE_LITERAL_MODES
from .._model_response import ChatResponse, StructuredResponse
from .._model_usage import ChatUsage
-from ..._utils._audio import _build_streaming_wav_header
from ...credential import OpenAICredential
from ...formatter import FormatterBase, OpenAIChatFormatter
from ...message import (
@@ -385,7 +385,7 @@ class OpenAIChatModel(ChatModelBase):
)
if audio_chunk:
if audio_block_id is None:
- audio_block_id = uuid.uuid4().hex
+ audio_block_id = _generate_id()
pcm_bytes = base64.b64decode(audio_chunk)
acc_audio_data += pcm_bytes
if not audio_header_sent:
diff --git a/src/agentscope/state/_state.py b/src/agentscope/state/_state.py
index 54185ad09..6f08b2fff 100644
--- a/src/agentscope/state/_state.py
+++ b/src/agentscope/state/_state.py
@@ -1,12 +1,12 @@
# -*- coding: utf-8 -*-
"""The agent state class."""
-import uuid
from typing import Any
from pydantic import BaseModel, Field
import aiofiles.os
+from .._utils._common import _generate_id
from ._task import Task
from ..message import TextBlock, DataBlock, Msg
from ..permission import PermissionContext
@@ -141,7 +141,7 @@ class TaskContext(BaseModel):
class AgentState(BaseModel):
"""The agent state that should be saved and loaded from storage."""
- session_id: str = Field(default_factory=lambda: uuid.uuid4().hex)
+ session_id: str = Field(default_factory=_generate_id)
"""The session id of the agent. Normally, each session will maintain one
independent agent state for each agent."""
@@ -150,7 +150,7 @@ class AgentState(BaseModel):
context when feed into the LLM."""
context: list[Msg] = Field(default_factory=list)
"""The uncompressed conversation context, that will be feed into the LLM"""
- reply_id: str = Field(default_factory=lambda: uuid.uuid4().hex)
+ reply_id: str = Field(default_factory=_generate_id)
"""The id of the current reply, which is also used as the id of the
final message of the reply."""
cur_iter: int = 0
diff --git a/src/agentscope/state/_task.py b/src/agentscope/state/_task.py
index d07eb03c9..ae594f1f3 100644
--- a/src/agentscope/state/_task.py
+++ b/src/agentscope/state/_task.py
@@ -1,11 +1,12 @@
# -*- coding: utf-8 -*-
"""The task class."""
-import uuid
from datetime import datetime
from typing import Any, Literal
from pydantic import BaseModel, Field
+from .._utils._common import _generate_id
+
class Task(BaseModel):
"""The agent task."""
@@ -25,7 +26,7 @@ class Task(BaseModel):
state: Literal["pending", "in_progress", "completed"] = "pending"
"""The task state."""
- id: str = Field(default_factory=lambda: uuid.uuid4().hex)
+ id: str = Field(default_factory=_generate_id)
"""The task identifier."""
owner: str | None = None
diff --git a/src/agentscope/tool/_response.py b/src/agentscope/tool/_response.py
index 786f8833d..946466999 100644
--- a/src/agentscope/tool/_response.py
+++ b/src/agentscope/tool/_response.py
@@ -1,10 +1,10 @@
# -*- coding: utf-8 -*-
"""The tool response class."""
-import uuid
from typing import List, Literal, Self
from pydantic import BaseModel, Field
+from .._utils._common import _generate_id
from ..message import DataBlock, TextBlock, Base64Source, ToolResultState
@@ -26,7 +26,7 @@ class ToolChunk(BaseModel):
"""The metadata to be accessed within the agent, so that we don't need to
parse the tool result block."""
- id: str = Field(default_factory=lambda: uuid.uuid4().hex)
+ id: str = Field(default_factory=_generate_id)
"""The identity of the tool response."""
@@ -49,7 +49,7 @@ class ToolResponse(BaseModel):
"""The metadata to be accessed within the agent, so that we don't need to
parse the tool result block."""
- id: str = Field(default_factory=lambda: uuid.uuid4().hex)
+ id: str = Field(default_factory=_generate_id)
"""The identity of the tool response."""
def append_chunk(self, chunk: ToolChunk) -> Self:
@@ -100,7 +100,7 @@ class ToolResponse(BaseModel):
# For different block types with the same ID, we just
# append the new block with a new ID to avoid the conflict
new_chunk_block = chunk_block.model_copy(deep=True)
- new_chunk_block.id = uuid.uuid4().hex
+ new_chunk_block.id = _generate_id()
self.content.append(new_chunk_block)
else:
diff --git a/src/agentscope/workspace/_base.py b/src/agentscope/workspace/_base.py
index 1c529bf8b..828197a33 100644
--- a/src/agentscope/workspace/_base.py
+++ b/src/agentscope/workspace/_base.py
@@ -23,10 +23,10 @@ Consumers:
- **Developer** — manages lifecycle via ``initialize`` / ``close``.
"""
-import uuid
from abc import abstractmethod
from typing import Self
+from .._utils._common import _generate_id
from ..mcp import MCPClient
from ..message import Msg, ToolResultBlock
from ..skill import Skill
@@ -60,7 +60,7 @@ class WorkspaceBase:
def __init__(self, workspace_id: str | None) -> None:
"""Initialize the workspace base instance."""
- self.workspace_id = workspace_id or uuid.uuid4().hex
+ self.workspace_id = workspace_id or _generate_id()
self.is_alive = False
# ── lifecycle (developer) ──────────────────────────────────────
diff --git a/tests/id_factory_test.py b/tests/id_factory_test.py
new file mode 100644
index 000000000..b3f58462d
--- /dev/null
+++ b/tests/id_factory_test.py
@@ -0,0 +1,49 @@
+# -*- coding: utf-8 -*-
+"""Tests for the configurable ID factory."""
+import re
+from unittest.async_case import IsolatedAsyncioTestCase
+
+from agentscope import set_id_factory
+from agentscope.message import Msg, TextBlock
+
+_HEX32_RE = re.compile(r"^[0-9a-f]{32}$")
+
+
+class IdFactoryTest(IsolatedAsyncioTestCase):
+ """Tests for set_id_factory."""
+
+ async def asyncSetUp(self) -> None:
+ """Save the current factory before each test."""
+ import agentscope._utils._common as common
+
+ # pylint: disable=protected-access
+ self._saved_factory = common._id_factory
+
+ async def test_default_id_factory_returns_hex32(self) -> None:
+ """The default ID factory returns uuid.uuid4().hex."""
+ msg = Msg(
+ name="test",
+ content=[TextBlock(text="hello")],
+ role="user",
+ )
+ self.assertRegex(msg.id, _HEX32_RE)
+ self.assertRegex(msg.content[0].id, _HEX32_RE)
+
+ async def test_custom_factory_affects_entities(self) -> None:
+ """After ``set_id_factory``, entities use the custom factory."""
+ set_id_factory(lambda: "custom-entity-id")
+
+ msg = Msg(
+ name="test",
+ content=[TextBlock(text="hello")],
+ role="user",
+ )
+ self.assertEqual(msg.id, "custom-entity-id")
+ self.assertEqual(msg.content[0].id, "custom-entity-id")
+
+ async def asyncTearDown(self) -> None:
+ """Restore the original factory after each test."""
+ import agentscope._utils._common as common
+
+ # pylint: disable=protected-access
+ common._id_factory = self._saved_factory