Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,20 @@ Thank you for your interest in contributing to AmritaCore! This guide will help

Before participating in the project, please read our [Code of Conduct](./CODE_OF_CONDUCT.md) and abide by its provisions.

## AIGC Content Licensing Policy

We welcome the use of AI-generated content as a tool to enhance development efficiency, while maintaining high standards for code quality and integrity:

1. **AI as a Tool**: The use of AI for code generation is recognized as a technological advancement and valuable productivity tool.

2. **Core Business Logic**: All core business logic code must be written manually by developers and undergo thorough code review. AI-generated core business logic will not be accepted.

3. **Documentation**: AI-generated documentation is permitted, but must strictly conform to the project's API definitions and specifications.

4. **Tests**: Test cases may be generated using LLMs, but must provide complete coverage of the corresponding code lines, logical branches, and edge cases.

5. **Review Requirement**: All AI-generated content, regardless of type, must be reviewed and validated by human contributors before submission.

## Setting Up the Development Environment

1. Fork the repository to your account
Expand Down
2 changes: 0 additions & 2 deletions demo/basic.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,6 @@ async def basic_example():
# FunctionConfig defines general behavior of the agent
func = FunctionConfig(
use_minimal_context=False, # Use full context or minimal context
tool_calling_mode="agent", # How tools are called
agent_thought_mode="reasoning", # How agent thinks through problems
)

# LLMConfig defines language model behavior
Expand Down
2 changes: 0 additions & 2 deletions demo/basic_with_sessions.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,6 @@ async def basic_with_sessions_example():
# Configure AmritaCore with security features
func = FunctionConfig(
use_minimal_context=False,
tool_calling_mode="agent",
agent_thought_mode="reasoning",
)

llm = LLMConfig(
Expand Down
2 changes: 0 additions & 2 deletions demo/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,8 +104,6 @@ async def main():
# Set configuration
func = FunctionConfig(
use_minimal_context=False,
tool_calling_mode="agent",
agent_thought_mode="reasoning",
# agent_mcp_client_enable=True,
# agent_mcp_server_scripts=[],
)
Expand Down
98 changes: 12 additions & 86 deletions demo/stream_using.py
Original file line number Diff line number Diff line change
@@ -1,98 +1,24 @@
"""
Basic Example for AmritaCore - A simple demonstration of core functionality.

This example demonstrates the streaming response usage of AmritaCore.
"""

import asyncio

from amrita_core import ChatObject, init, load_amrita
from amrita_core.chatmanager import RESPONSE_TYPE
from amrita_core.config import AmritaConfig
from amrita_core.types import MemoryModel, Message
from amrita_core import create_agent


async def minimal_example():
"""
A minimal example showing the essential steps to run AmritaCore with stream response.
"""
print("\n🧪 Minimal Example")
print("-" * 30)

# Minimal configuration
from amrita_core.config import set_config

set_config(AmritaConfig())

# Load AmritaCore
await load_amrita()

# Note: In a real scenario, you would configure your model preset here
print("✅ AmritaCore loaded with minimal configuration")

# Create context and system message
context = MemoryModel()
train = Message(content="You are a helpful assistant.", role="system")

# Create and run a chat interaction
chat = ChatObject(
context=context,
session_id="minimal_session",
user_input="What can you do?",
train=train.model_dump(),
# Create an agent with minimal parameters
agent = create_agent(
url="YOUR_API_ENDPOINT", # Replace with your API endpoint
key="YOUR_API_KEY", # Replace with your API key
model_config={"model": "gpt-3.5-turbo", "stream": True},
)
# Collect response (just to show it works)
i = 0
async with chat.begin():
async for chunk in chat.get_response_generator():
print(
chunk.get_content() if not isinstance(chunk, str) else chunk,
end="",
flush=True,
)
i += 1
print(f"💬 Response length: {i} characters")
print("✅ Minimal example completed!")


async def minimal_example_with_callback():
"""
A minimal example showing the essential steps to run AmritaCore with stream response and with callback's using.
"""
length: int = 0

async def callback(message: RESPONSE_TYPE):
nonlocal length
print(message, end="")
length += len(str(message))

print("\n🧪With callback")
print("-" * 30)
from amrita_core.config import set_config
# Get a chat object for the interaction
chat = agent.get_chatobject("Hello, what can you do?")

set_config(AmritaConfig())
await load_amrita()
# Create context and system message
context = MemoryModel()
train = Message(content="You are a helpful assistant.", role="system")

chat = ChatObject(
context=context,
session_id="minimal_session",
user_input="What can you do?",
train=train.model_dump(),
callback=callback, # Pass callback to ChatObject
)
# You can also use `chat.set_callback_func(callback)` to do it!
# Collect response (just to show it works)
await chat.begin()
print(f"💬 Response length: {length} characters")
print("✅ Example completed!")
# Execute the interaction and get the response
async with chat.begin():
print(await chat.full_response())


# Run the example
if __name__ == "__main__":
# Initialize AmritaCore
init()
asyncio.run(minimal_example())

print("\n✨ All examples completed!")
42 changes: 38 additions & 4 deletions docs/.vitepress/config.mts
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ export default withMermaid({
{ text: "Event System", link: "/guide/concepts/event" },
{ text: "Tool System", link: "/guide/concepts/tool" },
{ text: "Data Management", link: "/guide/concepts/management" },
{ text: "Agent Strategy", link: "/guide/concepts/agent-strategy" },
],
},
{
Expand Down Expand Up @@ -107,6 +108,18 @@ export default withMermaid({
text: "AmritaConfig",
link: "/guide/api-reference/classes/AmritaConfig",
},
{
text: "AgentRuntime",
link: "/guide/api-reference/classes/AgentRuntime",
},
{
text: "AgentStrategy",
link: "/guide/api-reference/classes/AgentStrategy",
},
{
text: "AmritaAgentStrategy",
link: "/guide/api-reference/classes/AmritaAgentStrategy",
},
{
text: "BaseModel",
link: "/guide/api-reference/classes/BaseModel",
Expand Down Expand Up @@ -151,6 +164,10 @@ export default withMermaid({
text: "ModelPreset",
link: "/guide/api-reference/classes/ModelPreset",
},
{
text: "StrategyContext",
link: "/guide/api-reference/classes/StrategyContext",
},
{
text: "TextContent",
link: "/guide/api-reference/classes/TextContent",
Expand Down Expand Up @@ -263,6 +280,7 @@ export default withMermaid({
{ text: "事件系统", link: "/zh/guide/concepts/event" },
{ text: "工具系统", link: "/zh/guide/concepts/tool" },
{ text: "数据管理", link: "/zh/guide/concepts/management" },
{ text: "Agent 策略", link: "/zh/guide/concepts/agent-strategy" },
],
},
{
Expand Down Expand Up @@ -301,6 +319,18 @@ export default withMermaid({
text: "AmritaConfig",
link: "/zh/guide/api-reference/classes/AmritaConfig",
},
{
text: "AgentRuntime",
link: "/zh/guide/api-reference/classes/AgentRuntime",
},
{
text: "AgentStrategy",
link: "/zh/guide/api-reference/classes/AgentStrategy",
},
{
text: "AmritaAgentStrategy",
link: "/zh/guide/api-reference/classes/AmritaAgentStrategy",
},
{
text: "BaseModel",
link: "/zh/guide/api-reference/classes/BaseModel",
Expand All @@ -317,6 +347,10 @@ export default withMermaid({
text: "DependsFactory",
link: "/zh/guide/api-reference/classes/DependsFactory",
},
{
text: "FallbackContext",
link: "/zh/guide/api-reference/classes/FallbackContext",
},
{
text: "Function",
link: "/zh/guide/api-reference/classes/Function",
Expand All @@ -325,10 +359,6 @@ export default withMermaid({
text: "FunctionDefinitionSchema",
link: "/zh/guide/api-reference/classes/FunctionDefinitionSchema",
},
{
text: "FallbackContext",
link: "/zh/guide/api-reference/classes/FallbackContext",
},
{
text: "MemoryModel",
link: "/zh/guide/api-reference/classes/MemoryModel",
Expand All @@ -345,6 +375,10 @@ export default withMermaid({
text: "ModelPreset",
link: "/zh/guide/api-reference/classes/ModelPreset",
},
{
text: "StrategyContext",
link: "/zh/guide/api-reference/classes/StrategyContext",
},
{
text: "TextContent",
link: "/zh/guide/api-reference/classes/TextContent",
Expand Down
68 changes: 68 additions & 0 deletions docs/guide/api-reference/classes/AgentRuntime.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
# AgentRuntime

The AgentRuntime class is a high-level wrapper around ChatObject that provides a reusable agent operation interface.

This class encapsulates the complexity of ChatObject and provides a simplified API for agent interactions. It maintains session state, configuration, and strategy settings, making it a reusable object for multiple agent operations within the same context.

## Properties

- `strategy` (type[AgentStrategy]): Agent strategy class used for execution
- `session_id` (str): Session ID for the agent
- `session` (SessionData | None): Session data or None if no session
- `preset` (ModelPreset): Model preset configuration
- `config` (AmritaConfig): Amrita configuration object
- `train` (Message[str]): Training data (system prompts)
- `context` (MemoryModel): Memory context for the conversation
- `template` (Template): Jinja2 template used to render system role message

## Constructor Parameters

- `config` ([AmritaConfig](AmritaConfig.md)): Amrita configuration object containing global configuration settings
- `preset` ([ModelPreset](ModelPreset.md)): Model preset configuration defining basic model parameters and settings
- `strategy` (type[AgentStrategy], optional): Agent strategy class, defaults to AmritaAgentStrategy
- `template` (Template | str, optional): Train template to render system role message, defaults to DEFAULT_TEMPLATE
- `session` (SessionData | str | None, optional): Session data or session ID string for restoring existing sessions. If None, a new session will be created
- `train` (dict[str, str] | Message[str] | None, optional): Training data (system prompts), can be in dictionary format or as a Message object
- `no_session` (bool, optional): Whether to disable session functionality. If True, session management will be disabled but a temporary session ID will still be assigned

## Methods

### set_strategy(strategy)

Set the agent strategy to be used for execution.

**Parameters**:

- `strategy` (type[AgentStrategy]): The agent strategy to be used for execution

### get_chatobject(input, \*\*kwargs)

Get a chat object for a specific interaction.

**Parameters**:

- `input` (USER_INPUT): Input from the user
- `**kwargs`: Additional keyword arguments passed to ChatObject constructor

**Returns**: [ChatObject](ChatObject.md) - A configured ChatObject instance ready for execution

## Usage Example

```python
from amrita_core import create_agent

# Create an agent using the factory function
agent = create_agent(
url="https://api.example.com",
key="your-api-key",
model_config={"model": "gpt-4", "temperature": 0.7}
)

# Get a chat object for interaction
chat = agent.get_chatobject("Hello, what can you do?")

# Execute the interaction
async with chat.begin():
response = await chat.full_response()
print(response)
```
66 changes: 66 additions & 0 deletions docs/guide/api-reference/classes/AgentStrategy.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
# AgentStrategy

The AgentStrategy abstract base class defines how an agent should execute its workflow.

This class provides a unified interface for different types of agent execution strategies, allowing the system to support various agent patterns (basic tool calling, RAG, complex workflows).

## Strategy Categories

Different strategy categories have different execution patterns:

- **'agent'**: Uses `single_execute()` method for step-by-step tool calling, managed by the framework
- **'rag'**: Uses `run()` method with minimal context (only system message and user query)
- **'workflow'**: Uses `run()` method with full manual control over tool calling and context management
- **'agent-mixed'**: Uses `single_execute()` method but can handle both RAG and Agent modes dynamically

## Properties

- `session` (SessionData | None): The session data associated with the current chat session, or None if not available
- `tools_manager` (MultiToolsManager): Manager for handling available tools in the current context
- `chat_object` (ChatObject): The chat object for yielding responses and managing the conversation flow
- `ctx` (StrategyContext): The strategy context containing execution parameters and configuration

## Constructor Parameters

- `ctx` ([StrategyContext](StrategyContext.md)): Strategy context containing chat_object, configuration, and message context

## Abstract Methods

### get_category()

Get the category of the agent strategy.

**Returns**: Literal["agent", "workflow", "rag", "agent-mixed"] - The strategy category as a literal string indicating execution pattern.

## Methods

### single_execute()

Execute a single agent step for 'agent' and 'agent-mixed' category strategies.

This method is called by the framework to perform one iteration of tool calling. The framework handles the loop management, call counting, and termination conditions.

**Returns**: bool - True if should continue to next execution, False to stop.

**Note**: This method is used by 'agent' and 'agent-mixed' category strategies. 'rag' and 'workflow' category strategies should implement `run()` instead.

### run()

Run the complete agent strategy for 'rag' and 'workflow' category strategies.

This method gives full control to the strategy implementation for managing tool calling iterations, context construction, error handling, and response generation.

**Note**: This method is used by 'rag' and 'workflow' category strategies. 'agent' and 'agent-mixed' category strategies should implement `single_execute()` instead.

### on_limited()

Handle the event when the agent reaches its tool calling limit.

This method is called when the agent strategy has reached the maximum allowed number of tool calls as configured by the framework.

### on_exception(exc)

Handle exceptions that occur during strategy execution.

**Parameters**:
- `exc` (BaseException): The exception that occurred during execution
Loading
Loading