mirror of
https://github.com/agentscope-ai/ReMe.git
synced 2026-11-27 23:58:47 +00:00
Some checks failed
CI and Release / Docker / Build and test / amd64 (push) Has been cancelled
CI and Release / Docker / Build and test / arm64 (push) Has been cancelled
Security / CodeQL / Analyze python (push) Has been cancelled
CI / Python quality / Pre-commit (push) Has been cancelled
CI / Python tests / Unit Tests - py3.12 (push) Has been cancelled
CI / Python tests / Unit Tests - py3.13 (push) Has been cancelled
CI / Python tests / Unit Tests - py3.14 (push) Has been cancelled
CI / Python packages / Build and verify distributions (push) Has been cancelled
CI / Python quality / GitHub Actions (push) Has been cancelled
CI / Python tests / Hermes embedded - ubuntu-latest (push) Has been cancelled
CI / Python tests / Hermes embedded - windows-latest (push) Has been cancelled
CI / Python tests / Unit Tests - py3.11 (push) Has been cancelled
CI / ReMe Studio / Studio checks (push) Has been cancelled
Deploy / Documentation / Build documentation (push) Has been cancelled
CI / Windows / CLI smoke - py3.11 (push) Has been cancelled
Security / CodeQL / Analyze javascript-typescript (push) Has been cancelled
CI and Release / Docker / Publish multi-platform tags (push) Has been cancelled
Deploy / Documentation / deploy (push) Has been cancelled
* refactor(core): reorganize the ReMe runtime and shared helpers * test(status): import the base component from its canonical module * test: remove redundant unit checks * refactor(core): use canonical runtime imports and shared CLI discovery Restore evolve behavior to the base branch and update its imports. Use Application as the runtime entry point and encode SSE in the HTTP service. * fix(cli): honor caller config when service replay is incomplete Use partial startup overrides for port probes and resolve named configs before requesting the service process working directory.
105 lines
4.1 KiB
Python
105 lines
4.1 KiB
Python
"""Shared lifecycle for lazy AgentScope chat providers."""
|
|
|
|
import asyncio
|
|
|
|
from agentscope.credential import CredentialBase
|
|
from agentscope.model import ChatModelBase
|
|
|
|
from ..base import BaseComponent
|
|
from ...enumeration import ComponentEnum
|
|
|
|
|
|
class BaseAsLLM(BaseComponent):
|
|
"""Base wrapper for AgentScope chat models.
|
|
|
|
Subclasses set ``credential_cls``. Providers are constructed on first use,
|
|
allowing local file and search jobs to run without model credentials.
|
|
"""
|
|
|
|
component_type = ComponentEnum.AS_LLM
|
|
credential_cls: type[CredentialBase]
|
|
_protect_owned_model_lifecycle = False
|
|
|
|
def __init__(self, **kwargs) -> None:
|
|
super().__init__(**kwargs)
|
|
self._model: ChatModelBase | None = None
|
|
self._owns_model = False
|
|
self._closed = False
|
|
self._closing_depth = 0
|
|
self._lifecycle_gate = asyncio.Lock()
|
|
|
|
async def start(self) -> None:
|
|
"""Start without cleaning up resources owned by another lifecycle call."""
|
|
async with self._lifecycle_gate:
|
|
await super().start()
|
|
if not self._closing_depth:
|
|
self._closed = False
|
|
|
|
async def _rollback_start(
|
|
self,
|
|
start_hook_entered: bool,
|
|
started_owned: list[BaseComponent],
|
|
) -> None:
|
|
"""Fence lazy model access during every startup rollback path."""
|
|
# BaseComponent.start() holds the lifecycle lock, but the synchronous
|
|
# model getter does not. Both dependency and hook failures can yield
|
|
# while releasing an owned client, so temporarily forbid construction.
|
|
self._closing_depth += 1
|
|
self._closed = True
|
|
try:
|
|
await super()._rollback_start(start_hook_entered, started_owned)
|
|
if not start_hook_entered and self._owns_model and self._model is not None:
|
|
try:
|
|
await self._close()
|
|
except BaseException:
|
|
self.logger.exception("Failed to clean up model after startup failure")
|
|
finally:
|
|
self._closing_depth -= 1
|
|
if not self._closing_depth:
|
|
# A failed start is retryable, unless another close is pending.
|
|
self._closed = False
|
|
|
|
async def close(self) -> None:
|
|
"""Prevent lazy construction throughout started or pre-start shutdown."""
|
|
self._closing_depth += 1
|
|
self._closed = True
|
|
try:
|
|
async with self._lifecycle_gate:
|
|
async with self._lock:
|
|
if not self._is_started:
|
|
await self._close()
|
|
return
|
|
await super().close()
|
|
finally:
|
|
self._closing_depth -= 1
|
|
self._closed = self._closing_depth > 0 or not self._is_started
|
|
|
|
async def _start(self) -> None:
|
|
"""Keep service startup independent of provider credentials."""
|
|
|
|
@property
|
|
def model(self) -> ChatModelBase:
|
|
"""Initialize on first access, including direct Step dependency resolution."""
|
|
self.initialize_model()
|
|
assert self._model is not None
|
|
return self._model
|
|
|
|
@model.setter
|
|
def model(self, value: ChatModelBase | None) -> None:
|
|
"""Preserve explicit model injection used by standalone consumers."""
|
|
self._model = value
|
|
self._owns_model = False
|
|
|
|
def initialize_model(self) -> None:
|
|
"""Construct the configured provider once, without making a remote request."""
|
|
if self._protect_owned_model_lifecycle and self._closed and (self._owns_model or self._model is None):
|
|
raise RuntimeError("Start the LLM component before accessing its model after close.")
|
|
if self._model is not None:
|
|
return
|
|
kwargs = dict(self.kwargs)
|
|
credential = self.credential_cls(**kwargs.pop("credential", {}))
|
|
model_cls = credential.get_chat_model_class()
|
|
params_dict = kwargs.pop("parameters", None)
|
|
parameters = model_cls.Parameters(**params_dict) if params_dict else None
|
|
self._model = model_cls(credential=credential, parameters=parameters, **kwargs)
|
|
self._owns_model = True
|