Skip to content

Refine create_agent model defaults and AgentRuntime behavior#28

Merged
JohnRichard4096 merged 4 commits intomainfrom
patch/agent-docs
Mar 15, 2026
Merged

Refine create_agent model defaults and AgentRuntime behavior#28
JohnRichard4096 merged 4 commits intomainfrom
patch/agent-docs

Conversation

@JohnRichard4096
Copy link
Copy Markdown
Member

@JohnRichard4096 JohnRichard4096 commented Mar 15, 2026

Summary by Sourcery

Improve agent factory ergonomics, default behaviors, and documentation while tightening type hints and session defaults.

New Features:

  • Allow specifying the model name directly on create_agent() and default to a generic "auto" model.
  • Provide a default system prompt when none is supplied to create_agent().

Bug Fixes:

  • Ensure SessionData subcomponents are initialized via dataclass default factories instead of manual construction.
  • Align ModelPreset default model value with runtime expectations and tests by using "auto" instead of an empty string.

Enhancements:

  • Make AgentRuntime.train a required system message parameter and clarify its purpose in the constructor docs.
  • Add stronger typing and generics for MCPClient and related APIs, and simplify tool refresh logic.
  • Mark control-flow-only methods with pragma: no cover and remove deprecated matcher cancellation API.

Build:

  • Bump package version from 0.6.0 to 0.6.1 to reflect the new API and behavior changes.

Documentation:

  • Update Python and Chinese documentation examples to showcase the new create_agent() model parameter and simplified model_config usage.
  • Clarify create_agent() return type and keep examples consistent across guides and demos.

Tests:

  • Add comprehensive unit tests for AgentRuntime initialization, session handling, training message handling, and the create_agent() factory.

@sourcery-ai
Copy link
Copy Markdown
Contributor

sourcery-ai Bot commented Mar 15, 2026

Reviewer's Guide

Introduces required system-train handling and model defaults for agents, refines MCP generics and hook control-flow typing/coverage hints, makes SessionData fields lazily constructed, updates docs and demos to the new create_agent signature and behavior, bumps the package version, and adds comprehensive tests for AgentRuntime and create_agent.

Sequence diagram for the updated create_agent flow

sequenceDiagram
    actor User
    participant create_agent
    participant Config as AmritaConfig
    participant ModelConfig
    participant ModelPreset
    participant AgentRuntime
    participant Message

    User ->> create_agent: create_agent(url, key, model, train, model_config, config, **kwargs)
    alt train is None
        create_agent ->> create_agent: train = "You are a helpful assistant."
    end

    alt config is None
        create_agent ->> Config: get_config()
        Config -->> create_agent: final_config
    else config provided
        create_agent ->> create_agent: final_config = config
    end

    alt model_config is dict
        create_agent ->> ModelConfig: ModelConfig(**model_config)
        ModelConfig -->> create_agent: model_config_obj
    else model_config is None
        create_agent ->> ModelConfig: ModelConfig()
        ModelConfig -->> create_agent: model_config_obj
    else model_config is ModelConfig
        create_agent ->> create_agent: model_config_obj = model_config
    end

    create_agent ->> ModelPreset: ModelPreset(name=temp_xxxx, base_url=url, api_key=key, config=model_config_obj, model=model)
    ModelPreset -->> create_agent: preset

    create_agent ->> Message: Message(content=train, role=system)
    Message -->> create_agent: system_message

    create_agent ->> AgentRuntime: AgentRuntime(config=final_config, preset=preset, train=system_message, **filtered_kwargs)
    AgentRuntime -->> User: agent_instance
Loading

File-Level Changes

Change Details Files
Make AgentRuntime require an explicit system train message and update create_agent to supply a default system prompt and model parameter.
  • Change AgentRuntime.init signature so train is required rather than optional and document it as the system prompt.
  • Update create_agent to accept an explicit model argument with default 'auto' and an optional train string with a default system prompt.
  • Ensure ModelPreset is instantiated with the provided model and AgentRuntime receives a system Message constructed from the train string.
src/amrita_core/agent/functions.py
src/amrita_core/types.py
tests/test_functions.py
Tighten MCP client typing with generics and slightly adjust client initialization behavior.
  • Introduce a generic MCP_SERVER_SCRIPT_TYPE TypeVar covering supported server script types.
  • Make MCPClient generic over MCP_SERVER_SCRIPT_TYPE and propagate that through ClientManager methods.
  • Use the generic type for server_script variables and adjust the condition for refreshing tools when connecting.
src/amrita_core/tools/mcp.py
Improve hook control-flow utilities typing and test coverage handling.
  • Annotate Matcher.stop_process and pass_event to return Never and mark their exceptions as not covered by tests.
  • Mark Event.fail as excluded from coverage while keeping its behavior unchanged.
  • Remove the deprecated cancel_matcher method from the matcher API.
src/amrita_core/hook/matcher.py
src/amrita_core/hook/event.py
Initialize SessionData subcomponents with dataclass-style default factories instead of explicit creation in SessionsManager.
  • Give SessionData.memory, tools, presets, mcp, and config default_factory values for lazy instantiation.
  • Simplify SessionsManager.init_session to only pass session_id when creating SessionData.
src/amrita_core/sessions.py
Align documentation and demo examples with the updated create_agent API and defaults.
  • Update Python and Chinese API reference examples to pass the model argument separately from model_config and adjust return type text.
  • Revise getting-started minimal examples and demo script to show the new model parameter usage and simpler ModelConfig dictionaries.
docs/guide/api-reference/index.md
docs/zh/guide/api-reference/index.md
docs/guide/getting-started/minimal-example.md
docs/guide/api-reference/classes/AgentRuntime.md
docs/zh/guide/api-reference/classes/AgentRuntime.md
docs/zh/guide/getting-started/minimal-example.md
demo/stream_using.py
Adjust defaults and tests for ModelPreset.model and bump package version.
  • Change ModelPreset.model default to 'auto' instead of an empty string.
  • Update the corresponding unit test to assert the new default value.
  • Increment the project version from 0.6.0 to 0.6.1 in pyproject.toml and refresh the lockfile.
src/amrita_core/types.py
tests/test_types.py
pyproject.toml
uv.lock

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@JohnRichard4096
Copy link
Copy Markdown
Member Author

@sourcery-ai title

@sourcery-ai sourcery-ai Bot changed the title Patch/agent docs Refine create_agent model defaults and AgentRuntime behavior Mar 15, 2026
Copy link
Copy Markdown
Contributor

@sourcery-ai sourcery-ai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 2 issues, and left some high level feedback:

  • The AgentRuntime.__init__ signature now requires train (no default/None), which may break existing callers that relied on the previous optional parameter; consider keeping train optional at the public API level (with a sensible default) and enforcing non-None internally instead.
  • The new MCP_SERVER_SCRIPT_TYPE is declared covariant=True but is used in parameter positions (e.g. get_client_by_script(self, server_script: MCP_SERVER_SCRIPT_TYPE)), which is invalid for a covariant type variable and will confuse type checkers; consider removing covariance or splitting into separate input/output type variables.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- The `AgentRuntime.__init__` signature now requires `train` (no default/`None`), which may break existing callers that relied on the previous optional parameter; consider keeping `train` optional at the public API level (with a sensible default) and enforcing non-`None` internally instead.
- The new `MCP_SERVER_SCRIPT_TYPE` is declared `covariant=True` but is used in parameter positions (e.g. `get_client_by_script(self, server_script: MCP_SERVER_SCRIPT_TYPE)`), which is invalid for a covariant type variable and will confuse type checkers; consider removing covariance or splitting into separate input/output type variables.

## Individual Comments

### Comment 1
<location path="src/amrita_core/agent/functions.py" line_range="181-183" />
<code_context>
         )
         ```
     """
+    train = train or "You are a helpful assistant."
     final_config = config or get_config()
     if isinstance(model_config, dict):
</code_context>
<issue_to_address>
**suggestion (bug_risk):** Using `train = train or ...` may overwrite intentional empty prompts.

Because `or` treats empty strings and other falsy values as missing, this will replace an explicitly empty system prompt with the default. If you only want a default when no value is provided, check specifically for `None`, e.g. `if train is None: train = "You are a helpful assistant."`.

```suggestion
    """
    if train is None:
        train = "You are a helpful assistant."
    final_config = config or get_config()
```
</issue_to_address>

### Comment 2
<location path="src/amrita_core/tools/mcp.py" line_range="30-38" />
<code_context>
 )

-MCP_SERVER_SCRIPT_TYPE = ClientTransportT
+MCP_SERVER_SCRIPT_TYPE = TypeVar(
+    "MCP_SERVER_SCRIPT_TYPE",
+    str,
+    ClientTransport,
+    AnyUrl,
+    FastMCP,
+    MCPConfig,
+    dict[str, Any],
+    covariant=True,
+)

</code_context>
<issue_to_address>
**suggestion:** The new `MCP_SERVER_SCRIPT_TYPE` TypeVar is very broad and may not align well with `Client`’s expectations.

This TypeVar now accepts many unrelated types and is covariant, yet is passed straight into `Client(server_script)` in `_connect`. That combination reduces type safety and makes it easier for incorrect usages to pass static checks. If all these variants are truly needed, consider a precise union type alias instead; otherwise, narrow `MCP_SERVER_SCRIPT_TYPE` closer to the original `ClientTransportT`-like constraint to better match `Client`’s real expectations.

Suggested implementation:

```python
from typing import Any

from fastmcp.mcp_config import MCPConfig
from mcp.types import TextContent
from pydantic import AnyUrl
from typing_extensions import Self
from zipp import Path

```

```python
MCP_SERVER_SCRIPT_TYPE = (
    str
    | ClientTransport
    | AnyUrl
    | FastMCP
    | MCPConfig
    | dict[str, Any]
)

```

If `MCP_SERVER_SCRIPT_TYPE` was previously used as a `TypeVar` in generic classes or functions (e.g., `Generic[MCP_SERVER_SCRIPT_TYPE]` or as a bound type parameter), you should:

1. Replace those generic uses with a non-generic annotation based on the new union alias semantics, for example:
   - From `class Foo(Generic[MCP_SERVER_SCRIPT_TYPE]): ...` to `class Foo: ...`
   - From `def bar(x: MCP_SERVER_SCRIPT_TYPE) -> MCP_SERVER_SCRIPT_TYPE: ...` to the same but now interpreted as a union instead of a type parameter.
2. Ensure that `Client`’s constructor parameter for `server_script` is annotated compatibly with this union (if you control that code). If `fastmcp.Client` already defines a similar union type alias, consider importing and reusing that alias instead of redefining it here for maximum consistency.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment thread src/amrita_core/agent/functions.py
Comment thread src/amrita_core/tools/mcp.py Outdated
@cloudflare-workers-and-pages
Copy link
Copy Markdown

Deploying amritacore with  Cloudflare Pages  Cloudflare Pages

Latest commit: 6239609
Status: ✅  Deploy successful!
Preview URL: https://e0a76ba4.amritacore.pages.dev
Branch Preview URL: https://patch-agent-docs.amritacore.pages.dev

View logs

@JohnRichard4096 JohnRichard4096 merged commit 608144f into main Mar 15, 2026
3 checks passed
@JohnRichard4096 JohnRichard4096 deleted the patch/agent-docs branch March 15, 2026 03:58
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant