跳转至内容

SDK 与配置

可嵌入 SDK 位于 dashscope_agenticx.sdk — 在 Agent 运行时之上提供 稳定、带类型的接口,供脚本、CI 流水线、IDE 插件及其他 Python 程序 使用。面向任务的演练参见嵌入式 SDK;配置文件与 环境变量参见配置。

from dashscope_agenticx.sdk import run_once_sync

print(run_once_sync("Summarize README.md"))

导入路径

请从 dashscope_agenticx.sdk 导入。顶层包重新导出了最常用的辅助 函数,但 sdk 模块才是文档化的完整接口。

配置解析

Config.load() 按优先级从低到高合并三层:

  1. 全局配置:~/.config/AgenticX/config.toml
  2. 工作区配置:./.agenticx/config.toml
  3. 环境变量填补剩余空缺(DASHSCOPE_API_KEY、 ANTHROPIC_API_KEY、OPENAI_API_KEY、AGENTICX_WORKSPACE、 AGENTICX_REGION、AGENTICX_MAAS_API_KEY、…)

AGENTICX_PROVIDER、AGENTICX_MODEL、AGENTICX_OPENAI_BASE_URL 与 AGENTICX_MCP_SERVERS 强制覆盖解析结果。SDK 中的 load_config() 仅在解析后的配置仍有空缺时应用调用方提供的参数。

Config.api_key 是一个属性,根据 Config.provider 路由到对应 Provider 的密钥字段(tongyi_api_key、anthropic_api_key、 openai_api_key)。

SDK 入口

sdk

Lightweight programmatic SDK for embedding agenticx in other applications.

This module exposes a stable, typed API surface on top of the lower-level Agent, Executor, and ProviderChain internals. It is intended for scripts, CI pipelines, IDE plugins, and other Python programs that want to reuse agenticx's agent stack without invoking the full interactive CLI.

Example::

import asyncio
from dashscope_agenticx.sdk import run_once

result = asyncio.run(run_once("Summarize README.md"))
print(result)

load_config

load_config(
    provider: Optional[str] = None,
    model: Optional[str] = None,
    api_key: Optional[str] = None,
    base_url: Optional[str] = None,
) -> Config

Load agenticx configuration with caller-supplied overrides.

Workspace/global config and environment variables still take their normal priority; explicit arguments only fill in missing defaults.

Source code in src/dashscope_agenticx/sdk.py
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
def load_config(
    provider: Optional[str] = None,
    model: Optional[str] = None,
    api_key: Optional[str] = None,
    base_url: Optional[str] = None,
) -> Config:
    """Load agenticx configuration with caller-supplied overrides.

    Workspace/global config and environment variables still take their normal
    priority; explicit arguments only fill in missing defaults.
    """
    config = Config.load(
        default_provider=provider or "tongyi",
        default_model=model or DEFAULT_MODEL,
    )
    if api_key and not config.api_key:
        config.api_key = api_key
    if base_url and not config.base_url:
        config.base_url = base_url
    return config

create_agent

create_agent(
    config: Optional[Config] = None,
    system_prompt: Optional[str] = None,
    session_id: Optional[str] = None,
    *,
    oneshot: bool = False
) -> Agent

Create an Agent instance ready for programmatic use.

Parameters:

Name Type Description Default
config Optional[Config]

agenticx configuration. If None, loads default config.

None
system_prompt Optional[str]

Optional system prompt override.

None
session_id Optional[str]

Optional safe topic identifier. If provided, conversation history is persisted under .agenticx/session/<id>/history.json.

None
oneshot bool

Enable autonomous one-shot guards and acceptance behavior.

False
Source code in src/dashscope_agenticx/sdk.py
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
def create_agent(
    config: Optional[Config] = None,
    system_prompt: Optional[str] = None,
    session_id: Optional[str] = None,
    *,
    oneshot: bool = False,
) -> Agent:
    """Create an ``Agent`` instance ready for programmatic use.

    Args:
        config: agenticx configuration.  If None, loads default config.
        system_prompt: Optional system prompt override.
        session_id: Optional safe topic identifier. If provided, conversation
            history is persisted under
            ``.agenticx/session/<id>/history.json``.
        oneshot: Enable autonomous one-shot guards and acceptance behavior.
    """
    _ensure_tools_imported()
    config = config or load_config()

    from dashscope_agenticx.cli import (
        _compose_system_prompt,
        _load_system_prompt,
    )
    from dashscope_agenticx.runtime import (  # pylint: disable=reimported
        RuntimeBuilder as _RuntimeBuilder,
    )

    resolved_prompt = _compose_system_prompt(
        system_prompt or _load_system_prompt(),
    )
    runtime = _RuntimeBuilder(config).build()
    return runtime.create_agent(
        system_prompt=resolved_prompt,
        session_id=session_id,
        oneshot=oneshot,
    )

run_events async

run_events(
    prompt: str,
    config: Optional[Config] = None,
    system_prompt: Optional[str] = None,
    session_id: Optional[str] = None,
) -> AsyncIterator[AgentEvent]

Run one turn as typed events for TUI, Client, IDE, or automation.

Source code in src/dashscope_agenticx/sdk.py
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
async def run_events(
    prompt: str,
    config: Optional[Config] = None,
    system_prompt: Optional[str] = None,
    session_id: Optional[str] = None,
) -> AsyncIterator[AgentEvent]:
    """Run one turn as typed events for TUI, Client, IDE, or automation."""
    agent = create_agent(
        config=config,
        system_prompt=system_prompt,
        session_id=session_id,
    )
    try:
        async with contextlib.aclosing(agent.run_events(prompt)) as events:
            async for event in events:
                yield event
    finally:
        if isinstance(getattr(agent, "runtime", None), Runtime):
            await agent.aclose()

run_stream async

run_stream(
    prompt: str,
    config: Optional[Config] = None,
    system_prompt: Optional[str] = None,
    session_id: Optional[str] = None,
) -> AsyncIterator[str]

Stream the agent's response for prompt as an async iterator.

Source code in src/dashscope_agenticx/sdk.py
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
async def run_stream(
    prompt: str,
    config: Optional[Config] = None,
    system_prompt: Optional[str] = None,
    session_id: Optional[str] = None,
) -> AsyncIterator[str]:
    """Stream the agent's response for ``prompt`` as an async iterator."""
    agent = create_agent(
        config=config,
        system_prompt=system_prompt,
        session_id=session_id,
    )
    try:
        async with contextlib.aclosing(agent.run_stream(prompt)) as chunks:
            async for chunk in chunks:
                yield chunk
    finally:
        if isinstance(getattr(agent, "runtime", None), Runtime):
            await agent.aclose()

run_once async

run_once(
    prompt: str,
    config: Optional[Config] = None,
    system_prompt: Optional[str] = None,
    session_id: Optional[str] = None,
) -> str

Run one non-interactive turn and return the full response text.

This is the easiest entry point for scripts and CI: it streams the full agent turn, executes any tool calls, and returns the final assistant text.

Source code in src/dashscope_agenticx/sdk.py
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
async def run_once(
    prompt: str,
    config: Optional[Config] = None,
    system_prompt: Optional[str] = None,
    session_id: Optional[str] = None,
) -> str:
    """Run one non-interactive turn and return the full response text.

    This is the easiest entry point for scripts and CI: it streams the full
    agent turn, executes any tool calls, and returns the final assistant text.
    """
    agent = create_agent(
        config=config,
        system_prompt=system_prompt,
        session_id=session_id,
        oneshot=True,
    )
    parts: list[str] = []
    try:
        async with contextlib.aclosing(agent.run_stream(prompt)) as chunks:
            async for chunk in chunks:
                parts.append(chunk)
    finally:
        if isinstance(getattr(agent, "runtime", None), Runtime):
            await agent.aclose()
    return "".join(parts)

run_once_sync

run_once_sync(
    prompt: str,
    config: Optional[Config] = None,
    system_prompt: Optional[str] = None,
    session_id: Optional[str] = None,
) -> str

Synchronous wrapper around :func:run_once.

Source code in src/dashscope_agenticx/sdk.py
173
174
175
176
177
178
179
180
def run_once_sync(
    prompt: str,
    config: Optional[Config] = None,
    system_prompt: Optional[str] = None,
    session_id: Optional[str] = None,
) -> str:
    """Synchronous wrapper around :func:`run_once`."""
    return asyncio.run(run_once(prompt, config, system_prompt, session_id))

run_interactive

run_interactive(
    system_prompt: Optional[str] = None,
    app_name: str = "Agent",
    default_model: str = DEFAULT_MODEL,
    default_provider: str = "tongyi",
    api_key: Optional[str] = None,
    base_url: Optional[str] = None,
    command: Optional[str] = None,
    prompt_symbol: str = "You> ",
    sdk_index: Optional[list[str]] = None,
    tui: Optional[bool] = None,
    module: str = "",
    guide_url: str = "",
) -> None

Run the full agenticx interactive loop with a custom identity.

This is a thin SDK wrapper around the existing embedded mode; see dashscope_agenticx.ui.embedded.run for details.

Source code in src/dashscope_agenticx/sdk.py
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
def run_interactive(
    system_prompt: Optional[str] = None,
    app_name: str = "Agent",
    default_model: str = DEFAULT_MODEL,
    default_provider: str = "tongyi",
    api_key: Optional[str] = None,
    base_url: Optional[str] = None,
    command: Optional[str] = None,
    prompt_symbol: str = "You> ",
    sdk_index: Optional[list[str]] = None,
    tui: Optional[bool] = None,
    module: str = "",
    guide_url: str = "",
) -> None:
    """Run the full agenticx interactive loop with a custom identity.

    This is a thin SDK wrapper around the existing embedded mode; see
    ``dashscope_agenticx.ui.embedded.run`` for details.
    """
    from dashscope_agenticx.ui.embedded import run as _embedded_run

    _embedded_run(
        system_prompt=system_prompt,
        app_name=app_name,
        default_model=default_model,
        default_provider=default_provider,
        api_key=api_key,
        base_url=base_url,
        command=command,
        prompt_symbol=prompt_symbol,
        sdk_index=sdk_index,
        tui=tui,
        module=module,
        guide_url=guide_url,
    )

配置(Config)

Config dataclass

Config(
    provider: str = "tongyi",
    model: str = DEFAULT_MODEL,
    thinking_provider: str = "",
    thinking_model: str = "",
    loop_mode: str = "auto",
    tongyi_api_key: str = "",
    anthropic_api_key: str = "",
    openai_api_key: str = "",
    base_url: str = "",
    workspace: str = "",
    region: str = "",
    maas_api_key: str = "",
    auto_approve: bool = False,
    confirm_mode: str = "all",
    max_turns: int = 50,
    timeout: int = 30,
    mcp_servers: list[MCPServerConfig] = list(),
    memory_enabled: bool = True,
    memory_user_id: str = "",
    memory_library_id: str = "",
    platform: str = "bailian",
    user_name: str = "",
    enabled_capabilities: list[str] | None = None,
    custom_models: list[str] = list(),
    user_directives: list[str] = list(),
    session_persist: bool = True,
    asr_model: str = "paraformer-realtime-v2",
    voice_silence_duration: float = 2.0,
    voice_max_seconds: int = 60,
    voice_silence_threshold: int = 500,
    tts_enabled: bool = False,
    tts_model: str = "cosyvoice-v2",
    tts_voice: str = "longxiaochun_v2",
    tts_speed: float = 1.0,
    subagents: dict[str, SubagentConfig] = dict(),
    delegation: DelegationConfig = DelegationConfig(),
    theme: dict[str, str] = (
        lambda: {
            "background": "#ffffff",
            "text": "#1e1e1e",
            "border": "ansi_blue",
            "border_style": "solid",
            "accent": "#007acc",
            "muted": "#595959",
            "panel_border": "blue",
        }
    )(),
    protocol: str = "openai",
    tui: bool = True,
    tui_mouse: bool = True,
    privacy_mode: bool = False,
    debug: bool = False,
    sandbox: bool = False,
    skill_registry: str = "",
    fallback_providers: list[str] = list(),
    expert_repo: str = "",
    expert_branch: str = "main",
)

provider class-attribute instance-attribute

provider: str = 'tongyi'

model class-attribute instance-attribute

model: str = DEFAULT_MODEL

thinking_provider class-attribute instance-attribute

thinking_provider: str = ''

thinking_model class-attribute instance-attribute

thinking_model: str = ''

loop_mode class-attribute instance-attribute

loop_mode: str = 'auto'

tongyi_api_key class-attribute instance-attribute

tongyi_api_key: str = ''

anthropic_api_key class-attribute instance-attribute

anthropic_api_key: str = ''

openai_api_key class-attribute instance-attribute

openai_api_key: str = ''

base_url class-attribute instance-attribute

base_url: str = ''

workspace class-attribute instance-attribute

workspace: str = ''

region class-attribute instance-attribute

region: str = ''

maas_api_key class-attribute instance-attribute

maas_api_key: str = ''

auto_approve class-attribute instance-attribute

auto_approve: bool = False

confirm_mode class-attribute instance-attribute

confirm_mode: str = 'all'

max_turns class-attribute instance-attribute

max_turns: int = 50

timeout class-attribute instance-attribute

timeout: int = 30

mcp_servers class-attribute instance-attribute

mcp_servers: list[MCPServerConfig] = field(
    default_factory=list
)

memory_enabled class-attribute instance-attribute

memory_enabled: bool = True

memory_user_id class-attribute instance-attribute

memory_user_id: str = ''

memory_library_id class-attribute instance-attribute

memory_library_id: str = ''

platform class-attribute instance-attribute

platform: str = 'bailian'

user_name class-attribute instance-attribute

user_name: str = ''

enabled_capabilities class-attribute instance-attribute

enabled_capabilities: list[str] | None = None

custom_models class-attribute instance-attribute

custom_models: list[str] = field(default_factory=list)

user_directives class-attribute instance-attribute

user_directives: list[str] = field(default_factory=list)

session_persist class-attribute instance-attribute

session_persist: bool = True

asr_model class-attribute instance-attribute

asr_model: str = 'paraformer-realtime-v2'

voice_silence_duration class-attribute instance-attribute

voice_silence_duration: float = 2.0

voice_max_seconds class-attribute instance-attribute

voice_max_seconds: int = 60

voice_silence_threshold class-attribute instance-attribute

voice_silence_threshold: int = 500

tts_enabled class-attribute instance-attribute

tts_enabled: bool = False

tts_model class-attribute instance-attribute

tts_model: str = 'cosyvoice-v2'

tts_voice class-attribute instance-attribute

tts_voice: str = 'longxiaochun_v2'

tts_speed class-attribute instance-attribute

tts_speed: float = 1.0

subagents class-attribute instance-attribute

subagents: dict[str, SubagentConfig] = field(
    default_factory=dict
)

delegation class-attribute instance-attribute

delegation: DelegationConfig = field(
    default_factory=DelegationConfig
)

theme class-attribute instance-attribute

theme: dict[str, str] = field(
    default_factory=lambda: {
        "background": "#ffffff",
        "text": "#1e1e1e",
        "border": "ansi_blue",
        "border_style": "solid",
        "accent": "#007acc",
        "muted": "#595959",
        "panel_border": "blue",
    }
)

protocol class-attribute instance-attribute

protocol: str = 'openai'

tui class-attribute instance-attribute

tui: bool = True

tui_mouse class-attribute instance-attribute

tui_mouse: bool = True

privacy_mode class-attribute instance-attribute

privacy_mode: bool = False

debug class-attribute instance-attribute

debug: bool = False

sandbox class-attribute instance-attribute

sandbox: bool = False

skill_registry class-attribute instance-attribute

skill_registry: str = ''

fallback_providers class-attribute instance-attribute

fallback_providers: list[str] = field(default_factory=list)

expert_repo class-attribute instance-attribute

expert_repo: str = ''

expert_branch class-attribute instance-attribute

expert_branch: str = 'main'

api_key property writable

api_key: str

Return the API key for the currently selected provider.

load classmethod

load(
    default_provider: str = "tongyi",
    default_model: str = DEFAULT_MODEL,
) -> Config
Source code in src/dashscope_agenticx/config.py
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
@classmethod
def load(
    cls,
    default_provider: str = "tongyi",
    default_model: str = DEFAULT_MODEL,
) -> Config:
    migrate_legacy_directories()
    config = cls()
    # Caller's defaults become the initial values; config files and env
    # vars override them during the loading process below.
    config.provider = default_provider
    config.model = default_model

    # Load global config first (provider + api_key)
    if CONFIG_FILE.exists():
        config._load_global()

    # Load workspace config (project settings)
    workspace_loaded = False
    if WORKSPACE_CONFIG_FILE.exists():
        config._load_workspace()
        workspace_loaded = True
    elif CONFIG_FILE.exists():
        # Fallback: read workspace-level fields from global config
        # (migration)
        config._load_workspace_from(CONFIG_FILE)
        workspace_loaded = True

    # Environment variables fill in MISSING API keys (saved config takes
    # priority).
    if not config.tongyi_api_key:
        if key := os.environ.get("DASHSCOPE_API_KEY"):
            config.tongyi_api_key = key
    if not config.anthropic_api_key:
        if key := os.environ.get("ANTHROPIC_API_KEY"):
            config.anthropic_api_key = key
    if not config.openai_api_key:
        if key := os.environ.get("OPENAI_API_KEY"):
            config.openai_api_key = key
    if not config.workspace:
        if ws := os.environ.get("AGENTICX_WORKSPACE"):
            config.workspace = ws
    if not config.region:
        if region := os.environ.get("AGENTICX_REGION"):
            config.region = region
    if not config.maas_api_key:
        if key := os.environ.get("AGENTICX_MAAS_API_KEY"):
            config.maas_api_key = key

    # First-run provider auto-selection: if there is no saved workspace
    # config, pick a provider based on whichever API key env var is
    # present. Once the user has saved workspace config (e.g. via
    # /provider), that choice wins.
    if not workspace_loaded:
        if os.environ.get("DASHSCOPE_API_KEY"):
            config.provider = "tongyi"
        elif os.environ.get("ANTHROPIC_API_KEY"):
            config.provider = "anthropic"
            config.model = "claude-sonnet-4-20250514"
        elif os.environ.get("OPENAI_API_KEY"):
            config.provider = "openai"
            config.model = "gpt-4o"

    # AGENTICX_PROVIDER / AGENTICX_MODEL always override because they
    # express explicit user intent.
    if base_url := os.environ.get("OPENAI_BASE_URL"):
        config.base_url = base_url
    if model := os.environ.get("AGENTICX_MODEL"):
        config.model = model
    if provider := os.environ.get("AGENTICX_PROVIDER"):
        config.provider = provider
    if mcp_env := os.environ.get("AGENTICX_MCP_SERVERS"):
        for svc in mcp_env.split(","):
            svc = svc.strip()
            if svc:
                config.mcp_servers.append(MCPServerConfig(service=svc))
    if user_id := os.environ.get("AGENTICX_MEMORY_USER_ID"):
        config.memory_user_id = user_id
    if lib_id := os.environ.get("AGENTICX_MEMORY_LIBRARY_ID"):
        config.memory_library_id = lib_id
    if os.environ.get("AGENTICX_MEMORY_DISABLED"):
        config.memory_enabled = False

    if config.provider == "dashscope":
        config.provider = "tongyi"

    # Validate: if the loaded model doesn't belong to the current provider,
    # fall back to the provider's first model. This handles the case where
    # a workspace config saves model = "qwen3.7-max" (tongyi) but the
    # provider later switches to anthropic, leaving a stale model name.
    # Skip validation when a custom backend path is set: the user is
    # responsible for the model name on their own endpoint.
    if not config.base_url:
        valid_models = _valid_models_for_provider(
            config.provider,
            config.custom_models,
        )
        if valid_models and config.model not in set(valid_models):
            config.model = valid_models[0]

    # Preserve legacy session/history layouts without clobbering new data.
    default_session = WORKSPACE_DIR / "session" / "default"
    for old, new in (
        (WORKSPACE_DIR / "session.json", default_session / "history.json"),
        (
            WORKSPACE_DIR / "session" / "history.json",
            default_session / "history.json",
        ),
        (WORKSPACE_DIR / "history", default_session / "input-history.txt"),
        (
            WORKSPACE_DIR / "session" / "input-history",
            default_session / "input-history.txt",
        ),
    ):
        _move_noclobber(old, new)

    return config

save

save()
Source code in src/dashscope_agenticx/config.py
934
935
936
937
938
939
940
941
942
943
944
945
946
def save(self):
    if CONFIG_FILE == WORKSPACE_CONFIG_FILE:
        # cwd == ~: both scopes share one file; write keys + settings
        # together
        CONFIG_DIR.mkdir(parents=True, exist_ok=True)
        atomic_write_text(
            CONFIG_FILE,
            "\n".join(self._global_lines() + self._workspace_lines())
            + "\n",
        )
        return
    self.save_global()
    self.save_workspace()

save_global

save_global()
Source code in src/dashscope_agenticx/config.py
948
949
950
def save_global(self):
    CONFIG_DIR.mkdir(parents=True, exist_ok=True)
    atomic_write_text(CONFIG_FILE, "\n".join(self._global_lines()) + "\n")

save_workspace

save_workspace()
Source code in src/dashscope_agenticx/config.py
 997
 998
 999
1000
1001
1002
def save_workspace(self):
    WORKSPACE_DIR.mkdir(parents=True, exist_ok=True)
    atomic_write_text(
        WORKSPACE_CONFIG_FILE,
        "\n".join(self._workspace_lines()) + "\n",
    )

关键默认值:max_turns=50、timeout=30(每次模型请求的秒数)、 platform="bailian"、memory_enabled=True、session_persist=True。

嵌套配置类型

MCPServerConfig dataclass

MCPServerConfig(
    service: str,
    url: str = "",
    transport: str = "sse",
    command: str = "",
    args: list[str] = list(),
)

service instance-attribute

service: str

url class-attribute instance-attribute

url: str = ''

transport class-attribute instance-attribute

transport: str = 'sse'

command class-attribute instance-attribute

command: str = ''

args class-attribute instance-attribute

args: list[str] = field(default_factory=list)

SubagentConfig dataclass

SubagentConfig(
    model: str = "",
    temperature: float = 0.0,
    max_turns: int = 0,
)

Per-subagent overrides. Only max_turns is applied.

model and temperature are accepted, validated and persisted by /subagents config, but a subagent shares the parent's provider, whose model and sampling parameters are fixed when it is constructed. Nothing reads them.

model class-attribute instance-attribute

model: str = ''

temperature class-attribute instance-attribute

temperature: float = 0.0

max_turns class-attribute instance-attribute

max_turns: int = 0

to_dict

to_dict() -> dict
Source code in src/dashscope_agenticx/config.py
394
395
396
397
398
399
400
401
402
def to_dict(self) -> dict:
    d = {}
    if self.model:
        d["model"] = self.model
    if self.temperature:
        d["temperature"] = self.temperature
    if self.max_turns:
        d["max_turns"] = self.max_turns
    return d

from_dict classmethod

from_dict(d: dict) -> SubagentConfig
Source code in src/dashscope_agenticx/config.py
404
405
406
407
408
409
410
@classmethod
def from_dict(cls, d: dict) -> SubagentConfig:
    return cls(
        model=d.get("model", ""),
        temperature=float(d.get("temperature", 0.0)),
        max_turns=int(d.get("max_turns", 0)),
    )

DelegationConfig dataclass

DelegationConfig(
    max_concurrent: int = 5,
    default_timeout: int = 120,
    allow_nested: bool = False,
)

Configuration for the delegate tool.

max_concurrent class-attribute instance-attribute

max_concurrent: int = 5

default_timeout class-attribute instance-attribute

default_timeout: int = 120

allow_nested class-attribute instance-attribute

allow_nested: bool = False

to_dict

to_dict() -> dict
Source code in src/dashscope_agenticx/config.py
421
422
423
424
425
426
def to_dict(self) -> dict:
    return {
        "max_concurrent": self.max_concurrent,
        "default_timeout": self.default_timeout,
        "allow_nested": self.allow_nested,
    }

from_dict classmethod

from_dict(d: dict) -> DelegationConfig
Source code in src/dashscope_agenticx/config.py
428
429
430
431
432
433
434
435
@classmethod
def from_dict(cls, d: dict) -> DelegationConfig:
    return cls(
        max_concurrent=int(d.get("max_concurrent", 5)),
        default_timeout=int(d.get("default_timeout", 120)),
        allow_nested=str(d.get("allow_nested", False)).lower()
        in ("true", "1", "yes"),
    )

模型辅助函数

DEFAULT_MODEL module-attribute

DEFAULT_MODEL = 'qwen3.8-flash'

context_window_for_model

context_window_for_model(model: str) -> int

Return the context window (tokens) for a model name.

Prefix-matched against MODEL_CONTEXT_WINDOWS (longest prefix first) so versioned aliases (qwen-turbo-2025-04-28, gpt-4o-2024-...) resolve; unknown models get the conservative default.

Source code in src/dashscope_agenticx/config.py
256
257
258
259
260
261
262
263
264
265
266
def context_window_for_model(model: str) -> int:
    """Return the context window (tokens) for a model name.

    Prefix-matched against MODEL_CONTEXT_WINDOWS (longest prefix first) so
    versioned aliases (qwen-turbo-2025-04-28, gpt-4o-2024-...) resolve; unknown
    models get the conservative default.
    """
    for prefix in sorted(MODEL_CONTEXT_WINDOWS, key=len, reverse=True):
        if model.startswith(prefix):
            return MODEL_CONTEXT_WINDOWS[prefix]
    return DEFAULT_CONTEXT_WINDOW

normalize_model_name

normalize_model_name(model: str) -> str

Strip surrounding whitespace and normalize model names to lowercase.

Source code in src/dashscope_agenticx/config.py
269
270
271
def normalize_model_name(model: str) -> str:
    """Strip surrounding whitespace and normalize model names to lowercase."""
    return model.strip().lower()

register_custom_model

register_custom_model(
    config: "Config",
    provider: str,
    model: str,
    *,
    persist: bool = True
) -> str

Register a custom model: normalize, merge into PROVIDER_MODELS, persist to workspace.

Source code in src/dashscope_agenticx/config.py
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
def register_custom_model(
    config: "Config",
    provider: str,
    model: str,
    *,
    persist: bool = True,
) -> str:
    """Register a custom model: normalize, merge into PROVIDER_MODELS,
    persist to workspace."""
    model = normalize_model_name(model)
    if provider in PROVIDER_MODELS and model not in PROVIDER_MODELS[provider]:
        PROVIDER_MODELS[provider].append(model)
    entry = f"{provider}:{model}"
    custom = getattr(config, "custom_models", None)
    if custom is not None and entry not in custom:
        custom.append(entry)
        if persist:
            config.save_workspace()
    return model

is_vision_model

is_vision_model(model: str) -> bool

True if the model name starts with any registered vision-model prefix.

Source code in src/dashscope_agenticx/config.py
312
313
314
315
def is_vision_model(model: str) -> bool:
    """True if the model name starts with any registered vision-model
    prefix."""
    return _is_model_in_set(model, VISION_MODELS)

is_audio_model

is_audio_model(model: str) -> bool

True if the model name starts with any registered audio-model prefix.

Source code in src/dashscope_agenticx/config.py
318
319
320
def is_audio_model(model: str) -> bool:
    """True if the model name starts with any registered audio-model prefix."""
    return _is_model_in_set(model, AUDIO_MODELS)