### OdaContext Usage Example Source: https://github.com/onedragon-anything/onedragon-agent/blob/main/docs/sdk/api_reference/oda_context.md Example demonstrating how to initialize and use OdaContext. It shows creating a configuration, initializing the context, starting the system, accessing various managers, and stopping the system. ```Python from one_dragon_agent import OdaContext, OdaContextConfig # 创建配置 config = OdaContextConfig() # 初始化 OdaContext context = OdaContext(config) await context.start() # 获取各种管理器 session_manager = context.session_manager agent_manager = context.agent_manager model_config_manager = context.model_config_manager tool_manager = context.tool_manager mcp_manager = context.mcp_manager agent_config_manager = context.agent_config_manager # 使用完成后停止 await context.stop() ``` -------------------------------- ### Install Dependencies and Package Source: https://github.com/onedragon-anything/onedragon-agent/blob/main/docs/develop/spec/agent_guidelines.md Installs project dependencies using `uv sync` and installs the `one_dragon_agent` package in editable mode. ```Bash uv sync --group dev uv pip install -e . ``` -------------------------------- ### Example Usage of OdaMcpManager Source: https://github.com/onedragon-anything/onedragon-agent/blob/main/docs/sdk/api_reference/oda_mcp_manager.md Demonstrates the usage of OdaMcpManager, including initializing the system, registering, getting, listing, updating, and unregistering MCP configurations, and creating an MCP toolset. ```python from one_dragon_agent import OdaContext, OdaContextConfig from one_dragon_agent.core.tool.mcp.oda_mcp_config import OdaMcpConfig # 初始化系统 config = OdaContextConfig() context = OdaContext(config) await context.start() try: # 获取 MCP 管理器 mcp_manager = context.mcp_manager # 创建 MCP 配置 mcp_config = OdaMcpConfig( app_name="my_app", mcp_id="filesystem_stdio", name="文件系统 MCP", description="提供文件系统操作能力", server_type="stdio", command="npx", args=["-y", "@modelcontextprotocol/server-filesystem", "/path/to/folder"], tool_filter=["read_file", "list_directory"] ) # 注册自定义 MCP 配置 await mcp_manager.register_custom_config(mcp_config) # 获取 MCP 配置 config = await mcp_manager.get_mcp_config( app_name="my_app", mcp_id="filesystem_stdio" ) if config: print(f"MCP 配置: {config}") # 列出所有 MCP 配置 configs = await mcp_manager.list_mcp_configs(app_name="my_app") print(f"应用 my_app 有 {len(configs)} 个 MCP 配置") # 创建 MCP 工具集 toolset = await mcp_manager.create_mcp_toolset( app_name="my_app", mcp_id="filesystem_stdio" ) print(f"创建的 MCP 工具集: {toolset}") # 更新 MCP 配置 mcp_config.tool_filter.append("write_file") await mcp_manager.update_custom_config( app_name="my_app", mcp_id="filesystem_stdio", config=mcp_config ) # 删除 MCP 配置 await mcp_manager.unregister_custom_config( app_name="my_app", mcp_id="filesystem_stdio" ) finally: await context.stop() ``` -------------------------------- ### MCP Configuration Management Examples Source: https://github.com/onedragon-anything/onedragon-agent/blob/main/docs/sdk/api_reference.md Provides usage examples for the MCP manager, including creating, registering, getting, listing, updating, and unregistering MCP configurations. ```Python # 获取 MCP 管理器 mcp_manager = context.get_mcp_manager() # 创建 MCP 配置 mcp_config = OdaMcpConfig( mcp_id="filesystem_stdio", app_name="my_app", name="文件系统 MCP", description="提供文件系统操作能力", server_type="stdio", command="npx", args=["-y", "@modelcontextprotocol/server-filesystem", "/path/to/folder"], tool_filter=["read_file", "list_directory"] ) # 注册自定义 MCP 配置 await mcp_manager.register_custom_config(mcp_config) # 获取 MCP 配置 config = await mcp_manager.get_mcp_config( app_name="my_app", tool_id="filesystem_stdio" ) if config: print(f"MCP 配置: {config}") # 列出所有 MCP 配置 configs = await mcp_manager.list_mcp_configs(app_name="my_app") print(f"应用 my_app 有 {len(configs)} 个 MCP 配置") # 更新 MCP 配置 mcp_config.tool_filter.append("write_file") await mcp_manager.update_custom_config( app_name="my_app", tool_id="filesystem_stdio", config=mcp_config ) # 删除 MCP 配置 await mcp_manager.unregister_custom_config( app_name="my_app", tool_id="filesystem_stdio" ) ``` -------------------------------- ### Agent Configuration Management Examples Source: https://github.com/onedragon-anything/onedragon-agent/blob/main/docs/sdk/api_reference.md Provides usage examples for the agent configuration manager, including creating, getting, listing, validating model configurations, validating MCP configurations, and checking for built-in configurations. ```Python # 获取智能体配置管理器 agent_config_manager = context.get_agent_config_manager() # 创建智能体配置 agent_config = OdaAgentConfig( app_name="my_app", agent_name="weather_agent", agent_type="llm_agent", description="天气查询智能体", instruction="你是一个天气查询助手,帮助用户获取天气信息", model_config="gemini-config", tool_list=["get_weather", "get_temperature"] ) await agent_config_manager.create_config(agent_config) # 获取智能体配置 config = await agent_config_manager.get_config("weather_agent") if config: print(f"智能体配置: {config}") # 列出所有智能体配置 configs = await agent_config_manager.list_configs() print(f"共有 {len(configs)} 个智能体配置") # 验证模型配置 is_valid = await agent_config_manager.validate_model_config( app_name="my_app", model_config="gemini-config" ) print(f"模型配置有效: {is_valid}") # 验证 MCP 配置 is_valid = await agent_config_manager.validate_mcp_config( app_name="my_app", mcp_list=["filesystem_mcp"] ) print(f"MCP 配置有效: {is_valid}") # 检查是否为内置配置 is_builtin = agent_config_manager.is_built_in_config("default") print(f"是否为内置配置: {is_builtin}") ``` -------------------------------- ### OdaContext Usage Example Source: https://github.com/onedragon-anything/onedragon-agent/blob/main/docs/sdk/api_reference.md Demonstrates the basic usage of OdaContext, including initialization, starting the context, retrieving managers, and stopping the context. This example shows how to set up and tear down the core components of the OneDragon Agent. ```Python from one_dragon_agent import OdaContext, OdaContextConfig # 创建配置 config = OdaContextConfig() # 初始化 OdaContext context = OdaContext(config) await context.start() # 获取各种管理器 session_manager = context.get_session_manager() agent_manager = context.get_agent_manager() # 使用完成后停止 await context.stop() ``` -------------------------------- ### Example Usage of OdaAgentManager Source: https://github.com/onedragon-anything/onedragon-agent/blob/main/docs/sdk/api_reference/oda_agent_manager.md Demonstrates how to initialize the system, get the agent manager, create an agent instance, and use it to process a message. It includes proper system startup and shutdown procedures using a try-finally block. ```python from one_dragon_agent import OdaContext, OdaContextConfig # 初始化系统 config = OdaContextConfig() context = OdaContext(config) await context.start() try: # 获取智能体管理器 agent_manager = context.agent_manager # 创建智能体 agent = await agent_manager.create_agent( agent_name="weather_agent", app_name="my_app", user_id="user_123", session_id="session_001" ) # 使用智能体处理消息 async for event in agent.run_async("今天天气怎么样?"): print(f"事件: {event}") finally: await context.stop() ``` -------------------------------- ### Start OdaContext System Source: https://github.com/onedragon-anything/onedragon-agent/blob/main/docs/sdk/api_reference/oda_context.md Starts the system and initializes all services and managers. This is the main entry point for starting the OdaContext system, initializing all ADK native services and OneDragon manager components in the correct order of dependencies. ```Python async def start(self) -> None: """启动系统并初始化所有服务和管理器 此方法是启动 OdaContext 系统的主要入口点。 它按照依赖关系的正确顺序初始化所有 ADK 原生服务和 OneDragon 管理组件。 """ ``` -------------------------------- ### Example Usage of Model Configuration Management Source: https://github.com/onedragon-anything/onedragon-agent/blob/main/docs/sdk/api_reference.md Demonstrates the usage of the model configuration manager, including creating, getting, getting default, listing, and validating model configurations. ```Python # 获取模型配置管理器 model_config_manager = context.get_model_config_manager() # 创建模型配置 model_config = OdaModelConfig( app_name="my_app", model_id="gemini-config", base_url="https://api.example.com", api_key="your-api-key", model="gemini-2.0-flash" ) await model_config_manager.create_config(model_config) # 获取模型配置 config = await model_config_manager.get_config("gemini-config") if config: print(f"模型配置: {config}") # 获取默认模型配置 default_config = model_config_manager.get_default_config() if default_config: print(f"默认模型配置: {default_config}") # 列出所有模型配置 configs = await model_config_manager.list_configs() print(f"共有 {len(configs)} 个模型配置") # 验证模型配置 is_valid = await model_config_manager.validate_model_config( app_name="my_app", model_config="gemini-config" ) print(f"模型配置有效: {is_valid}") ``` -------------------------------- ### OdaAgent Usage Example Source: https://github.com/onedragon-anything/onedragon-agent/blob/main/docs/sdk/api_reference/oda_agent.md Provides a Python example demonstrating how to initialize the OneDragon system, create a session, process a message asynchronously using OdaAgent, and clean up resources. ```Python from one_dragon_agent import OdaContext, OdaContextConfig # 初始化系统 config = OdaContextConfig() context = OdaContext(config) await context.start() try: # 获取会话管理器 session_manager = context.session_manager # 创建会话 session = await session_manager.create_session( app_name="my_app", user_id="user_123", session_id="session_001" ) # 异步执行智能体 async for event in session.process_message("你好,请介绍一下自己"): print(f"事件: {event}") # 获取智能体信息 # 注意:智能体实例由会话内部管理,通常不需要直接访问 finally: await context.stop() ``` -------------------------------- ### Python: OdaSessionManager Usage Example Source: https://github.com/onedragon-anything/onedragon-agent/blob/main/docs/sdk/api_reference/oda_session_manager.md Provides a comprehensive example of how to use the OdaSessionManager within the OdaContext. It demonstrates initialization, starting the context, creating, getting, listing, deleting sessions, cleaning up inactive sessions, and setting concurrent limits, all within a try-finally block for proper context cleanup. ```Python from one_dragon_agent import OdaContext, OdaContextConfig # 初始化系统 config = OdaContextConfig() context = OdaContext(config) await context.start() try: # 获取会话管理器 session_manager = context.session_manager # 创建会话 session = await session_manager.create_session( app_name="my_app", user_id="user_123", session_id="session_001" ) # 获取会话 session = await session_manager.get_session( app_name="my_app", user_id="user_123", session_id="session_001" ) # 列出会话 sessions = await session_manager.list_sessions( app_name="my_app", user_id="user_123" ) # 删除会话 await session_manager.delete_session( app_name="my_app", user_id="user_123", session_id="session_001" ) # 清理超时会话 await session_manager.cleanup_inactive_sessions(timeout_seconds=3600) # 设置并发限制 await session_manager.set_concurrent_limit(max_concurrent_sessions=100) finally: await context.stop() ``` -------------------------------- ### Start OdaContext Source: https://github.com/onedragon-anything/onedragon-agent/blob/main/docs/sdk/api_reference.md Starts the OdaContext, initializing all internal services and managers. This method should be called after the context has been created. ```Python async def start(self) -> None: """启动系统,初始化所有服务和管理器""" ``` -------------------------------- ### Stdio MCP Configuration Example Source: https://github.com/onedragon-anything/onedragon-agent/blob/main/docs/sdk/api_reference/oda_mcp_manager.md An example of an OdaMcpConfig for the 'stdio' server type, used for local process communication via standard input and output. ```python # stdio 类型的 MCP 配置示例 stdio_config = OdaMcpConfig( app_name="file_app", mcp_id="filesystem_stdio", name="文件系统 MCP (Stdio)", description="通过 stdio 连接的文件系统 MCP 服务器", server_type="stdio", command="npx", args=["-y", "@modelcontextprotocol/server-filesystem", "/path/to/folder"], tool_filter=["read_file", "list_directory"] ) ``` -------------------------------- ### OdaSession Usage Example Source: https://github.com/onedragon-anything/onedragon-agent/blob/main/docs/sdk/api_reference/oda_session.md Demonstrates how to initialize the OneDragon Agent system, create a session, process messages with and without specifying an agent, and clean up resources. ```Python from one_dragon_agent import OdaContext, OdaContextConfig # 初始化系统 config = OdaContextConfig() context = OdaContext(config) await context.start() try: # 获取会话管理器 session_manager = context.session_manager # 创建会话 session = await session_manager.create_session( app_name="my_app", user_id="user_123", session_id="session_001" ) # 处理消息并迭代事件 async for event in session.process_message( message="你好,请介绍一下自己", agent_name="default" ): print(f"事件: {event}") # 不指定智能体,使用默认智能体 async for event in session.process_message( message="今天天气怎么样?" ): print(f"事件: {event}") finally: # 清理会话资源 await session.cleanup() await context.stop() ``` -------------------------------- ### HTTP MCP Configuration Example Source: https://github.com/onedragon-anything/onedragon-agent/blob/main/docs/sdk/api_reference/oda_mcp_manager.md This Python code provides an example of configuring an MCP server for standard HTTP communication using REST APIs. It specifies the application name, MCP ID, server URL, headers including content type, and filters for various HTTP methods. ```Python # http 类型的 MCP 配置示例 http_config = OdaMcpConfig( app_name="web_app", mcp_id="web_api_http", name="Web API MCP (HTTP)", description="通过 HTTP 连接的 Web API MCP 服务器", server_type="http", url="http://localhost:8080/mcp", headers={"Authorization": "Bearer your-token", "Content-Type": "application/json"}, tool_filter=["get_data", "post_data", "delete_resource"] ) ``` -------------------------------- ### Code Quality Checks with Ruff Source: https://github.com/onedragon-anything/onedragon-agent/blob/main/docs/develop/spec/agent_guidelines.md Performs code checking and formatting using `ruff` via `uv run`. ```Bash uv run ruff check src/ tests/ uv run ruff format src/ tests/ ``` -------------------------------- ### Example Usage: Initialize System and Manage Agent Configurations Source: https://github.com/onedragon-anything/onedragon-agent/blob/main/docs/sdk/api_reference/oda_agent_config_manager.md Demonstrates the initialization of the OneDragon agent system and the usage of OdaAgentConfigManager to create, retrieve, list, validate, update, and delete agent configurations. ```Python from one_dragon_agent import OdaContext, OdaContextConfig, OdaAgentConfig # 初始化系统 config = OdaContextConfig() context = OdaContext(config) await context.start() try: # 获取智能体配置管理器 agent_config_manager = context.agent_config_manager # 创建智能体配置 agent_config = OdaAgentConfig( app_name="my_app", agent_name="weather_agent", agent_type="default", description="天气查询智能体", instruction="你是一个天气查询助手,帮助用户获取天气信息", model_config="gemini-config", tool_list=[], mcp_list=[], sub_agent_list=[] ) await agent_config_manager.create_config(agent_config) # 获取智能体配置 config = await agent_config_manager.get_config("weather_agent") if config: print(f"智能体配置: {config}") # 列出所有智能体配置 configs = await agent_config_manager.list_configs() print(f"共有 {len(configs)} 个智能体配置") # 验证模型配置 is_valid = await agent_config_manager.validate_model_config( app_name="my_app", model_config="gemini-config" ) print(f"模型配置有效: {is_valid}") # 验证 MCP 配置 is_valid = await agent_config_manager.validate_mcp_config( app_name="my_app", mcp_list=["filesystem_mcp"] ) print(f"MCP 配置有效: {is_valid}") # 检查是否为内置配置 is_builtin = agent_config_manager.is_built_in_config("default") print(f"是否为内置配置: {is_builtin}") # 更新智能体配置 config.instruction = "你是一个专业的天气查询助手,提供准确的天气信息和穿衣建议" await agent_config_manager.update_config(config) # 删除智能体配置 await agent_config_manager.delete_config("weather_agent") finally: await context.stop() ``` -------------------------------- ### Execute and Manage OdaAgent Source: https://github.com/onedragon-anything/onedragon-agent/blob/main/docs/sdk/api_reference.md Provides examples for executing agents asynchronously and synchronously, retrieving agent information, checking their readiness status, and cleaning up their resources. ```Python # 异步执行智能体 async for event in agent.run_async("你好,请介绍一下自己"): print(f"事件: {event}") # 同步执行智能体 for event in agent.run("你好,请介绍一下自己"): print(f"事件: {event}") # 获取智能体信息 info = agent.get_agent_info() print(f"智能体信息: {info}") # 检查智能体状态 if agent.is_ready(): print("智能体已就绪") else: print("智能体未就绪") # 清理智能体资源 await agent.cleanup() ``` -------------------------------- ### Example: Registering Built-in Tools Source: https://github.com/onedragon-anything/onedragon-agent/blob/main/docs/sdk/api_reference/oda_tool_manager.md Demonstrates how to initialize OdaContext, access the tool manager, and register instances of built-in tools like FunctionTool for Google Search and code execution. ```Python from google.adk.tools import BaseTool, FunctionTool from one_dragon_agent import OdaContext, OdaContextConfig # 初始化系统 config = OdaContextConfig() context = OdaContext(config) await context.start() try: # 获取工具管理器 tool_manager = context.tool_manager # 注册 Google 搜索工具 google_search = FunctionTool(func=lambda query: {"result": f"搜索结果: {query}"}) await tool_manager.register_tool( tool=google_search, app_name="my_app", tool_id="google_search" ) # 注册代码执行工具 code_exec = FunctionTool(func=lambda code: {"result": f"执行结果: {code}"}) await tool_manager.register_tool( tool=code_exec, app_name="my_app", tool_id="code_execution" ) print("工具注册完成") finally: await context.stop() ``` -------------------------------- ### Run Python Commands with UV Source: https://github.com/onedragon-anything/onedragon-agent/blob/main/docs/develop/spec/agent_guidelines.md Executes Python commands using `uv run`, with an option to use environment variables from a `.env` file. ```Bash uv run python ... uv run --env-file .env python ... ``` -------------------------------- ### Get Agent Config Manager Source: https://github.com/onedragon-anything/onedragon-agent/blob/main/docs/sdk/api_reference.md Retrieves the OdaAgentConfigManager instance, responsible for managing agent-specific configurations. This manager facilitates the setup and modification of agent settings. ```Python def get_agent_config_manager(self) -> OdaAgentConfigManager: """获取智能体配置管理器 Returns: OdaAgentConfigManager: 智能体配置管理器实例 """ ``` -------------------------------- ### WorkspaceIndex Initialization Steps Source: https://github.com/onedragon-anything/onedragon-agent/blob/main/docs/develop/core/modules/workspace_index.md Outlines the asynchronous initialization process for WorkspaceIndex, including PathSpec construction, core index building, and file system event listening. ```Python # 1. PathSpec construction: core_patterns -> ignore_patterns -> .gitignore # 2. Core area index construction # 3. Start file system event listener ``` -------------------------------- ### Python Explicit Parent Class Constructor Call Source: https://github.com/onedragon-anything/onedragon-agent/blob/main/docs/develop/spec/agent_guidelines.md This example illustrates the mandatory practice of directly calling the parent class constructor in subclasses within the OneDragon Agent project. It explicitly forbids the use of `super().__init__()` for clarity and adherence to project-specific standards. ```Python # Correct: class MySubclass(MyBaseClass): def __init__(self, name, value): # Directly call the parent's __init__ MyBaseClass.__init__(self, name) self.value = value ``` ```Python # Incorrect: class MySubclass(MyBaseClass): def __init__(self, name, value): # Do not use super() for initialization super().__init__(name) self.value = value ``` -------------------------------- ### 配置系统环境变量 (Windows) Source: https://github.com/onedragon-anything/onedragon-agent/blob/main/docs/sdk/configuration.md 展示如何在 Windows 系统中通过 `set` 命令设置 OneDragon-Agent 的系统级环境变量,包括持久化方式、LLM 服务地址、API KEY 和模型。 ```cmd set ODA_STORAGE=mysql set ODA_DEFAULT_LLM_BASE_URL="https://api.example.com" set ODA_DEFAULT_LLM_API_KEY="your-api-key" set ODA_DEFAULT_LLM_MODEL="gemini-2.0-flash" ``` -------------------------------- ### WorkspaceIndex Constructor Parameters Source: https://github.com/onedragon-anything/onedragon-agent/blob/main/docs/develop/core/modules/workspace_index.md Defines the parameters for initializing the WorkspaceIndex service, including root path, core patterns, ignore patterns, and whether to use .gitignore files. ```Python root_path: str core_patterns: list[str] ignore_patterns: list[str] use_gitignore: bool ``` -------------------------------- ### 初始化 OneDragon-Agent 系统 Source: https://github.com/onedragon-anything/onedragon-agent/blob/main/docs/sdk/basic_usage.md 演示如何使用 OneDragon-Agent SDK 初始化系统。这包括创建配置对象、初始化 OdaContext 并启动系统。支持通过环境变量进行自动配置。 ```Python import asyncio from one_dragon_agent import OdaContext, OdaContextConfig async def main(): # 创建配置对象 config = OdaContextConfig() # 初始化 OdaContext context = OdaContext(config) # 启动系统 await context.start() try: # 在这里使用 SDK pass finally: # 停止系统并清理资源 await context.stop() if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### 管理 OneDragon-Agent 会话 Source: https://github.com/onedragon-anything/onedragon-agent/blob/main/docs/sdk/basic_usage.md 展示了如何使用 OneDragon-Agent SDK 管理会话,包括创建新会话、获取现有会话、列出用户的所有会话以及删除会话。每个会话代表一个独立的用户对话环境。 ```Python # 获取会话管理器 session_manager = context.get_session_manager() # 创建新会话 session = await session_manager.create_session( app_name="my_app", user_id="user_123", session_id="session_001" # 可选,如果不提供会自动生成 ) print(f"会话创建成功: {session}") ``` ```Python # 获取指定会话 session = await session_manager.get_session( app_name="my_app", user_id="user_123", session_id="session_001" ) if session: print("会话存在") else: print("会话不存在") ``` ```Python # 列出指定用户的所有会话 sessions = await session_manager.list_sessions( app_name="my_app", user_id="user_123" ) print(f"用户 {user_id} 有 {len(sessions)} 个会话") for session in sessions: print(f"- 会话ID: {session}") ``` ```Python # 删除指定会话 await session_manager.delete_session( app_name="my_app", user_id="user_123", session_id="session_001" ) print("会话已删除") ``` -------------------------------- ### SSE Server Configuration Example Source: https://github.com/onedragon-anything/onedragon-agent/blob/main/docs/sdk/api_reference/oda_mcp_config.md Illustrates the creation and usage of an OdaMcpConfig object for an 'sse' type MCP server. This example includes setting the mcp_id, app_name, name, description, server_type, URL, headers, and tool_filter, and demonstrates accessing these configuration values. ```Python # sse 类型的 MCP 配置示例 sse_config = OdaMcpConfig( mcp_id="web_api_sse", app_name="web_app", name="Web API MCP (SSE)", description="通过 SSE 连接的 Web API MCP 服务器", server_type="sse", url="http://localhost:8090/sse", headers={"Authorization": "Bearer your-token"}, tool_filter=["fetch_data", "submit_form"] ) # 访问配置属性 print(f"MCP ID: {sse_config.mcp_id}") print(f"应用名称: {sse_config.app_name}") print(f"服务器类型: {sse_config.server_type}") print(f"服务器 URL: {sse_config.url}") print(f"请求头: {sse_config.headers}") print(f"工具过滤器: {sse_config.tool_filter}") ``` -------------------------------- ### HTTP Server Configuration Example Source: https://github.com/onedragon-anything/onedragon-agent/blob/main/docs/sdk/api_reference/oda_mcp_config.md Provides an example of configuring an OdaMcpConfig object for an 'http' type MCP server. The code shows how to initialize the configuration with relevant details such as mcp_id, app_name, name, description, server_type, URL, headers, and tool_filter, and how to retrieve these settings. ```Python # http 类型的 MCP 配置示例 http_config = OdaMcpConfig( mcp_id="web_api_http", app_name="web_app", name="Web API MCP (HTTP)", description="通过 HTTP 连接的 Web API MCP 服务器", server_type="http", url="http://localhost:8080/mcp", headers={"Authorization": "Bearer your-token", "Content-Type": "application/json"}, tool_filter=["get_data", "post_data", "delete_resource"] ) ``` -------------------------------- ### MCP Tool: Model Context Protocol Source: https://github.com/onedragon-anything/onedragon-agent/blob/main/docs/develop/core/modules/oda_tool_manager.md Illustrates the usage of MCP (Model Context Protocol) tools. The example defines an asynchronous function `create_mcp_tools` that initializes an MCPToolset with connection parameters and loads available tools. This enables interaction with models through the MCP. ```Python from google.adk.tools.mcp_tool.mcp_toolset import MCPToolset async def create_mcp_tools(): mcp_toolset = MCPToolset( connection_params=... ) # MCP connection parameters async with mcp_toolset as toolset: tools = await toolset.load_tools() return tools ``` -------------------------------- ### Agent Instance Creation Flow Source: https://github.com/onedragon-anything/onedragon-agent/blob/main/docs/develop/core/modules/oda_agent_manager.md This Mermaid diagram illustrates the step-by-step process for creating an agent instance, from the initial request to the final return of the configured agent instance. It highlights key components like configuration validation, MCP tool usage, and dependency injection into the Runner and LlmAgent. ```mermaid graph TD A[开始: 请求创建智能体实例] --> B{获取智能体配置}; B --> C[验证配置的有效性]; C --> D{检查是否需要MCP工具}; D --> E[需要MCP工具]; D --> F[不需要MCP工具]; E --> G[通过OdaMcpManager创建MCPToolset]; F --> H[创建ADK原生LlmAgent实例]; G --> H[创建ADK原生LlmAgent实例]; H --> I[创建Runner实例]; I --> J[静态绑定LlmAgent到Runner]; J --> K[注入SessionService到Runner]; K --> L[注入ArtifactService到Runner]; L --> M[注入MemoryService到Runner]; M --> N[注入MCPToolset到LlmAgent]; N --> O[配置动态会话绑定]; O --> P[创建OdaAgent包装器实例]; P --> Q[初始化智能体内部状态]; Q --> R[返回OdaAgent实例]; R --> S[创建完成]; ``` -------------------------------- ### Get OdaAgent Information Source: https://github.com/onedragon-anything/onedragon-agent/blob/main/docs/sdk/api_reference/oda_agent.md Retrieves information about the OdaAgent. Returns a dictionary containing the agent's details. ```Python def get_agent_info(self) -> dict: """获取智能体信息 Returns: dict: 智能体信息 """ pass ``` -------------------------------- ### Get Agent Configuration Source: https://github.com/onedragon-anything/onedragon-agent/blob/main/docs/sdk/api_reference.md Retrieves an agent configuration by its unique identifier. Returns the configuration object or None if it does not exist. ```Python async def get_config(self, agent_name: str) -> Optional[OdaAgentConfig]: """获取智能体配置 Args: agent_name: 智能体名称,唯一标识符 Returns: Optional[OdaAgentConfig]: 配置对象,如果不存在则返回 None """ pass ``` -------------------------------- ### Search Method Behavior During Initialization Source: https://github.com/onedragon-anything/onedragon-agent/blob/main/docs/develop/core/modules/workspace_index.md Outlines the logic within the search method to handle different initialization states: fully initialized, initializing, and degraded mode (initialization failed or timed out). This ensures responsiveness and robustness. ```Python # Assuming search method, initialization_state, and index structures are available def search(query): if initialization_state == 'initialized': # Perform normal search on the complete index return perform_full_search(query) elif initialization_state == 'initializing': # Attempt immediate search on partially built index (core files) result = perform_partial_search(query) if result: return result else: # Wait for initialization to complete (with timeout) if wait_for_initialization(timeout=30): # Re-run search on the now complete index return perform_full_search(query) else: # Initialization failed or timed out, enter degraded mode return perform_degraded_search(query) else: # Degraded mode # Search only on the incomplete index return perform_degraded_search(query) # Helper functions like perform_full_search, perform_partial_search, # wait_for_initialization, perform_degraded_search would be defined elsewhere. ``` -------------------------------- ### Initialize and Use OdaContext Source: https://github.com/onedragon-anything/onedragon-agent/blob/main/docs/sdk/concepts.md Demonstrates how to create, start, and stop the OdaContext, which serves as the global resource manager. It also shows how to access various managers like session and agent managers. ```Python from one_dragon_agent import OdaContext, OdaContextConfig # 创建配置 config = OdaContextConfig() # 初始化 OdaContext context = OdaContext(config) await context.start() # 获取各种管理器 session_manager = context.get_session_manager() agent_manager = context.get_agent_manager() mcp_manager = context.get_mcp_manager() # 使用完成后停止 await context.stop() ``` -------------------------------- ### Get MCP Configuration Source: https://github.com/onedragon-anything/onedragon-agent/blob/main/docs/sdk/api_reference/oda_mcp_manager.md Retrieves an MCP configuration, supporting queries for both built-in and custom configurations. Returns the OdaMcpConfig object or None if not found. ```python async def get_mcp_config(self, app_name: str, mcp_id: str) -> OdaMcpConfig | None: """获取 MCP 配置(支持查询内置和自定义配置) Args: app_name: 应用名称 mcp_id: MCP 标识符 Returns: OdaMcpConfig | None: MCP 配置对象或 None """ ``` -------------------------------- ### 完整示例:OneDragon-Agent 会话和消息处理 Source: https://github.com/onedragon-anything/onedragon-agent/blob/main/docs/sdk/basic_usage.md 此示例演示了如何初始化 OneDragon-Agent 上下文,创建用户会话,处理多轮消息,捕获预期的智能体未找到错误,以及列出用户的所有会话。它涵盖了 SDK 的核心功能。 ```Python import asyncio from one_dragon_agent import OdaContext, OdaContextConfig from one_dragon_agent.exceptions import SessionNotFoundError, AgentNotFoundError async def main(): # 初始化系统 config = OdaContextConfig() context = OdaContext(config) await context.start() try: # 获取会话管理器 session_manager = context.get_session_manager() # 创建会话 session = await session_manager.create_session( app_name="chat_app", user_id="user_123", session_id="chat_session_001" ) print(f"会话创建成功: {session}") # 第一轮对话 try: response1 = await session.process_message( message="你好,我叫李四", agent_name="default" ) print(f"智能体: {response1}") except Exception as e: print(f"第一轮对话错误: {e}") # 第二轮对话 try: response2 = await session.process_message( message="记住我的名字了吗?", agent_name="default" ) print(f"智能体: {response2}") except Exception as e: print(f"第二轮对话错误: {e}") # 尝试使用不存在的智能体 try: response3 = await session.process_message( message="测试错误处理", agent_name="nonexistent_agent" ) print(f"智能体: {response3}") except AgentNotFoundError as e: print(f"捕获到预期错误: {e}") # 列出用户的所有会话 sessions = await session_manager.list_sessions( app_name="chat_app", user_id="user_123" ) print(f"用户 user_123 有 {len(sessions)} 个会话") finally: # 停止系统 await context.stop() if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Initialize OdaContextConfig with Constructor Source: https://github.com/onedragon-anything/onedragon-agent/blob/main/docs/sdk/api_reference/oda_context_config.md Demonstrates how to initialize the OdaContextConfig class using its constructor, specifying storage type and default LLM parameters. ```Python from one_dragon_agent import OdaContextConfig config = OdaContextConfig( storage="memory", default_llm_base_url="https://api.example.com", default_llm_api_key="your-api-key", default_llm_model="gemini-2.0-flash" ) print(f"存储方式: {config.storage}") print(f"默认 LLM 地址: {config.default_llm_base_url}") print(f"默认 LLM 模型: {config.default_llm_model}") ``` -------------------------------- ### Get Agent Configuration Source: https://github.com/onedragon-anything/onedragon-agent/blob/main/docs/sdk/api_reference/oda_agent_config_manager.md Retrieves an agent configuration by its unique agent name. Returns the configuration object if found, otherwise returns None. ```Python async def get_config(self, agent_name: str) -> OdaAgentConfig | None: """获取智能体配置 Args: agent_name: 智能体名称,唯一标识符 Returns: OdaAgentConfig | None: 配置对象,如果不存在则返回 None """ pass ``` -------------------------------- ### Get Agent Manager Source: https://github.com/onedragon-anything/onedragon-agent/blob/main/docs/sdk/api_reference.md Retrieves the OdaAgentManager instance, responsible for managing agent-related functionalities. This manager provides access to agent configurations and operations. ```Python def get_agent_manager(self) -> OdaAgentManager: """获取智能体管理器 Returns: OdaAgentManager: 智能体管理器实例 """ ``` -------------------------------- ### 使用配置文件加载配置 (Python) Source: https://github.com/onedragon-anything/onedragon-agent/blob/main/docs/sdk/configuration.md 此示例展示了如何从 JSON 文件加载应用程序配置。它定义了一个 `load_config_from_file` 函数来读取文件内容,然后使用这些数据来创建模型配置。 ```Python import json from pathlib import Path def load_config_from_file(file_path): with open(file_path, 'r') as f: return json.load(f) # 加载配置文件 config_data = load_config_from_file("config.json") # 创建模型配置 model_config = OdaModelConfig( app_name=config_data["app_name"], model_id=config_data["model"]["id"], base_url=config_data["model"]["base_url"], api_key=config_data["model"]["api_key"], model=config_data["model"]["name"] ) ``` -------------------------------- ### Get Default Agent Configuration Source: https://github.com/onedragon-anything/onedragon-agent/blob/main/docs/sdk/configuration.md Retrieves the default agent configuration, which is automatically created and cannot be modified. It prints the configuration if available, otherwise indicates it's unavailable. ```python # 获取默认智能体配置(会自动创建) default_config = await agent_config_manager.get_config("default") if default_config: print(f"默认智能体配置: {default_config}") else: print("默认智能体配置不可用") ``` -------------------------------- ### 在 OneDragon-Agent 中处理消息 Source: https://github.com/onedragon-anything/onedragon-agent/blob/main/docs/sdk/basic_usage.md 演示了如何通过 OneDragon-Agent SDK 的会话对象发送消息并获取智能体的响应。支持使用默认智能体或指定特定智能体进行处理。 ```Python # 发送消息并获取响应 response = await session.process_message( message="你好,请介绍一下自己", agent_name="default" # 使用默认智能体 ) print(f"智能体响应: {response}") ``` ```Python # 使用特定智能体处理消息 response = await session.process_message( message="帮我查询一下北京的天气", agent_name="weather_agent" # 使用天气查询智能体 ) print(f"天气查询结果: {response}") ``` ```Python # 不指定智能体,使用默认智能体 response = await session.process_message( message="今天天气怎么样?" ) print(f"响应: {response}") ``` -------------------------------- ### Interact with OdaSession Source: https://github.com/onedragon-anything/onedragon-agent/blob/main/docs/sdk/api_reference.md Provides examples of how to use the OdaSession object to process messages, retrieve session information, check activity status, and clean up resources. ```Python # 处理消息 response = await session.process_message( message="你好,请介绍一下自己", agent_name="default" ) print(f"响应: {response}") # 不指定智能体,使用默认智能体 response = await session.process_message( message="今天天气怎么样?" ) print(f"响应: {response}") # 获取会话信息 info = session.get_session_info() print(f"会话信息: {info}") # 检查会话状态 if session.is_active(): print("会话处于活跃状态") else: print("会话已关闭") # 清理会话资源 await session.cleanup() ``` -------------------------------- ### Multi-turn Conversation Example with OdaSession Source: https://github.com/onedragon-anything/onedragon-agent/blob/main/docs/sdk/api_reference/oda_session.md Illustrates a multi-turn conversation using OdaSession, showing how the agent maintains context across multiple `process_message` calls. ```Python # 第一轮对话 async for event in session.process_message( message="我叫张三", agent_name="default" ): if hasattr(event, 'content') and event.content: print(f"第一轮: {event.content}") # 第二轮对话(智能体会记住用户的名字) async for event in session.process_message( message="我叫什么名字?", agent_name="default" ): if hasattr(event, 'content') and event.content: print(f"第二轮: {event.content}") # 输出: 你叫张三 ``` -------------------------------- ### Create OdaContextConfig from Environment Variables Source: https://github.com/onedragon-anything/onedragon-agent/blob/main/docs/sdk/api_reference/oda_context_config.md Shows how to create an OdaContextConfig instance by loading settings from environment variables using the `from_env` class method. ```Python from one_dragon_agent import OdaContextConfig config = OdaContextConfig.from_env() ```