diff --git a/.gitleaks.toml b/.gitleaks.toml index 2b48875..14735aa 100644 --- a/.gitleaks.toml +++ b/.gitleaks.toml @@ -77,4 +77,7 @@ paths = [ "requirements.txt", "tests/platform/test_configuration_creds.py", "tests/platform/test_configuration_byteplus.py" -] \ No newline at end of file +] +regexes = [ + '''c05d49af-1234-5678-abcd-xxxx''', +] diff --git a/docs/.vitepress/config.js b/docs/.vitepress/config.js index 4ac3e38..9ac4093 100644 --- a/docs/.vitepress/config.js +++ b/docs/.vitepress/config.js @@ -4,18 +4,27 @@ export default { base: '/agentkit-sdk-python/', head: [ - ['link', { rel: 'icon', href: '/favicon.ico' }] + ['link', { rel: 'icon', href: '/favicon.ico' }], ], - + themeConfig: { logo: '/logo.png', - nav: [ - { text: '首页', link: '/' } + socialLinks: [ + { icon: 'github', link: 'https://github.com/volcengine/agentkit-sdk-python' }, ], + footer: { + message: 'Released under the Apache-2.0 License.', + copyright: 'Copyright © 2026 Volcengine', + }, + + search: { + provider: 'local', + }, + sidebar: { - '/content/1.introduction/': [ + '/': [ { text: '📖 概述', collapsed: false, @@ -23,8 +32,8 @@ export default { { text: 'AgentKit', link: '/content/1.introduction/1.overview' }, { text: '安装指南', link: '/content/1.introduction/2.installation' }, { text: '快速开始', link: '/content/1.introduction/3.quickstart' }, - { text: 'Troubleshooting', link: '/content/1.introduction/4.troubleshooting' } - ] + { text: 'Troubleshooting', link: '/content/1.introduction/4.troubleshooting' }, + ], }, { text: '⚡ CLI', @@ -32,543 +41,173 @@ export default { items: [ { text: 'CLI 概览', link: '/content/2.agentkit-cli/1.overview' }, { text: '命令详解', link: '/content/2.agentkit-cli/2.commands' }, - { text: '配置文件说明', link: '/content/2.agentkit-cli/3.configurations' } - ] - }, - { - text: '🔧 SDK', - collapsed: true, - items: [ - { text: 'SDK 概览', link: '/content/3.agentkit-sdk/1.overview' }, - { text: 'Anotation 使用指南', link: '/content/3.agentkit-sdk/2.annotation' } - ] - }, - { - text: '🚀 Runtime', - collapsed: true, - items: [ - { text: 'Runtime 快速开始', link: '/content/4.runtime/1.runtime_quickstart.md' } - ] - }, - { - text: '🛠️ Tools', - collapsed: true, - items: [ - { text: 'Tools 快速开始', link: '/content/5.tools/1.sandbox_quickstart' } - ] - }, - { - text: '💾 Memory', - collapsed: true, - items: [ - { text: 'Memory 快速开始', link: '/content/6.memory/1.memory_quickstart' } - ] - }, - { - text: '📚 Knowledge', - collapsed: true, - items: [ - { text: 'Knowledge 快速开始', link: '/content/7.knowledge/1.knowledge_quickstart' } - ] - }, - { - text: '🔌 MCP', - collapsed: true, - items: [ - { text: 'MCP 概览', link: '/content/8.mcp/1.overview' }, - { text: 'MCP 快速开始', link: '/content/8.mcp/2.mcp_quickstart' } - ] - } - ], - - '/content/2.agentkit-cli/': [ - { - text: '📖 概述', - collapsed: true, - items: [ - { text: 'AgentKit', link: '/content/1.introduction/1.overview' }, - { text: '安装指南', link: '/content/1.introduction/2.installation' }, - { text: '快速开始', link: '/content/1.introduction/3.quickstart' }, - { text: 'Troubleshooting', link: '/content/1.introduction/4.troubleshooting' } - ] - }, - { - text: '⚡ CLI', - collapsed: false, - items: [ - { text: 'CLI 概览', link: '/content/2.agentkit-cli/1.overview' }, - { text: '命令详解', link: '/content/2.agentkit-cli/2.commands' }, - { text: '配置文件说明', link: '/content/2.agentkit-cli/3.configurations' } - ] + { text: '配置文件说明', link: '/content/2.agentkit-cli/3.configurations' }, + { text: 'Logging', link: '/content/2.agentkit-cli/4.logging' }, + ], }, { text: '🔧 SDK', collapsed: true, items: [ { text: 'SDK 概览', link: '/content/3.agentkit-sdk/1.overview' }, - { text: 'Anotation 使用指南', link: '/content/3.agentkit-sdk/2.annotation' } - ] - }, - { - text: '🚀 Runtime', - collapsed: true, - items: [ - { text: 'Runtime 快速开始', link: '/content/4.runtime/1.runtime_quickstart.md' } - ] - }, - { - text: '🛠️ Tools', - collapsed: true, - items: [ - { text: 'Tools 快速开始', link: '/content/5.tools/1.sandbox_quickstart' } - ] - }, - { - text: '💾 Memory', - collapsed: true, - items: [ - { text: 'Memory 快速开始', link: '/content/6.memory/1.memory_quickstart' } - ] - }, - { - text: '📚 Knowledge', - collapsed: true, - items: [ - { text: 'Knowledge 快速开始', link: '/content/7.knowledge/1.knowledge_quickstart' } - ] - }, - { - text: '🔌 MCP', - collapsed: true, - items: [ - { text: 'MCP 概览', link: '/content/8.mcp/1.overview' }, - { text: 'MCP 快速开始', link: '/content/8.mcp/2.mcp_quickstart' } - ] - } - ], - - '/content/3.agentkit-sdk/': [ - { - text: '📖 概述', - collapsed: true, - items: [ - { text: 'AgentKit', link: '/content/1.introduction/1.overview' }, - { text: '安装指南', link: '/content/1.introduction/2.installation' }, - { text: '快速开始', link: '/content/1.introduction/3.quickstart' }, - { text: 'Troubleshooting', link: '/content/1.introduction/4.troubleshooting' } - ] - }, - { - text: '⚡ CLI', - collapsed: true, - items: [ - { text: 'CLI 概览', link: '/content/2.agentkit-cli/1.overview' }, - { text: '命令详解', link: '/content/2.agentkit-cli/2.commands' }, - { text: '配置文件说明', link: '/content/2.agentkit-cli/3.configurations' } - ] - }, - { - text: '🔧 SDK', - collapsed: false, - items: [ - { text: 'SDK 概览', link: '/content/3.agentkit-sdk/1.overview' }, - { text: 'Anotation 使用指南', link: '/content/3.agentkit-sdk/2.annotation' } - ] + { text: 'Annotation 使用指南', link: '/content/3.agentkit-sdk/2.annotation' }, + ], }, { text: '🚀 Runtime', collapsed: true, items: [ - { text: 'Runtime 快速开始', link: '/content/4.runtime/1.runtime_quickstart.md' } - ] + { text: 'Runtime 快速开始', link: '/content/4.runtime/1.runtime_quickstart' }, + ], }, { text: '🛠️ Tools', collapsed: true, items: [ - { text: 'Tools 快速开始', link: '/content/5.tools/1.sandbox_quickstart' } - ] + { text: 'Tools 快速开始', link: '/content/5.tools/1.sandbox_quickstart' }, + ], }, { text: '💾 Memory', collapsed: true, items: [ - { text: 'Memory 快速开始', link: '/content/6.memory/1.memory_quickstart' } - ] + { text: 'Memory 快速开始', link: '/content/6.memory/1.memory_quickstart' }, + ], }, { text: '📚 Knowledge', collapsed: true, items: [ - { text: 'Knowledge 快速开始', link: '/content/7.knowledge/1.knowledge_quickstart' } - ] + { text: 'Knowledge 快速开始', link: '/content/7.knowledge/1.knowledge_quickstart' }, + ], }, { text: '🔌 MCP', collapsed: true, items: [ { text: 'MCP 概览', link: '/content/8.mcp/1.overview' }, - { text: 'MCP 快速开始', link: '/content/8.mcp/2.mcp_quickstart' } - ] - } - ], - - '/content/4.runtime/': [ - { - text: '📖 概述', - collapsed: true, - items: [ - { text: 'AgentKit', link: '/content/1.introduction/1.overview' }, - { text: '安装指南', link: '/content/1.introduction/2.installation' }, - { text: '快速开始', link: '/content/1.introduction/3.quickstart' }, - { text: 'Troubleshooting', link: '/content/1.introduction/4.troubleshooting' } - ] - }, - { - text: '⚡ CLI', - collapsed: true, - items: [ - { text: 'CLI 概览', link: '/content/2.agentkit-cli/1.overview' }, - { text: '命令详解', link: '/content/2.agentkit-cli/2.commands' }, - { text: '配置文件说明', link: '/content/2.agentkit-cli/3.configurations' } - ] - }, - { - text: '🔧 SDK', - collapsed: true, - items: [ - { text: 'SDK 概览', link: '/content/3.agentkit-sdk/1.overview' }, - { text: 'Anotation 使用指南', link: '/content/3.agentkit-sdk/2.annotation' } - ] - }, - { - text: '🚀 Runtime', - collapsed: false, - items: [ - { text: 'Runtime 快速开始', link: '/content/4.runtime/1.runtime_quickstart.md' } - ] - }, - { - text: '🛠️ Tools', - collapsed: true, - items: [ - { text: 'Tools 快速开始', link: '/content/5.tools/1.sandbox_quickstart' } - ] - }, - { - text: '💾 Memory', - collapsed: true, - items: [ - { text: 'Memory 快速开始', link: '/content/6.memory/1.memory_quickstart' } - ] - }, - { - text: '📚 Knowledge', - collapsed: true, - items: [ - { text: 'Knowledge 快速开始', link: '/content/7.knowledge/1.knowledge_quickstart' } - ] + { text: 'MCP 快速开始', link: '/content/8.mcp/2.mcp_quickstart' }, + ], }, - { - text: '🔌 MCP', - collapsed: true, - items: [ - { text: 'MCP 概览', link: '/content/8.mcp/1.overview' }, - { text: 'MCP 快速开始', link: '/content/8.mcp/2.mcp_quickstart' } - ] - } ], - '/content/5.tools/': [ - { - text: '📖 概述', - collapsed: true, - items: [ - { text: 'AgentKit', link: '/content/1.introduction/1.overview' }, - { text: '安装指南', link: '/content/1.introduction/2.installation' }, - { text: '快速开始', link: '/content/1.introduction/3.quickstart' }, - { text: 'Troubleshooting', link: '/content/1.introduction/4.troubleshooting' } - ] - }, - { - text: '⚡ CLI', - collapsed: true, - items: [ - { text: 'CLI 概览', link: '/content/2.agentkit-cli/1.overview' }, - { text: '命令详解', link: '/content/2.agentkit-cli/2.commands' }, - { text: '配置文件说明', link: '/content/2.agentkit-cli/3.configurations' } - ] - }, - { - text: '🔧 SDK', - collapsed: true, - items: [ - { text: 'SDK 概览', link: '/content/3.agentkit-sdk/1.overview' }, - { text: 'Anotation 使用指南', link: '/content/3.agentkit-sdk/2.annotation' } - ] - }, - { - text: '🚀 Runtime', - collapsed: true, - items: [ - { text: 'Runtime 快速开始', link: '/content/4.runtime/1.runtime_quickstart.md' } - ] - }, - { - text: '🛠️ Tools', - collapsed: false, - items: [ - { text: 'Tools 快速开始', link: '/content/5.tools/1.sandbox_quickstart' } - ] - }, - { - text: '💾 Memory', - collapsed: true, - items: [ - { text: 'Memory 快速开始', link: '/content/6.memory/1.memory_quickstart' } - ] - }, - { - text: '📚 Knowledge', - collapsed: true, - items: [ - { text: 'Knowledge 快速开始', link: '/content/7.knowledge/1.knowledge_quickstart' } - ] - }, - { - text: '🔌 MCP', - collapsed: true, - items: [ - { text: 'MCP 概览', link: '/content/8.mcp/1.overview' }, - { text: 'MCP 快速开始', link: '/content/8.mcp/2.mcp_quickstart' } - ] - } - ], - '/content/6.memory/': [ - { - text: '📖 概述', - collapsed: true, - items: [ - { text: 'AgentKit', link: '/content/1.introduction/1.overview' }, - { text: '安装指南', link: '/content/1.introduction/2.installation' }, - { text: '快速开始', link: '/content/1.introduction/3.quickstart' }, - { text: 'Troubleshooting', link: '/content/1.introduction/4.troubleshooting' } - ] - }, - { - text: '⚡ CLI', - collapsed: true, - items: [ - { text: 'CLI 概览', link: '/content/2.agentkit-cli/1.overview' }, - { text: '命令详解', link: '/content/2.agentkit-cli/2.commands' }, - { text: '配置文件说明', link: '/content/2.agentkit-cli/3.configurations' } - ] - }, - { - text: '🔧 SDK', - collapsed: true, - items: [ - { text: 'SDK 概览', link: '/content/3.agentkit-sdk/1.overview' }, - { text: 'Anotation 使用指南', link: '/content/3.agentkit-sdk/2.annotation' } - ] - }, - { - text: '🚀 Runtime', - collapsed: true, - items: [ - { text: 'Runtime 快速开始', link: '/content/4.runtime/1.runtime_quickstart.md' } - ] - }, - { - text: '🛠️ Tools', - collapsed: true, - items: [ - { text: 'Tools 快速开始', link: '/content/5.tools/1.sandbox_quickstart' } - ] - }, - { - text: '💾 Memory', - collapsed: false, - items: [ - { text: 'Memory 快速开始', link: '/content/6.memory/1.memory_quickstart' } - ] - }, - { - text: '📚 Knowledge', - collapsed: true, - items: [ - { text: 'Knowledge 快速开始', link: '/content/7.knowledge/1.knowledge_quickstart' } - ] - }, - { - text: '🔌 MCP', - collapsed: true, - items: [ - { text: 'MCP 概览', link: '/content/8.mcp/1.overview' }, - { text: 'MCP 快速开始', link: '/content/8.mcp/2.mcp_quickstart' } - ] - } - ], - '/content/7.knowledge/': [ - { - text: '📖 概述', - collapsed: true, - items: [ - { text: 'AgentKit', link: '/content/1.introduction/1.overview' }, - { text: '安装指南', link: '/content/1.introduction/2.installation' }, - { text: '快速开始', link: '/content/1.introduction/3.quickstart' }, - { text: 'Troubleshooting', link: '/content/1.introduction/4.troubleshooting' } - ] - }, - { - text: '⚡ CLI', - collapsed: true, - items: [ - { text: 'CLI 概览', link: '/content/2.agentkit-cli/1.overview' }, - { text: '命令详解', link: '/content/2.agentkit-cli/2.commands' }, - { text: '配置文件说明', link: '/content/2.agentkit-cli/3.configurations' } - ] - }, - { - text: '🔧 SDK', - collapsed: true, - items: [ - { text: 'SDK 概览', link: '/content/3.agentkit-sdk/1.overview' }, - { text: 'Anotation 使用指南', link: '/content/3.agentkit-sdk/2.annotation' } - ] - }, - { - text: '🚀 Runtime', - collapsed: true, - items: [ - { text: 'Runtime 快速开始', link: '/content/4.runtime/1.runtime_quickstart.md' } - ] - }, - { - text: '🛠️ Tools', - collapsed: true, - items: [ - { text: 'Tools 快速开始', link: '/content/5.tools/1.sandbox_quickstart' } - ] - }, - { - text: '💾 Memory', - collapsed: true, - items: [ - { text: 'Memory 快速开始', link: '/content/6.memory/1.memory_quickstart' } - ] - }, - { - text: '📚 Knowledge', - collapsed: false, - items: [ - { text: 'Knowledge 快速开始', link: '/content/7.knowledge/1.knowledge_quickstart' } - ] - }, - { - text: '🔌 MCP', - collapsed: true, - items: [ - { text: 'MCP 概览', link: '/content/8.mcp/1.overview' }, - { text: 'MCP 快速开始', link: '/content/8.mcp/2.mcp_quickstart' } - ] - } - ], - '/content/8.mcp/': [ - { - text: '📖 概述', - collapsed: true, - items: [ - { text: 'AgentKit', link: '/content/1.introduction/1.overview' }, - { text: '安装指南', link: '/content/1.introduction/2.installation' }, - { text: '快速开始', link: '/content/1.introduction/3.quickstart' }, - { text: 'Troubleshooting', link: '/content/1.introduction/4.troubleshooting' } - ] - }, - { - text: '⚡ CLI', - collapsed: true, - items: [ - { text: 'CLI 概览', link: '/content/2.agentkit-cli/1.overview' }, - { text: '命令详解', link: '/content/2.agentkit-cli/2.commands' }, - { text: '配置文件说明', link: '/content/2.agentkit-cli/3.configurations' } - ] - }, - { - text: '🔧 SDK', - collapsed: true, - items: [ - { text: 'SDK 概览', link: '/content/3.agentkit-sdk/1.overview' }, - { text: 'Anotation 使用指南', link: '/content/3.agentkit-sdk/2.annotation' } - ] - }, - { - text: '🚀 Runtime', - collapsed: true, - items: [ - { text: 'Runtime 快速开始', link: '/content/4.runtime/1.runtime_quickstart.md' } - ] - }, - { - text: '🛠️ Tools', - collapsed: true, - items: [ - { text: 'Tools 快速开始', link: '/content/5.tools/1.sandbox_quickstart' } - ] - }, - { - text: '💾 Memory', - collapsed: true, - items: [ - { text: 'Memory 快速开始', link: '/content/6.memory/1.memory_quickstart' } - ] - }, - { - text: '📚 Knowledge', - collapsed: true, - items: [ - { text: 'Knowledge 快速开始', link: '/content/7.knowledge/1.knowledge_quickstart' } - ] - }, - { - text: '🔌 MCP', - collapsed: false, - items: [ - { text: 'MCP 概览', link: '/content/8.mcp/1.overview' }, - { text: 'MCP 快速开始', link: '/content/8.mcp/2.mcp_quickstart' } - ] - } - ] }, - - socialLinks: [ - { icon: 'github', link: 'https://github.com/volcengine/agentkit-sdk-python' } - ], - - footer: { - message: 'Released under the Apache-2.0 License.', - copyright: 'Copyright © 2025 Volcengine' - }, - - search: { - provider: 'local' - }, - + outline: { level: [2, 3], - label: '目录' + label: '目录', }, - + docFooter: { prev: '上一页', - next: '下一页' + next: '下一页', }, - + lastUpdated: { text: '最后更新于', formatOptions: { dateStyle: 'short', - timeStyle: 'medium' - } - } - } -} \ No newline at end of file + timeStyle: 'medium', + }, + }, + }, + + locales: { + root: { + label: '简体中文', + lang: 'zh-CN', + themeConfig: { + nav: [{ text: '首页', link: '/' }], + }, + }, + en: { + label: 'English', + lang: 'en-US', + themeConfig: { + nav: [{ text: 'Home', link: '/en/' }], + sidebar: { + '/en/': [ + { + text: '📖 Overview', + collapsed: false, + items: [ + { text: 'AgentKit', link: '/en/content/1.introduction/1.overview' }, + { text: 'Installation', link: '/en/content/1.introduction/2.installation' }, + { text: 'Quick Start', link: '/en/content/1.introduction/3.quickstart' }, + { text: 'Troubleshooting', link: '/en/content/1.introduction/4.troubleshooting' }, + ], + }, + { + text: '⚡ CLI', + collapsed: true, + items: [ + { text: 'CLI Overview', link: '/en/content/2.agentkit-cli/1.overview' }, + { text: 'Commands', link: '/en/content/2.agentkit-cli/2.commands' }, + { text: 'Configuration', link: '/en/content/2.agentkit-cli/3.configurations' }, + { text: 'Logging', link: '/en/content/2.agentkit-cli/4.logging' }, + ], + }, + { + text: '🔧 SDK', + collapsed: true, + items: [ + { text: 'SDK Overview', link: '/en/content/3.agentkit-sdk/1.overview' }, + { text: 'Annotations', link: '/en/content/3.agentkit-sdk/2.annotation' }, + ], + }, + { + text: '🚀 Runtime', + collapsed: true, + items: [ + { text: 'Runtime Quickstart', link: '/en/content/4.runtime/1.runtime_quickstart' }, + ], + }, + { + text: '🛠️ Tools', + collapsed: true, + items: [ + { text: 'Tools Quickstart', link: '/en/content/5.tools/1.sandbox_quickstart' }, + ], + }, + { + text: '💾 Memory', + collapsed: true, + items: [ + { text: 'Memory Quickstart', link: '/en/content/6.memory/1.memory_quickstart' }, + ], + }, + { + text: '📚 Knowledge', + collapsed: true, + items: [ + { text: 'Knowledge Quickstart', link: '/en/content/7.knowledge/1.knowledge_quickstart' }, + ], + }, + { + text: '🔌 MCP', + collapsed: true, + items: [ + { text: 'MCP Overview', link: '/en/content/8.mcp/1.overview' }, + { text: 'MCP Quickstart', link: '/en/content/8.mcp/2.mcp_quickstart' }, + ], + }, + ], + }, + outline: { + level: [2, 3], + label: 'On this page', + }, + docFooter: { + prev: 'Previous page', + next: 'Next page', + }, + lastUpdated: { + text: 'Last updated at', + formatOptions: { + dateStyle: 'short', + timeStyle: 'medium', + }, + }, + }, + }, + }, +} diff --git a/docs/README.md b/docs/README.md index 1551a20..98bb053 100644 --- a/docs/README.md +++ b/docs/README.md @@ -16,6 +16,7 @@ npm install npm run docs:dev ``` +访问 `http://localhost:5173` 查看文档站点。 ### 构建生产版本 ```bash diff --git a/docs/content/2.agentkit-cli/3.configurations.md b/docs/content/2.agentkit-cli/3.configurations.md index 720e680..425e16e 100644 --- a/docs/content/2.agentkit-cli/3.configurations.md +++ b/docs/content/2.agentkit-cli/3.configurations.md @@ -236,8 +236,6 @@ defaults: ```bash # 3) 环境变量(临时覆盖) -export AGENTKIT_CLOUD_PROVIDER=byteplus -# 兼容别名 export CLOUD_PROVIDER=byteplus ``` diff --git a/docs/en/content/1.introduction/1.overview.md b/docs/en/content/1.introduction/1.overview.md new file mode 100644 index 0000000..2177cea --- /dev/null +++ b/docs/en/content/1.introduction/1.overview.md @@ -0,0 +1,36 @@ +# AgentKit + +## Product Positioning + +AgentKit is an enterprise-grade AI Agent development platform launched by Volcengine. It provides developers with a complete solution for building, deploying, and operating Agents. Through a standardized development toolchain and cloud-native infrastructure, the platform significantly lowers the barrier to developing and deploying complex intelligent agent applications. + +## Key Advantages + +- **Declarative application definition**: Define the core components and configuration of an agent application through a concise YAML file, enabling “define once, run anywhere”. +- **Modular and extensible**: Includes rich built-in modules such as **Tool**, **Memory**, and **Knowledge**, and provides standardized interfaces to make customization and extension easy. +- **Cloud-native deployment**: Seamlessly integrates with **AgentKit Platform**, supporting one-click deployment to the cloud, with elastic scaling, continuous integration, and high availability guarantees. +- **Multi-agent collaboration**: Supports building complex systems where multiple **Agents** work together, enabling task decomposition, collaboration, and aggregation, and supports the A2A protocol Agent. +- **Full lifecycle management**: Provides a complete `agentkit` CLI toolchain covering project initialization, local debugging, cloud deployment, and online operations. +- **Multi-language support**: Supports Python and Golang development to meet different tech stack needs. +- **Rich project templates**: Provides multiple prebuilt templates, including basic apps, streaming output, A2A protocol, etc., to kickstart development quickly. + +## Architecture Concept + +AgentKit’s core design concept is to separate the **definition** and **execution** of an **Agent App**. + +- **Application definition (Definition)**: Developers declaratively define application metadata, dependencies, runtime environment, and required platform services (such as knowledge base and memory modules) via the `agentkit.yaml` file. +- **Application execution (Execution)**: The `agentkit` CLI and **AgentKit Platform** parse the definition file and automatically complete a series of tedious tasks such as environment preparation, code packaging, image building, continuous integration, and cloud deployment. + +This separation allows developers to focus on implementing business logic while AgentKit handles complex engineering problems, enabling agile development and fast production delivery. + +## Applicable Scenarios + +- **Intelligent Q&A bots**: Quickly build knowledge-base-integrated intelligent Q&A services. +- **Automated workflows**: Create automation flows that can execute a series of tasks (such as sending emails, generating reports, calling APIs). +- **Complex data analysis**: Build data analysis **Agents** that understand user intent, query databases, analyze data, and generate visual reports. +- **Multi-agent systems**: Design and deploy systems where multiple **Agents** collaborate to complete complex tasks, such as a “researcher–analyst–reporter” pattern. + +## Get Started + +- **[Install AgentKit](./2.installation.md)**: Learn how to install AgentKit. +- **[Quick Start](./3.quickstart.md)**: Use a simple example to quickly experience the full process from development to deployment. diff --git a/docs/en/content/1.introduction/2.installation.md b/docs/en/content/1.introduction/2.installation.md new file mode 100644 index 0000000..e0a45de --- /dev/null +++ b/docs/en/content/1.introduction/2.installation.md @@ -0,0 +1,151 @@ +# Install AgentKit + +This guide will walk you through installing AgentKit and completing the basic configuration. + +## Environment Requirements + +- **Python version**: 3.10 or later +- **Operating system**: Linux, macOS +- **Package manager**: `uv` or `pip` recommended + +We strongly recommend installing AgentKit in a Python virtual environment to avoid conflicts with system packages. + +## Installation Methods + +### Method 1: Install with pip + +#### Stable Version + +Recommended for production deployments: + +```bash +pip install agentkit-sdk-python +``` + +#### Development Version + +Includes the latest features and fixes: + +```bash +pip install --pre agentkit-sdk-python +``` + +#### Install a Specific Version + +Install a specific version: + +```bash +pip install agentkit-sdk-python==0.1.7 +``` + +### Method 2: Install with uv (Recommended) + +We recommend using `uv` to manage virtual environments and dependencies. + +```bash +# install uv +curl -LsSf https://astral.sh/uv/install.sh | sh + +# Initialize uv environment +uv init --no-workspace + +# Specify Python version for the environment +uv venv --python 3.12 + +# Install AgentKit using uv +uv add agentkit-sdk-python + +# Install veadk (recommended for local debugging) +uv add veadk-python + +# Activate the virtual environment +source .venv/bin/activate +``` + +### Method 3: Install from Source + +For developers and customization scenarios: + +#### Install from the official Github repository + +```bash +# clone repo +git clone git@github.com:volcengine/agentkit-sdk-python.git + +cd agentkit-sdk-python + +# we use uv to build this project +uv venv --python 3.12 + +# only install necessary requirements +uv sync + +# install agentkit-sdk-python with editable mode +uv pip install -e . + +# Activate the virtual environment +source .venv/bin/activate +``` + +If you prefer `pip` and `venv`, you can also run: + +```bash +# Create virtual environment +python3 -m venv .venv + +# Activate virtual environment +source .venv/bin/activate + +# Install AgentKit +pip install agentkit-sdk-python +``` + +## Verify Installation + +After installation, run the following command to verify that the `agentkit` CLI is available: + +```bash +agentkit --version +``` + +If the version is printed successfully, AgentKit has been installed. + +## Authentication Configuration + +Before using the `agentkit` CLI to interact with AgentKit Platform, you need to configure access credentials (AK/SK). + +### Recommended: Use global configuration + +Use AgentKit’s global configuration feature to store your credentials securely: + +```bash +# Initialize global configuration +agentkit config --global --init + +# Set your access credentials +agentkit config --global --set volcengine.access_key="YOUR_ACCESS_KEY" +agentkit config --global --set volcengine.secret_key="YOUR_SECRET_KEY" + +# Verify configuration +agentkit config --global --show +``` + +This stores credentials securely in `~/.agentkit/config.yaml`, avoiding exposure of sensitive information in shell history. + +### Environment variables (for development debugging) + +For temporary development debugging, you can set environment variables: + +```bash +export VOLCENGINE_ACCESS_KEY="YOUR_ACCESS_KEY" +export VOLCENGINE_SECRET_KEY="YOUR_SECRET_KEY" +``` + +⚠️ **Note**: For security reasons, it is not recommended to add `export` commands containing sensitive information to shell configuration files (such as `~/.bashrc` or `~/.zshrc`), because this may cause credential leakage. + +## Next Steps + +You have now installed and configured AgentKit, and you can start building your first Agent. + +- **[Quick Start](./3.quickstart.md)**: Follow our quick start guide to experience the full workflow from development to deployment. +- **[Troubleshooting](./4.troubleshooting.md)**: If you run into issues, see the troubleshooting guide. diff --git a/docs/en/content/1.introduction/3.quickstart.md b/docs/en/content/1.introduction/3.quickstart.md new file mode 100644 index 0000000..ffa75bb --- /dev/null +++ b/docs/en/content/1.introduction/3.quickstart.md @@ -0,0 +1,188 @@ +# Quick Start + +This guide will walk you through developing a simple **Agent** using the “Basic Agent App” template, and quickly experiencing the full **AgentKit** workflow from development and deployment to testing. AgentKit provides multiple templates, including basic apps, streaming output, and A2A protocol, and supports both Python and Golang development. + +## Preparation + +### 1. Obtain Volcengine access keys (AK/SK) + +First, you need a Volcengine account and to enable the **AgentKit** service. Please visit the [Volcengine Console](https://console.volcengine.com/) to complete registration and activation. + +Then, create and obtain access keys (AK/SK) on the [Access Control](https://console.volcengine.com/iam/keymanage) page. + +After obtaining them, set them as environment variables: + +```bash +export VOLCENGINE_ACCESS_KEY= +export VOLCENGINE_SECRET_KEY= +``` + +### 2. Obtain a model inference API Key (Optional) + +Your **Agent** usually needs to call a large language model (LLM) to provide core intelligence. **AgentKit Platform** supports multiple models from Volcengine Ark. Make sure you have enabled the [Volcengine Ark](https://console.volcengine.com/ark/region:ark+cn-beijing/overview) service and obtained the model inference **Endpoint** and **API Key**. + +- **Get the inference endpoint (Endpoint)**: On the Ark platform’s “Online Inference” page, you can select a preset inference endpoint or create a custom inference endpoint. + + ![Inference Endpoint](../../../public/images/select_or_create_model_endpoint.jpg) + +- **Get the API Key**: On the “API Key Management” page, select or create a new API Key. + + ![API Key Management](../../../public/images/model_apikey.jpg) + +Please record your **Endpoint ID** such as `ep-20250520174054-xxxxx` (it can also be a model ID such as `deepseek-v3-1-terminus`) and **API Key**. You will later configure them for the **Agent** via the environment variables `MODEL_AGENT_NAME` and `MODEL_AGENT_API_KEY`. + +> If you do not provide this information, **AgentKit Platform** will automatically inject a built-in `doubao-seed-1-6` model for you during cloud deployment. + +### 3. Local debugging credential configuration (Required for Local mode) + +If you plan to run and debug the Agent locally (Local mode), because the local environment cannot automatically inject cloud credentials, you **must** configure the access credentials manually; otherwise, the Agent will not be able to call the LLM. + +You can configure credentials in one of the following two ways: + +**Option 1: Configure Ark model credentials** + +Directly specify the model endpoint and API Key to use: + +```bash +# Set via --runtime_envs (-e) during config +agentkit config -e MODEL_AGENT_NAME= -e MODEL_AGENT_API_KEY= +``` + +**Option 2: Configure Volcengine access keys** + +If you configure Volcengine AK/SK, veADK will try to automatically obtain your model access permissions: + +```bash +# Set via --runtime_envs (-e) during config +agentkit config -e VOLCENGINE_ACCESS_KEY= -e VOLCENGINE_SECRET_KEY= +``` + +> **Note**: +> 1. In Local mode, directly `export`ing environment variables in the host shell does not take effect inside the container. You must use `agentkit config -e` to write them into `agentkit.yaml` under `runtime_envs`. +> 2. In Cloud mode, the Runtime automatically injects related credentials, and you usually do not need to manually configure the above environment variables. + +## Getting Started + +### Step 1: Install AgentKit + +Before you begin, ensure you have followed the [Install AgentKit](./2.installation.md) guide to complete installation of the `agentkit` CLI and environment configuration. + +### Step 2: Initialize a project + +Create a project directory and initialize your **Agent** app using `agentkit init`: + +```bash +mkdir simple-agent && cd simple-agent +agentkit init +``` + +After running, a list of available templates will be shown. Select template `1` (Basic Agent App). You can also specify a template directly using the `--template` parameter: + +```bash +# Use basic template +agentkit init --template basic + +# Use streaming output template +agentkit init --template basic_stream + +# List all available templates +agentkit init --list-templates +``` + +After the command runs, template code and config files will be generated in the current directory: + +```txt +. +├── agentkit.yaml # Core configuration file for the Agent. +├── requirements.txt # Python dependencies for the project. +└── simple_agent.py # Entry point for the Agent application. +``` + +### Step 3: Configure and deploy + +You can use `agentkit launch` to build and deploy the app to the cloud in one command. This command uses the configuration in `agentkit.yaml`. + +If you need custom configuration (for example, specify deployment region, image repository, or provide model keys), you can edit `agentkit.yaml` manually, or run `agentkit config` to generate configuration through an interactive wizard. + +```bash +agentkit config +``` + +The configuration wizard will guide you to complete the following settings: + +**General settings** (press Enter to use default values): +- **1.App name**: Agent app name (default is `simple_agent`, press Enter to accept) +- **2.Entry file**: App entry file (default is `simple_agent.py`) +- **3.App description**: App description (optional) +- **4.Programming language**: Python or Golang (default Python) +- **5.Dependency file**: default `requirements.txt` or `go.mod` +- **6.Common internal Runtime environment variables for Agent apps**: + - `MODEL_AGENT_NAME`: Ark model endpoint ID (optional) + - `MODEL_AGENT_API_KEY`: Ark model API Key (optional) +- **7.Deployment mode**: choose `cloud` (cloud build and deployment) + +**Cloud deployment settings**: +- **1.Service region**: default `cn-beijing` +- **2.Image tag**: default `{{timestamp}}`, will be rendered as a timestamp in the format 20251218154940 +- **3.CR image repository**: CLI will automatically generate the CR instance name, CR namespace, and CR repository name. Users can also specify manually (recommended to keep automatic). + +After configuration is complete, run the `launch` command to deploy with one click: + +```bash +agentkit launch +``` + +This command automatically completes the following steps: +1. Render Dockerfile +2. Create a project archive and upload it to TOS +3. Prepare CR (container image repository) resources +4. Create and run a Pipeline build +5. Deploy to the Runtime environment + +After a successful deployment, you will see output like: + +```bash +✅ Runtime created successfully: r-ye9j62wydcn****nhsoa, request_id: 20251120***************5344 +Waiting for Runtime to be Ready... +💡 Tip: Runtime is initializing, please be patient and do not interrupt the process +✅ Runtime status is Ready + Runtime status: Releasing ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 100% 0:01:23 +Endpoint: https://sd4fe31poh486****.apigateway-cn-beijing.volceapi.com +100% ▶ Deployment complete +✅ Successfully launched agent: https://sd4fe31poh486npgcaqq0.apigateway-cn-beijing.volceapi.com +Built image: agentkit-cli-21076x****-cn-beijing.cr.volces.com/agentkit/myapp:2025112017**** +Endpoint: https://sd4fe31poh486****.apigateway-cn-beijing.volceapi.com +``` + +> **Tip**: The first deployment usually takes about 2–3 minutes. Please be patient. + +## Use the Agent + +### Invoke the Agent + +Test the Agent with the `invoke` command: + +```bash +agentkit invoke "Hello" +``` + +If you see output similar to the following, congratulations—your first **Agent** is running successfully! + +```text +(agentkit) test@localhost:~/workspace/simple-agent$ agentkit invoke "Hello" +Invoking agent... +Using default headers: {'user_id': 'agentkit_user', 'session_id': 'agentkit_sample_session'} +✅ Invocation successful +📝 Response: +Hello! I am an AI assistant developed by the **** team, specializing in data science (information gathering, data analysis, etc.), document writing (writing multi-chapter articles, in-depth research reports), and software development (creating websites/applications, solving coding problems, etc.). +If you have any specific needs, I'd be happy to help! +``` + +## Next Steps + +Congratulations on completing development and deployment of your first **Agent**! + +Next, you can: +- Explore other app templates (MCP, A2A, etc.) +- Integrate Platform services like Memory, Knowledge, and Tools to build more powerful **Agents** +- Use commands like `agentkit memory`, `agentkit knowledge`, and `agentkit tools` to manage platform services diff --git a/docs/en/content/1.introduction/4.troubleshooting.md b/docs/en/content/1.introduction/4.troubleshooting.md new file mode 100644 index 0000000..b3b2380 --- /dev/null +++ b/docs/en/content/1.introduction/4.troubleshooting.md @@ -0,0 +1,160 @@ +# Troubleshooting Guide + +This guide is intended to help you diagnose and resolve common issues you may encounter when using AgentKit. If you cannot find a solution here, feel free to contact us via [GitHub Issues](https://github.com/volcengine/agentkit-sdk-python/issues). + +## Installation Issues + +### 1. `agentkit` command not found + +- **Symptom**: When running the `agentkit` command in the terminal, the system reports `command not found`. +- **Cause**: This is usually because the executable path installed by `pip` has not been added to the system `PATH` environment variable. +- **Solution**: + - Confirm install location: Run `pip show agentkit-sdk-python` or `uv pip show agentkit-sdk-python` and find the install path indicated by the `Location` field. + - Locate the executable: Under the install path’s `bin` directory (for example `.../site-packages/bin`), you should be able to find the `agentkit` executable. + - Add to PATH: Add the absolute path of this `bin` directory to your `~/.bashrc`, `~/.zshrc`, or other shell configuration files. + ```bash + export PATH="/path/to/your/python/bin:$PATH" + ``` + - Reload configuration: Run `source ~/.bashrc` or restart the terminal to apply the changes. + +### 2. Dependency conflicts + +- **Symptom**: When installing `agentkit-sdk-python`, `pip` reports dependency version conflicts. +- **Cause**: Your Python environment may already contain library versions that are incompatible with AgentKit. +- **Solution**: + - Use a virtual environment (recommended): We strongly recommend using `uv` or `venv` to create a clean virtual environment in your project to avoid conflicts with system-level Python packages. + ```bash + uv venv + source .venv/bin/activate + uv pip install agentkit-sdk-python + ``` + - Clean and reinstall: If you must use the existing environment, uninstall and reinstall: + ```bash + pip uninstall agentkit-sdk-python + pip install agentkit-sdk-python + ``` +## Configuration Issues + +### 1. Environment variables not taking effect + +- **Symptom**: Prompts indicate it cannot connect to AgentKit Platform or authentication fails. +- **Cause**: Required environment variables may not have been passed in, or incorrect environment variable names were used. +- **Solution**: + - Confirm required environment variables are set + ```bash + echo $VOLCENGINE_ACCESS_KEY + echo $VOLCENGINE_SECRET_KEY + ``` + - Ensure there are no extra spaces or quotes + - Re-export the environment variables in the current shell session + +### 2. Configuration file format error + +- **Symptom**: When running `agentkit launch`, it reports configuration file parsing failure. +- **Cause**: File format issues +- **Solution**: + - Check whether `agentkit.yaml` is formatted correctly (pay attention to indentation) + - Re-run `agentkit config` to generate configuration + +## Deployment Issues + +### 1. CR creation failed + +- **Symptom**: +``` +CreateRegistry: QuotaExceeded.Registry The quota of Registry is exceeded. +``` +- **Cause**: Insufficient account quota +- **Solution**: + - Number of CR instances exceeds the quota limit + - In `agentkit config`, configure it to use an existing CR instance name + - Or contact the administrator to increase quota + +### 2. Image build failed + +- **Symptom**: Pipeline build fails and reports dependency installation errors. +- **Cause**: Dependency installation failure +- **Solution**: + - Check whether dependencies in `requirements.txt` are correct + - Confirm dependency versions are compatible with Python 3.12 + - Check Pipeline logs for detailed error information (logs will be automatically downloaded to your local root directory; pay attention to prompts in the interactive UI and find a file named like pipeline_failed_****ff20ce223.log in the root directory) + +### 3. Runtime deployment timeout + +- **Symptom**: Runtime stays in `Releasing` state for a long time. +- **Cause**: The first deployment takes longer, or there may be insufficient resources. +- **Solution**: + - The first deployment usually takes 2–3 minutes; please be patient + - Use `agentkit status` to check status + - If it is still not ready after 5 minutes, resources may be insufficient; try `agentkit destroy` and then redeploy + +### 4. Runtime status abnormal + +- **Symptom**: Runtime status is `Failed` or `Error`. +- **Cause**: Internal Runtime exception +- **Solution**: + - Check whether environment variable configuration is correct (especially the model API Key) + - Check logs in the AgentKit Platform console + - Confirm the application code has no startup errors + - Try cleaning up with `agentkit destroy` and redeploying + +## Invocation Issues + +### 1. invoke failed + +- **Symptom**: When running `agentkit invoke`, it reports connection failure or timeout. +- **Cause**: Network issues or incorrect Endpoint configuration +- **Solution**: + - Use `agentkit status` to confirm Runtime status is `Ready` + - Check network connectivity + - Confirm the Endpoint address is correct + - Check firewall or proxy settings + +### 2. Model invocation failed + +- **Symptom**: The Agent returns an error indicating model access failure. +- **Cause**: Incorrect model API Key configuration or exhausted model quota +- **Solution**: + - Confirm the Ark model API Key configuration is correct + - Check whether the endpoint ID is valid + - Confirm whether model quota has been exhausted + - Log in to the Ark platform to check API Key permissions + +## Permission Issues + +### 1. AK/SK authentication failed + +- **Symptom**: Reports `InvalidAccessKeyId` or `SignatureDoesNotMatch`. +- **Cause**: Incorrect AK/SK configuration or insufficient permissions +- **Solution**: + - Confirm AK/SK is correct and valid + - Check whether you have access permissions for the AgentKit service + - Confirm AK/SK has not been disabled or expired + - Contact the administrator to assign the required permissions + +### 2. Resource access denied + +- **Symptom**: Reports `AccessDenied` or insufficient permissions. +- **Cause**: The account does not have enough permissions to perform the operation +- **Solution**: + - Confirm the account has the required permissions for the relevant resources + - Check IAM role configuration + - Contact the administrator to grant necessary permissions + +## Getting Help + +If the above solutions cannot resolve your issue, please: + +1. **Check logs**: + - Local logs: Check command line output + - Platform logs: Visit the AgentKit console to view detailed logs + +2. **Contact support**: + - Provide detailed error information and logs + - Describe reproduction steps + - Attach relevant configuration files (be sure to redact sensitive data) + - Contact Volcengine technical support + +3. **Read the docs**: + - [Volcengine Official Documentation](https://www.volcengine.com/docs/86681/1844878) + - [Official website FAQ](https://www.volcengine.com/docs/86681/2085690?lang=zh) diff --git a/docs/en/content/2.agentkit-cli/1.overview.md b/docs/en/content/2.agentkit-cli/1.overview.md new file mode 100644 index 0000000..9001a14 --- /dev/null +++ b/docs/en/content/2.agentkit-cli/1.overview.md @@ -0,0 +1,179 @@ +# AgentKit CLI Overview + +**AgentKit CLI** is a powerful command-line tool designed for developers to simplify and accelerate the full lifecycle of **Agent** application development, deployment, and management. Whether you’re rapidly prototyping locally or deploying at scale in production, the `agentkit` command delivers a consistent and efficient developer experience. + +## Key Advantages + +- **Declarative configuration**: Manage all configuration through a single `agentkit.yaml` file—clear, portable, and easy to version-control. +- **Multi-environment deployment**: Seamlessly supports three modes—local development, hybrid deployment, and fully cloud deployment—to fit different scenarios. +- **One-command workflows**: High-level commands like `agentkit launch` combine multiple steps (build, deploy, etc.) into one, dramatically improving efficiency. +- **Templated projects**: Built-in application templates help you bootstrap quickly without starting from scratch. +- **Smart interactivity**: Interactive wizards such as `agentkit config` guide you through setup and reduce the learning curve. + +## Main Commands + +The `agentkit` CLI provides a set of intuitive commands to manage your **Agent** applications: + +### Core Commands + +| Command | Description | +| :--- | :--- | +| `agentkit init` | Initialize a new **Agent** project, with optional templates. | +| `agentkit config` | Configure `agentkit.yaml` via an interactive wizard. | +| `agentkit build` | Build your **Agent** application into a Docker image. | +| `agentkit deploy` | Deploy a built image to the specified environment (local or cloud). | +| `agentkit launch` | Build and deploy in one command—the most commonly used command during development. | +| `agentkit invoke` | Interact with a deployed **Agent** for quick testing. | +| `agentkit status` | View the **Agent** runtime status and endpoint. | +| `agentkit destroy` | Stop and destroy the **Agent** instance, releasing related resources. | + +### Platform Service Commands + +| Command | Description | +| :--- | :--- | +| `agentkit memory` | Manage AgentKit Memory collections. | +| `agentkit knowledge` | Manage AgentKit Knowledge bases. | +| `agentkit tools` | Manage AgentKit Tools and Sessions. | +| `agentkit runtime` | Manage AgentKit Runtime instances. | + +> Want detailed usage for each command? See [Command Reference](./2.commands.md). + +## Three Deployment Modes + +One of the core features of **AgentKit CLI** is its flexible deployment model, designed to adapt to different stages from development to production. + +### 1. Local Mode (`local`) + +Build and deploy on your local machine—ideal for fast development and debugging. + +- **Workflow**: `Source code` → `Local Docker build` → `Run local container` +- **Benefits**: Fast iteration, supports offline work, easy to debug directly. + +### 2. Cloud Mode (`cloud`) + +Fully host build and deployment on the **AgentKit Platform**—a best practice for production. + +- **Workflow**: `Source code` → `Cloud auto build` → `Cloud image registry` → `Production-grade Runtime` +- **Benefits**: No local Docker required, built-in observability, high environment consistency, secure and reliable. + +### 3. Hybrid Mode (`hybrid`) + +Build the image locally, then push it to the cloud **AgentKit Platform** for deployment. This combines local control with cloud capabilities. + +- **Workflow**: `Source code` → `Local Docker build` → `Upload to cloud image registry` → `Production-grade Runtime` +- **Benefits**: Balances local build flexibility with the stability of a cloud runtime—suitable for scenarios that require a custom build process. + +## Configuration File (`agentkit.yaml`) + +`agentkit.yaml` is the core of an **AgentKit** project. It defines all application configuration in a declarative manner. We strongly recommend managing this file with the `agentkit config` command. + +```yaml +# General configuration +common: + agent_name: my-agent + entry_point: app.py + language_version: '3.12' + launch_type: cloud # Define the default deployment mode + +# Mode-specific configuration +launch_types: + cloud: + region: cn-beijing + image_tag: latest + runtime_envs: + MODEL_API_KEY: "your-api-key" +``` + +> Want detailed explanations of all configuration options? See [Configuration Reference](./3.configurations.md). + +## Quick Start + +In just a few minutes, you can deploy your first **Agent**. + +```bash +# 1. Initialize a project (choose the Basic App template) +mkdir my-first-agent && cd my-first-agent +agentkit init my-first-agent + +# Or specify a particular template +agentkit init my-first-agent --template basic_stream # Streaming output template +agentkit init my-first-agent --template a2a # A2A protocol template + +# 2. Configure the app (via the interactive wizard) +agentkit config + +# 3. Deploy to the cloud in one command +agentkit launch + +# 4. Test your Agent +agentkit invoke "Hello!" + +# 5. Check runtime status +agentkit status + +# 6. Clean up resources (optional) +agentkit destroy +``` + +### Explore More Features + +```bash +# List available templates +agentkit init --list-templates + +# Manage platform services +agentkit memory list # List memory collections +agentkit knowledge list # List knowledge bases +agentkit tools list # List tools +agentkit runtime list # List runtime instances +``` + +## Environment Requirements + +### ✅ Basic Requirements (All Modes) + +- Python 3.10 or later +- pip package manager +- AgentKit SDK installed + +### 🐍 Python Development Environment + +- Supports Python 3.10, 3.11, 3.12, 3.13 +- Recommended to manage dependencies with `requirements.txt` + +### 🐹 Golang Development Environment + +- Supports Golang 1.24 +- Manage dependencies with `go.mod` +- Suitable for high-performance scenarios + +### 🐳 Local Development (Local/Hybrid Mode) + +- Docker Desktop or Docker Engine 20.10+ +- Ensure the Docker service is running + +### ☁️ Cloud Deployment (Cloud/Hybrid Mode) + +- A Volcengine account +- Configure access credentials (AK/SK). We recommend using the secure global configuration approach: + ```bash + # Initialize global configuration + agentkit config --global --init + + # Set access credentials + agentkit config --global --set volcengine.access_key="your_access_key" + agentkit config --global --set volcengine.secret_key="your_secret_key" + + # (Optional for Byteplus) Set BytePlus as the default cloud provider + agentkit config --global --set defaults.cloud_provider=byteplus + + # (Optional for Byteplus) Set Byteplus access credentials + agentkit config --global --set byteplus.access_key="your_byteplus_access_key" + agentkit config --global --set byteplus.secret_key="your_byteplus_secret_key" + ``` + +## Next Steps + +- 📖 [**Command Reference**](./2.commands.md): Dive into parameters and usage for each CLI command. +- ⚙️ [**Configuration Reference**](./3.configurations.md): Master all configuration options in `agentkit.yaml`. +- 🚀 [**Quick Start**](../1.introduction/3.quickstart.md): Follow an end-to-end tutorial to build a complete **Agent** application from scratch. diff --git a/docs/en/content/2.agentkit-cli/2.commands.md b/docs/en/content/2.agentkit-cli/2.commands.md new file mode 100644 index 0000000..e36f677 --- /dev/null +++ b/docs/en/content/2.agentkit-cli/2.commands.md @@ -0,0 +1,1891 @@ +--- +title: CLI Command Reference +--- + +# CLI Command Reference + +**AgentKit CLI** is the core tool for interacting with the **AgentKit Platform**. It provides a complete set of commands designed to simplify and automate the full lifecycle of **Agent** development, deployment, and management. Whether you are initializing a new project, configuring cloud resources, or testing and iterating on your **Agent**, **AgentKit CLI** provides strong support. + +This document introduces the purpose, parameters/options, and best practices for each command, helping you use **AgentKit CLI** efficiently to build excellent **Agent** applications. + +## Command Overview + +**AgentKit CLI** follows the standard format: `agentkit [arguments] [options]`. + +| Command | Description | Core Use Cases | +| :--- | :--- | :--- | +| `init` | **Initialize a project**: Create a brand-new **Agent** project or wrap existing code. | Start new **Agent** development; quickly deploy existing code. | +| `config` | **Configure an app**: Manage project configuration interactively or non-interactively. | Set deployment mode, environment variables, image tags, etc. | +| `build` | **Build an image**: Package your **Agent** code into a portable Docker image. | Prepare for deployment; CI/CD integration. | +| `deploy` | **Deploy an app**: Publish a built image to the target runtime environment. | Go live or update an **Agent** service. | +| `launch` | **One-command launch**: Automatically completes both build and deploy. | Fast iteration; simplified release workflow. | +| `invoke` | **Test invocation**: Invoke an **Agent** locally or in the cloud for functional validation. | Debug **Agent** logic; end-to-end validation. | +| `status` | **View status**: Get runtime status and endpoint information for a deployed **Agent**. | Monitor service health; obtain access URL. | +| `destroy` | **Clean up resources**: Stop and delete deployed **Agent** instances and related resources. | Take a service offline; release cloud resources. | + +--- + +## `agentkit init` + +`agentkit init` guides you through creating a new **Agent** project. It supports both “start from scratch” and “wrap existing code”, significantly improving bootstrap efficiency. + +### Modes + +1. **Template Mode**: Create a project from **AgentKit** built-in templates. Suitable for developers starting from scratch. +2. **Wrapper Mode**: Quickly wrap an existing `veadk` **Agent** definition file into a deployable **AgentKit** project to reuse code. + +### Syntax + +```bash +# Template mode: create from a preset template +agentkit init [project_name] [options] + +# Wrapper mode: wrap an existing Agent definition file +agentkit init [project_name] --from-agent [options] +``` + +### Core Parameter + +- `project_name` (optional): + - **Description**: A unique name for your **Agent** project, such as `smart-faq-agent`. + - **Default**: In template mode, `simple_agent`; in wrapper mode, auto-generated from the source filename (e.g. `agentkit-my_agent`). + - **Constraints**: Can only contain letters, numbers, underscores (`_`), and hyphens (`-`). + +### Template Mode Options + +| Option | Description | Example | +| :--- | :--- | :--- | +| `--template`, `-t` | Select a project template such as `basic`, `basic_stream`, `a2a`. | `--template basic` | +| `--agent-name` | Set the display name of the **Agent**. | `--agent-name "Intelligent Customer Support"` | +| `--description` | Describe what the **Agent** does (especially important in multi-agent collaboration). | `--description "Handle common user questions"` | +| `--system-prompt` | Define the **Agent** system prompt to shape its role and behavior. | `--system-prompt "You are a professional customer support agent..."` | +| `--model-name` | Specify the model name on Volcengine Ark. | `--model-name "doubao-pro-32k"` | +| `--tools` | Comma-separated list of tools such as `web_search,run_code`. | `--tools "web_search"` | + +### Wrapper Mode Options + +| Option | Description | Example | +| :--- | :--- | :--- | +| `--from-agent`, `-f` | **(Required)** Path to an existing Python file that contains a `veadk.Agent` definition. | `--from-agent ./my_existing_agent.py` | +| `--agent-var` | If auto-detection fails, manually specify the variable name of the **Agent** object in the file. | `--agent-var "custom_agent_instance"` | +| `--wrapper-type` | Wrapper type to generate: `basic` (standard) or `stream` (streaming). | `--wrapper-type stream` | + +### Common Options + +| Option | Description | Default | +| :--- | :--- | :--- | +| `--directory` | Target directory where the project will be created. | Current directory (`.`) | + +### Examples + +#### Template Mode + +```bash +# Example 1: interactive creation; guides you to choose a template +agentkit init my-first-agent + +# Example 2: create directly using the 'basic' template +agentkit init weather-report-agent --template basic + +# Example 3: create in a specified directory +agentkit init my_agent --template basic_stream --directory ./my_agents + +# Example 4: shorthand +agentkit init weather -t basic + +# Example 5: customize Agent attributes +agentkit init custom-agent \ + --template basic \ + --agent-name "Advanced Assistant" \ + --description "An agent with web access and code execution" \ + --tools "web_search,run_code" + +# Example 6: create a streaming output Agent +agentkit init stream_agent \ + --template basic_stream \ + --agent-name "Streaming Chat Assistant" \ + --model-name "doubao-seed-1-6-250615" +``` + +#### Wrapper Mode + +```bash +# Example 7: wrap an existing Agent file (auto-detect Agent variable) +agentkit init --from-agent ./my_agent.py + +# Example 8: wrap and specify a project name +agentkit init weather_bot --from-agent ./weather_agent.py + +# Example 9: shorthand and specify Agent variable name +agentkit init -f ./my_agent.py --agent-var my_custom_agent + +# Example 10: generate a streaming wrapper +agentkit init chat_bot \ + --from-agent ./chat_agent.py \ + --wrapper-type stream + +# Example 11: wrap into a specified directory +agentkit init deployed_agent \ + --from-agent ../agents/production_agent.py \ + --agent-var prod_agent \ + --wrapper-type basic \ + --directory ./deployment + +# Example 12: a complete wrapper command +agentkit init my_deployed_bot \ + -f ~/projects/agents/my_bot.py \ + --agent-var bot \ + --wrapper-type stream \ + --directory ./deploy +``` + +**Best practices** + +- **Start from templates**: For new **AgentKit** users, start with the `basic` template; it provides a simple project structure. +- **Leverage wrapper mode**: When you already have mature `veadk` **Agent** logic, wrapper mode helps you avoid rewriting code and focus on fast deployment. +- **Use clear names**: Give your project and **Agent** descriptive names to support long-term maintenance and teamwork. + +### Output + +#### Template mode output + +After running a template-mode command, you will see output similar to: + +``` + ✨ Build AI Agents with Ease ✨ + +Available Templates +┌────┬──────────────────────────┬──────────┬──────────────────────────────────────────────┐ +│ ID │ Name │ Type │ Description │ +├────┼──────────────────────────┼──────────┼──────────────────────────────────────────────┤ +│ 1 │ Basic Agent App │ Basic App│ Basic Agent app, great for getting started │ +│ 2 │ Basic Stream Agent App │ Stream App│ Agent app with streaming output │ +│ 3 │ A2A Agent App │ A2A App │ Multi-agent app supporting the A2A protocol │ +│ 4 │ Eino A2A Agent App │ A2A App │ A2A app based on the Eino framework (Golang) │ +└────┴──────────────────────────┴──────────┴──────────────────────────────────────────────┘ + +Please select a template by entering the ID (1-2): +Template ID: 1 +Selected: Basic Agent App + +Creating project: my_weather_agent +Using template: Basic Agent App + +✨ Project initialized successfully! +Template: Basic Agent App +Entry point: my_weather_agent.py +Language: Python 3.12 + +Created files: + ✓ my_weather_agent.py + ✓ requirements.txt + ✓ agentkit.yaml + ✓ .dockerignore + +Next steps: + 1. Review and modify the generated files + 2. Use agentkit config to configure your agent + 3. Use agentkit launch to build and deploy +``` + +#### Wrapper mode output 🆕 + +After running a wrapper-mode command, you will see output similar to: + +``` + ✨ Build AI Agents with Ease ✨ + +🔄 Wrapping existing Agent file + +Project name: agentkit-my_agent +Agent file: ./my_agent.py +Wrapper type: basic + +✨ Project initialized successfully! +Template: Agent Wrapper (Basic) +Entry point: agentkit-my_agent.py +Language: Python 3.12 +Agent file: my_agent.py +Agent variable: agent + +Created files: + ✓ my_agent.py + ✓ agentkit-my_agent.py + ✓ requirements.txt + ✓ agentkit.yaml + ✓ .dockerignore + +Next steps: + 1. Review and modify the generated files + 2. Use agentkit config to configure your agent + 3. Use agentkit launch to build and deploy +``` + +### Wrapper mode deep dive 🆕 + +Wrapper mode is a powerful feature that lets you quickly deploy an existing Agent definition file to the AgentKit platform without rewriting code. + +#### How it works + +1. **Parse the Agent file**: Automatically analyzes your Python file and identifies the Agent object definition. +2. **Copy the source file**: Copies your Agent file into the project directory. +3. **Generate a wrapper**: Creates a new Python file that imports and wraps your Agent. +4. **Configure deployment**: Generates `agentkit.yaml` and other required deployment files. + +#### What the wrapper does + +The generated wrapper file is responsible for: + +- **Importing your Agent**: Imports the Agent object from your file. +- **Creating a Runner**: Wraps the Agent using the `veadk` Runner. +- **Providing deployment interfaces**: Implements the `@app.entrypoint` and `@app.ping` interfaces required by AgentKit. +- **Handling request/response**: Automatically converts HTTP request formats. + +#### Requirements for the Agent file + +Your Agent file must meet the following requirements: + +**Basic requirements**: + +```python +# Must be a Python file (.py) +# Must contain an Agent object definition + +from veadk import Agent + +# Agent definition - variable name can be agent, my_agent, etc. +agent = Agent( + model="doubao-seed-1-6-250615", + description="My Agent" +) +``` + +**Supported Agent variable names**: + +- The system auto-detects common names such as: `agent`, `main_agent`, `my_agent`, etc. +- You can also use a custom name, but you must specify it via `--agent-var`. + +**Unsupported cases**: + +- ❌ No `Agent(...)` definition in the file. +- ❌ Agent definition is inside a function (must be at module level). +- ❌ Agent object is created via complex logic (must be a direct assignment). + +#### Wrapper type comparison + +| Feature | Basic wrapper | Stream wrapper | +|------|-------------|--------------| +| **Response mode** | Return the full result once | Streaming return (SSE) | +| **Typical scenarios** | Standard chat; short responses | Long-form generation; real-time output | +| **Dependencies** | `veadk-python` | `veadk-python` + `google-adk` | +| **Config requirements** | None | Agent must support streaming output | +| **Client UX** | Wait and then show once | Token-by-token display; better interactivity | + +#### When to use which + +**Good scenarios for wrapper mode**: + +- ✅ You already have `veadk` Agent code and want to deploy quickly. +- ✅ Your Agent is developed and debugged locally and is ready to go live. +- ✅ Multiple projects share the same Agent definition. +- ✅ You want to keep Agent code and deployment code separated. + +**Good scenarios for template mode**: + +- ✅ Create a new Agent from scratch. +- ✅ Learn the AgentKit development workflow. +- ✅ Need complete example code as a starting point. + +#### Project structure after wrapping + +``` +my_project/ +├── my_agent.py # your original Agent definition +├── agentkit-my_agent.py # wrapper generated by AgentKit (entry point) +├── requirements.txt # dependencies list (with usage notes) +├── agentkit.yaml # deployment config (entry_point points to wrapper) +└── .dockerignore # Docker build ignore rules +``` + +**Wrapper file example** (basic type): + +```python +# Import your Agent +from my_agent import agent + +from veadk import Runner +from agentkit.apps import AgentkitSimpleApp + +app = AgentkitSimpleApp() +runner = Runner(agent=agent) + + +@app.entrypoint +async def run(payload: dict, headers: dict) -> str: + prompt = payload["prompt"] + user_id = headers["user_id"] + session_id = headers["session_id"] + + response = await runner.run( + messages=prompt, + user_id=user_id, + session_id=session_id, + ) + return response + + +@app.ping +def ping() -> str: + return "pong!" + + +if __name__ == "__main__": + app.run(host="0.0.0.0", port=8000) +``` + +#### FAQ + +**Q: What if the Agent definition cannot be found?** + +A: Use `--agent-var` to explicitly specify the Agent variable name: + +```bash +agentkit init -f ./my_agent.py --agent-var my_custom_agent_name +``` + +**Q: Can I modify the generated wrapper?** + +A: Yes. The wrapper is standard Python code and can be modified as needed. Just make sure `@app.entrypoint` and `@app.ping` remain unchanged. + +**Q: Will the original Agent file be modified?** + +A: No. The system only copies your file into the target directory; it does not modify the original file. + +**Q: How do I add extra dependencies in the wrapper project?** + +A: Edit the generated `requirements.txt` file and add the dependency packages you need. The file already contains usage notes. + +--- + +## agentkit config + +Configure parameters for an Agent application. Three modes are supported: **interactive** (guided), **non-interactive** (fast updates), and **hybrid** (flexible combination). + +**🆕 Global configuration support**: A global configuration file (`~/.agentkit/config.yaml`) is available to share configuration across projects. + +### Usage + +```bash +# Project configuration +agentkit config [arguments] [options] + +# Project level: set the cloud provider (volcengine/byteplus) +agentkit config --cloud_provider byteplus + +# Global configuration 🆕 +agentkit config --global [options] +``` + +### Three configuration modes + +#### 🎯 Interactive mode (default; recommended for first-time setup) + +Run with no parameters; the wizard guides you step-by-step: + +```bash +agentkit config +``` + +**Interactive flow example**: + +``` +[1/7] 🤖 Agent name: my_agent +[2/7] 📝 Entry point: my_agent.py +[3/7] 📄 App description: My weather query agent +[4/7] 🐍 Python version: 3.12 +[5/7] 📦 Dependencies file: requirements.txt +[6/7] 🚀 Deployment mode (choose one): + 1. local - build and run locally + 2. hybrid - build locally, run in the cloud + 3. cloud - build and run in the cloud (recommended) +[7/7] 🔐 App-level environment variables (shared by all modes): + Variable: MODEL_API_KEY=xxxxx +``` + +#### ⚡ Non-interactive mode (fast updates; suitable for scripts/CI/CD) + +Configure directly via command-line parameters without manual input: + +```bash +# Full configuration example +agentkit config \ + --agent_name myAgent \ + --entry_point agent.py \ + --launch_type cloud \ + --cloud_provider byteplus \ + --image_tag v1.0.0 \ + --runtime_envs API_KEY=xxxxx +``` + +```bash +# Incremental updates (only modify part of the configuration) +agentkit config --entry_point new_agent.py +agentkit config --image_tag v1.0.1 +``` + +#### 🔀 Hybrid mode + +Specify some parameters via the command line and input the rest interactively: + +```bash +agentkit config --agent_name myAgent --interactive +``` + +### Main parameters + +#### General configuration parameters + +| Parameter | Description | Example | +|------|------|------| +| `--agent_name` | Agent application name | `my_weather_bot` | +| `--entry_point` | Entry file (must end with `.py`) | `agent.py` | +| `--description` | App description | `"Weather assistant"` | +| `--language_version` | Language version | `3.12` | +| `--dependencies_file` | Dependencies file | `requirements.txt` | +| `--launch_type` | Deployment mode | `local`, `hybrid`, `cloud` | +| `--cloud_provider` / `--cloud-provider` | Cloud provider | `volcengine`, `byteplus` | + +#### Environment variable configuration (important ⭐) + +AgentKit supports **two-level environment variable** configuration: + +| Parameter | Level | Description | Use cases | +|------|------|------|----------| +| `--runtime_envs` / `-e` | **App level** | Shared across all deployment modes | API keys, model endpoints, cross-environment configuration | +| `--workflow-runtime-envs` | **Workflow level** | Only applies to the current deployment mode | Debug flags, mode-specific configuration | + +**Examples**: + +```bash +# App level (shared across all modes) +agentkit config \ + -e API_KEY=shared-key \ + -e MODEL_ENDPOINT=https://api.example.com + +# Workflow level (current mode only) +agentkit config \ + --workflow-runtime-envs DEBUG=true \ + --workflow-runtime-envs LOCAL_CACHE=/tmp + +# Mixed usage +agentkit config \ + -e API_KEY=shared \ + --workflow-runtime-envs DEBUG=true +``` + +**Merge rules**: + +- App-level environment variables are inherited by all workflows. +- Workflow-level environment variables only take effect in the current mode. +- Variables with the same name: workflow-level overrides app-level. + +#### Cloud/Hybrid mode parameters + +| Parameter | Description | Example | +|------|------|------| +| `--region` | Volcengine region | `cn-beijing` | +| `--tos_bucket` | TOS bucket | `agentkit-bucket` | +| `--image_tag` | Image tag | `v1.0.0`, `latest` | +| `--cr_instance_name` | CR instance name | `my-cr-instance` | +| `--cr_namespace_name` | CR namespace | `agentkit` | +| `--cr_repo_name` | CR repository name | `my-agent` | + +> 💡 Tip: the `--cr_*` parameters also support legacy aliases `--ve_cr_*` for backward compatibility. + +#### Runtime resource bindings (Cloud/Hybrid) + +You can use `agentkit config` to bind (or unbind) runtime resources. When `agentkit launch/deploy` creates/updates a runtime, the bindings are passed through to the Runtime API. + +Supported binding fields: + +- `memory_id`: bind a Memory +- `knowledge_id`: bind a Knowledge +- `tool_id`: bind a Tool +- `mcp_toolset_id`: bind an MCP Toolset + +**Command-line examples**: + +```bash +# Bind resources +agentkit config \ + --memory_id mem-xxx \ + --knowledge_id kb-xxx \ + --tool_id tool-xxx \ + --mcp_toolset_id mcp-ts-xxx + +# Unbind (set to empty string) +agentkit config --memory_id "" +``` + +**YAML persisted location** (`agentkit.yaml`): + +```yaml +launch_types: + cloud: # or hybrid + runtime_bindings: + memory_id: mem-xxx + knowledge_id: kb-xxx + tool_id: tool-xxx + mcp_toolset_id: mcp-ts-xxx +``` + +> 💡 **Unbind semantics**: +> - **Omit a key** in config: do not change that binding +> - Set to `""` or `null`: clear/unbind (a clear operation will be sent when updating the Runtime) + +#### Runtime network configuration (Cloud/Hybrid) + +You can use `agentkit config` to set runtime networking (VPC/private network, public network, or dual-stack). This configuration takes effect **only when creating a runtime for the first time (CreateRuntime)**. + +> ⚠️ **Limitation**: If a runtime already exists, `agentkit launch/deploy` will call UpdateRuntime. +> UpdateRuntime does not support modifying `network_configuration`, so this setting will not affect existing runtimes. +> If you need to change the network, destroy and recreate the runtime. + +**Command-line example (private network)**: + +```bash +agentkit config \ + --runtime-network-mode private \ + --runtime-vpc-id vpc-xxxxxxxx \ + --runtime-subnet-id subnet-aaaaaaaa \ + --runtime-enable-shared-internet-access +``` + +**YAML format** (`agentkit.yaml`): + +```yaml +launch_types: + cloud: # or hybrid + runtime_network: + mode: private # public | private | both + vpc_id: vpc-xxxxxxxx # required for private/both + enable_shared_internet_access: true # only effective for private/both + subnet_ids: + - subnet-aaaaaaaa +``` + +`mode` values: + +- `public`: public access only +- `private`: private access only (requires `vpc_id`) +- `both`: enable both public and private access (requires `vpc_id`) + +`enable_shared_internet_access`: + +- Only takes effect when `mode` is `private` or `both`. When enabled, the runtime uses the platform-provided shared public egress to access the public internet. +- If `mode=public` and this flag is enabled, AgentKit will error to prevent a misleading “configured but not effective” setup. + +### Control options + +| Option | Description | +|------|------| +| `--config`, `-c` | Specify the configuration file path (default: `agentkit.yaml`) | +| `--interactive`, `-i` | Force interactive mode | +| `--dry-run` | Preview changes without saving | +| `--show`, `-s` | Show current configuration | + +### Global configuration options 🆕 + +AgentKit supports a global configuration file (`~/.agentkit/config.yaml`) for sharing configuration across projects. + +| Option | Description | +|------|------| +| `--global`, `-g` | Operate on the global config instead of the project config | +| `--init` | Initialize the global config file (create a template) | +| `--set` | Set a global config field (format: `key=value`) | + +**Supported global config fields**: + +| Field | Description | Example | +|------|------|------| +| `volcengine.access_key` | Volcengine Access Key | `AK***` | +| `volcengine.secret_key` | Volcengine Secret Key | `SK***` | +| `volcengine.region` | Default region | `cn-beijing` | +| `cr.instance_name` | CR instance name | `team-cr-instance` | +| `cr.namespace_name` | CR namespace | `agentkit-team` | +| `tos.bucket` | TOS bucket name | `team-agentkit-builds` | +| `tos.prefix` | TOS object prefix | `agentkit-builds` | +| `tos.region` | TOS region | `cn-beijing` | + +**Configuration precedence**: + +``` +Environment variables > Project config (agentkit.yaml) > Global config > Defaults +``` + +### Examples + +#### Example 1: first-time configuration (interactive) + +```bash +agentkit config +``` + +#### Example 2: quickly update a single field + +```bash +# Update entry point +agentkit config --entry_point new_agent.py + +# Update image tag +agentkit config --image_tag v1.0.1 + +# Add an environment variable +agentkit config -e NEW_KEY=new_value +``` + +#### Example 3: complete non-interactive configuration + +```bash +agentkit config \ + --agent_name weather-bot \ + --entry_point agent.py \ + --description "Weather assistant" \ + --launch_type cloud \ + --image_tag v1.0.0 \ + --region cn-beijing \ + -e API_KEY=xxxxx \ + -e MODEL_ENDPOINT=https://api.example.com +``` + +#### Example 4: configuration preview (dry run) + +```bash +# Show changes but do not save +agentkit config --entry_point agent.py --image_tag v2.0 --dry-run +``` + +Example output: + +``` +General config - changes: +┌──────────────┬──────────────┬──────────────┐ +│ Config item │ Old value │ New value │ +├──────────────┼──────────────┼──────────────┤ +│ entry_point │ old_agent.py │ agent.py │ +│ image_tag │ v1.0 │ v2.0 │ +└──────────────┴──────────────┴──────────────┘ + +🔍 Dry-run: no changes were saved +``` + +#### Example 5: show current configuration + +```bash +agentkit config --show +``` + +#### Example 6: global configuration management 🆕 + +**Initialize global configuration:** + +```bash +# Create a global config template +agentkit config --global --init +``` + +Output: + +``` +✅ Global configuration file created: ~/.agentkit/config.yaml + +📝 A template has been generated containing the following fields: + +🔐 Volcengine credentials + access_key: '' + secret_key: '' + region: cn-beijing + +📦 CR configuration + instance_name: '' + namespace_name: '' + +🗂️ TOS configuration + bucket: '' + prefix: agentkit-builds + region: cn-beijing +``` + +**Show global configuration:** + +```bash +agentkit config --global --show +``` + +**Set global configuration:** + +```bash +# Set a single field +agentkit config --global --set cr.instance_name=team-cr-instance +agentkit config --global --set tos.bucket=team-bucket + +# Set credentials +agentkit config --global --set volcengine.access_key=AK*** +agentkit config --global --set volcengine.secret_key=SK*** +``` + +**Team collaboration scenario:** + +```bash +# 1. Team admin creates and shares global configuration +agentkit config --global --init +vim ~/.agentkit/config.yaml # fill in team-shared configuration + +# 2. Team members automatically use global config when initializing projects +agentkit init my-agent +# related fields in agentkit.yaml are left empty; global config is used at runtime + +# 3. Special projects can override global configuration in agentkit.yaml +agentkit config --cr_instance_name special-cr # override global config +``` + +#### Example 7: CI/CD integration + +```bash +# Use in CI/CD pipelines +agentkit config \ + --agent_name ${CI_PROJECT_NAME} \ + --entry_point agent.py \ + --launch_type cloud \ + --image_tag ${CI_COMMIT_TAG} \ + -e DEPLOY_TIME=$(date -u +"%Y-%m-%dT%H:%M:%SZ") + +agentkit launch +``` + +### Interactive input for environment variables + +In interactive mode, environment variable configuration supports convenience commands: + +``` +🔐 App-level environment variables (enter KEY=VALUE; empty line to finish) + + Available commands: + - Enter KEY=VALUE to add a variable + - Enter 'list' to show existing variables + - Enter 'del KEY' to delete a variable + - Enter 'clear' to clear all + - Press Enter on an empty line to finish + +Variable: MODEL_API_KEY=xxxxx +✅ Added: MODEL_API_KEY + +Variable: list +Current variables: + MODEL_API_KEY=xxxxx + +Variable: [press Enter to finish] +📋 Configured 1 shared variable +``` + +### Configuration validation + +All configuration is validated automatically: + +- ✅ **Required fields**: Agent name and entry point cannot be empty +- ✅ **Format validation**: entry point must end with `.py` +- ✅ **Option constraints**: launch_type must be `local`, `hybrid`, or `cloud` +- ✅ **Naming rules**: Agent name can only contain letters, numbers, underscore, hyphen, and dot + +Validation failures show detailed errors and exit. + +### Best practices + +1. **Use interactive mode for first-time setup** for a guided experience + ```bash + agentkit config + ``` + +2. **Use non-interactive mode for daily updates** for speed and efficiency + ```bash + agentkit config --entry_point new_agent.py + ``` + +3. **Use non-interactive mode in CI/CD** for full automation + ```bash + agentkit config --agent_name $PROJECT --image_tag $TAG + ``` + +4. **Preview before applying** to avoid mistakes + ```bash + agentkit config --entry_point agent.py --dry-run + ``` + +5. **Manage environment variables by level**: + - App level: shared across environments (API keys, etc.) + - Workflow level: mode-specific (debug flags, etc.) + +6. **Use global config for team collaboration** 🆕: + ```bash + # Team admin + agentkit config --global --init + agentkit config --global --set cr.instance_name=team-cr + agentkit config --global --set tos.bucket=team-bucket + + # Team members + agentkit init my-agent # automatically uses global config + agentkit launch # automatically uses global config at runtime + ``` + +7. **Understand configuration precedence**: + - Project config can override global config + - Environment variables have the highest priority + - Order: `Environment variables > Project config > Global config > Defaults` + +--- + +## agentkit build + +Package your Agent code into a Docker image in preparation for deployment. + +### Usage + +```bash +agentkit build [options] +``` + +### Parameter description + +`--config-file` configuration file path + +- Specify the config file location +- Default: `agentkit.yaml` + +`--platform` build platform + +- Specify the target platform/architecture +- Default: `auto` (auto-detect) +- Usually not needed + +`--regenerate-dockerfile` force regenerate Dockerfile + +- Force regenerate Dockerfile even if it already exists +- Use case: when configuration has changed and you need to refresh the Dockerfile +- Default: `False` + +### Docker build customization 🛠 + +AgentKit supports customizing Docker image builds via the `docker_build` section. Add the following to `agentkit.yaml`. + +#### Configuration fields + +**`base_image`** - custom base image + +Python projects (string form): + +```yaml +docker_build: + base_image: "python:3.12-slim" + # Or use an Alpine image + base_image: "python:3.12-alpine" +``` + + + +**`build_script`** - custom build script + +- Path is relative to the project root +- Used for installing system dependencies, compiling extensions, etc. +- The script runs automatically during the build + +```yaml +docker_build: + build_script: "scripts/setup.sh" +``` + +#### Complete example + +**Python project example**: + +```yaml +agent_name: my-agent +entry_point: agent.py +language: Python +language_version: "3.12" +dependencies_file: requirements.txt +launch_type: local + +# Docker build customization +docker_build: + base_image: "python:3.12-alpine" + build_script: "scripts/setup.sh" +``` + +Build script example (`scripts/setup.sh`): + +```bash +#!/bin/bash +# Install system dependencies +apt-get update && apt-get install -y gcc g++ libpq-dev +# Or on Alpine: apk add --no-cache gcc musl-dev postgresql-dev + +echo "Custom build script completed" +``` + + + +#### Use cases + +| Scenario | Configuration | Example | +|------|---------|------| +| Use a lightweight image | Specify an Alpine base image | `base_image: "python:3.12-alpine"` | +| Install system dependencies | Write a build script | `build_script: "scripts/install_deps.sh"` | +| Compile C extensions | Install a build toolchain | Install gcc, g++, etc. in the script | +| Configure certificates | Update CA certificates | Run `update-ca-certificates` in the script | +| Multi-stage builds | Specify builder and runtime separately | Golang projects only | + +#### Dockerfile auto-management + +- Dockerfile is **auto-generated** based on configuration and includes a metadata header +- Automatically updated when configuration changes (old versions are backed up to `.agentkit/dockerfile_backups/`) +- If you remove the metadata header, AgentKit will no longer manage the file automatically +- Use `--regenerate-dockerfile` to force regeneration + +Example metadata header: + +```dockerfile +# ============================================================================ +# AUTO-GENERATED by AgentKit v1.x.x +# ============================================================================ +# Source: agentkit.yaml +# Checksum: sha256:... +# Generated: 2025-01-17T10:30:00 +# +# This file is automatically generated and managed by AgentKit: +# - It will be auto-updated when agentkit.yaml config changes +# - To fully customize, remove this header comment +# ============================================================================ +``` + +### Build process + +The build strategy is chosen automatically based on `launch_type`: + +#### 🏠 Local mode (build locally) + +Build with Docker on your machine: + +``` +🔨 Starting local image build... +[1/3] Generating Dockerfile... +[2/3] Building Docker image... +[3/3] Verifying image availability... +✅ Build succeeded: my-agent:latest +``` + +Estimated time: 1–3 minutes. + +#### ☁️ Cloud mode (build in the cloud) + +Build automatically on Volcengine: + +``` +🔨 Starting cloud build... +[1/6] Generating Dockerfile... +[2/6] Packaging project code... +[3/6] Uploading to object storage... +[4/6] Preparing image registry... +[5/6] Creating build pipeline... +[6/6] Executing build task... +✅ Build succeeded: xxx.cr.volces.com/agentkit/my-agent:latest +``` + +Estimated time: 3–5 minutes. + +### Build result + +- **Image name**: {agent_name}:{image_tag} +- **Image information**: automatically saved into the configuration file +- **Build record**: includes timestamp, image ID, etc. + +### Examples + +```bash +# Example 1: build with default configuration +agentkit build + +# Example 2: specify config file +agentkit build --config-file ./prod.yaml + +# Example 3: force regenerate Dockerfile +agentkit build --regenerate-dockerfile + +# Example 4: force refresh after config changes +agentkit build --config-file ./prod.yaml --regenerate-dockerfile +``` + +#### Custom build examples + +**Example 5: use an Alpine base image** + +1. Modify `agentkit.yaml`: + +```yaml +docker_build: + base_image: "python:3.12-alpine" + build_script: "scripts/alpine-setup.sh" +``` + +2. Create `scripts/alpine-setup.sh`: + +```bash +#!/bin/sh +apk add --no-cache gcc musl-dev postgresql-dev +``` + +3. Build: + +```bash +agentkit build +``` + +**Example 6: install system dependencies (C extensions)** + +1. Modify `agentkit.yaml`: + +```yaml +docker_build: + build_script: "scripts/install-deps.sh" +``` + +2. Create `scripts/install-deps.sh`: + +```bash +#!/bin/bash +apt-get update && apt-get install -y \ + gcc g++ \ + libpq-dev \ + libxml2-dev \ + libxslt1-dev +``` + +3. Build: + +```bash +agentkit build +``` + +**Example 7: Golang multi-stage build** + +Modify `agentkit.yaml`: + +```yaml +docker_build: + base_image: + builder: "golang:1.24-alpine" + runtime: "alpine:3.19" + build_script: "scripts/install-certs.sh" +``` + +Build: + +```bash +agentkit build +``` + +### Notes + +**Local mode prerequisites**: + +- ✅ Ensure Docker is installed and running +- ✅ Docker daemon is accessible + +**Cloud mode prerequisites**: + +- ✅ Set AK/SK credentials +- ✅ Ensure network access to Volcengine + +**Docker build customization**: + +- ✅ Build script path should be relative to the project root +- ✅ Scripts automatically gain execute permissions +- ✅ Missing build scripts produce warnings but do not stop the build +- ✅ Dockerfile is auto-generated and updated when configuration changes +- ✅ Older Dockerfiles are backed up to `.agentkit/dockerfile_backups/` +- ✅ Removing the metadata header disables automatic management + +Tip: build metadata will be written back to the config file for use by the `deploy` command. + +--- + +## agentkit deploy + +Deploy the built image and start the Agent to serve requests. + +### Usage + +```bash +agentkit deploy [options] +``` + +### Parameter Description + +`--config-file` Configuration file path +- Specify the config file location +- Default: `agentkit.yaml` + +### Deployment Process + +Automatically selects the deployment target based on the configured `launch_type`: + +#### 🏠 Local Mode (Local Deployment) +Starts the container on your local machine: +``` +🚀 Starting deployment to local Docker... +[1/3] Stopping old container version... +[2/3] Starting new container... +[3/3] Verifying container status... +✅ Deployment successful! Container is running +🌐 Access URL: http://localhost:8000 +``` +Estimated time: 10-30 seconds + +#### ☁️ Cloud Mode (Cloud Deployment) +Creates a Runtime on Volcengine: +``` +🚀 Starting deployment to cloud platform... +✅ Generated Runtime name: my-agent-20250120-abc123 +✅ Created Runtime: r-xxxxxx +⏳ Waiting for Runtime to be ready... +✅ Runtime is ready! +🌐 Access URL: http://xxx.apigateway-cn-beijing.volceapi.com +``` +Estimated time: 1-2 minutes + +### Usage Examples + +```bash +# Example 1: Deploy to default environment +agentkit deploy + +# Example 2: Deploy to production environment +agentkit deploy --config-file ./prod.yaml +``` + +### After Deployment + +**Local Mode**: +- ✅ Container running locally +- ✅ Accessible via `localhost:port` +- ✅ Automatic health checks + +**Cloud Mode**: +- ✅ Runtime running in the cloud +- ✅ Get a publicly accessible URL +- ✅ Automatic Runtime status verification + +--- + +## agentkit launch + +Build + Deploy in one step! Equivalent to automatically running `build` then `deploy`. + +### Usage + +```bash +agentkit launch [options] +``` + +### Parameter Description + +`--config-file` Configuration file path +- Specify the config file location +- Default: `agentkit.yaml` + +### Execution Flow + +``` +🚀 Starting Agent launch... + +━━━ Step 1: Build Image ━━━ +🔨 Reading config: agentkit.yaml +🔨 Starting build... +✅ Build completed + +━━━ Step 2: Deploy Application ━━━ +🚀 Starting deployment... +✅ Deployment completed + +✨ Agent launched successfully! +``` + +### Usage Examples + +```bash +# Example 1: One-click launch +agentkit launch + +# Example 2: Launch to production environment +agentkit launch --config-file ./prod.yaml +``` + +### Why Use launch + +- ⚡ **Time-saving** - One command instead of two +- 🔒 **Version consistency** - Ensures build and deploy use the same configuration +- 🚀 **Fast iteration** - Test immediately after code changes + +--- + +## agentkit invoke + +Send a test request to a deployed Agent to verify functionality. + +### Usage + +```bash +agentkit invoke [message content] [options] +``` + +⚠️ **Important**: You must provide either message content or the `--payload` option, **but not both** + +### Parameter Description + +**Message Content** +- Enter the text you want to send directly after the command, without any option flags +- Will be automatically wrapped as {"prompt": "your message"} +- Cannot be used with `--payload` +- Example: `agentkit invoke "hello"` or `agentkit invoke "how's the weather today?"` + +**Options** + +`--payload, -p` Custom request data +- Specify complete request content in JSON format +- Cannot be used with message content +- Example: --payload '{"prompt": "hello", "context": "greeting"}' + +`--headers, -h` Custom request headers +- Specify HTTP headers in JSON format +- Automatically adds `user_id` and `session_id` by default +- Example: --headers '{"user_id": "test123"}' + +`--raw` Output raw response (for debugging) +- For streaming calls: prints SSE event JSON from server line by line to verify event format +- For non-streaming calls: outputs compact raw JSON (no pretty indent) +- Example: `agentkit invoke "hello" --raw` + +`--show-reasoning` Output reasoning content (for LangChain debugging) +- When streaming events contain `additional_kwargs.reasoning_content`, incrementally prints this field +- Displayed separately from final answer (Reasoning first, then Answer) +- Example: `agentkit invoke "1+1=?" --show-reasoning` + +`--apikey, -ak` API Key +- May be required for cloud deployment (Cloud mode) +- Used for authentication +- Optional parameter + +`--config-file` Configuration file path +- Specify the config file location +- Default: `agentkit.yaml` in current directory + +### Usage Examples + +#### Example 1: Send message directly (simplest) + +```bash +agentkit invoke "How's the weather in Hangzhou today?" +``` + +Equivalent to sending the following JSON: +```json +{ + "prompt": "How's the weather in Hangzhou today?" +} +``` + +#### Example 2: Custom request content + +```bash +agentkit invoke --payload '{"prompt": "Hangzhou weather?", "user_location": "Hangzhou"}' +``` + +#### Example 3: With headers + +```bash +agentkit invoke \ + --payload '{"prompt": "Hangzhou weather?"}' \ + --headers '{"user_id": "user123", "session_id": "sess456"}' +``` + +#### Example 4: Cloud deployment (with API Key) + +```bash +agentkit invoke "hello" --apikey your_api_key_here +``` + +### Execution Output + +``` +💬 Calling Agent... +✅ Runtime ID: r-xxxxxx +🌐 Calling address: http://xxx.apigateway-cn-beijing.volceapi.com +✅ Call successful! + +📡 Agent response: +Hangzhou is sunny today, 22°C, great for going out. +``` + +### Notes + +- ⚠️ Message content and `--payload` are mutually exclusive +- ⚠️ Cloud deployment may require API Key +- ⚠️ Ensure Agent is deployed before calling (check with `agentkit status`) + +--- + +## agentkit status + +View the Agent's running status, including whether it's online, access URL, and other information. + +### Usage + +```bash +agentkit status [options] +``` + +### Parameter Description + +`--config-file` Configuration file path +- Specify the config file location +- Default: `agentkit.yaml` + +### Output Example + +#### 🏠 Local Mode + +``` +✅ Container name: my-agent +✅ Running status: running +🌐 Access URL: http://localhost:8000 + +Details: +{ + "container_id": "abc123...", + "status": "running", + "ports": ["8000:8000"], + "created": "2025-01-20 10:00:00", + "health": "healthy" +} +``` + +#### ☁️ Cloud Mode + +``` +✅ Runtime ID: r-xxxxxx +✅ Running status: Ready +🌐 Access URL: http://xxx.apigateway-cn-beijing.volceapi.com + +Details: +{ + "runtime_id": "r-xxxxxx", + "runtime_name": "my-agent-20250120-abc123", + "status": "Ready", + "endpoint": "http://xxx.apigateway-cn-beijing.volceapi.com", + "image": "xxx.cr.volces.com/agentkit/my-agent:latest", + "created_at": "2025-01-20 10:00:00" +} +``` + +### Status Description + +**Local Mode Status**: +- ✅ `running` - Running normally +- ⏸️ `stopped` - Stopped +- 🔄 `restarting` - Restarting +- ❌ `error` - Error occurred + +**Cloud Mode Status**: +- ✅ `Ready` - Ready to receive requests +- 🔄 `Releasing` - Deploying +- ❌ `Error` - Runtime error +- ❌ `Failed` - Deployment failed + +### Usage Examples + +```bash +# Example 1: View current status +agentkit status + +# Example 2: View production environment status +agentkit status --config-file ./prod.yaml +``` + +--- + +## agentkit destroy + +Stop and delete the Agent instance, releasing resources. ⚠️ This operation is irreversible! + +### Usage + +```bash +agentkit destroy [options] +``` + +### Parameter Description + +`--force` Force delete +- Skip confirmation prompt and delete directly +- Default is off (will ask for confirmation) +- Use with caution! + +`--config-file` Configuration file path +- Specify the config file location +- Default: `agentkit.yaml` + +### Safety Confirmation + +By default, you will be asked to confirm the operation: + +``` +🗑️ Preparing to destroy running Agent... +⚠️ This operation cannot be undone! +Are you sure you want to continue? [y/N]: y +``` + +Skip confirmation (not recommended): +```bash +agentkit destroy --force +``` + +### What Will Be Deleted + +#### 🏠 Local Mode +- ✅ Stop Docker container +- ✅ Delete container instance +- ⚠️ Image will be retained (can be manually deleted) + +#### ☁️ Cloud Mode +- ✅ Delete Runtime instance +- ✅ Release cloud resources +- ⚠️ Image will be retained (can be manually deleted in CR) + +### Execution Output + +``` +🗑️ Starting to destroy Agent resources... +✅ Stopped Runtime: r-xxxxxx +✅ Runtime deleted successfully +✅ Resources cleaned up + +Tip: Configuration file and images are retained, can redeploy anytime. +``` + +### Usage Examples + +```bash +# Example 1: Safe deletion (recommended) +agentkit destroy + +# Example 2: Force deletion +agentkit destroy --force + +# Example 3: Delete specified environment +agentkit destroy --config-file ./dev.yaml +``` + +### Important Notes + +- ⚠️ **Irreversible**: Cannot be undone after deletion, data will be permanently lost +- ✅ **Config retained**: `agentkit.yaml` file will not be deleted +- ✅ **Image retained**: Docker images will not be deleted, can redeploy +- 💡 **Redeploy**: Can redeploy anytime with `agentkit deploy` + +--- + +## Common Options + +All commands support these options: + +### --help View Help + +View detailed descriptions and parameters for any command: + +```bash +# View help for a specific command +agentkit invoke --help +agentkit build --help + +# View list of all commands +agentkit --help +``` + +### --version View Version + +Display CLI version information: + +```bash +agentkit --version +# or +agentkit -v +``` + +--- + +## Platform Service Commands + +AgentKit CLI provides rich platform service management commands for managing Memory, Knowledge, Tools, and Runtime resources. + +### `agentkit memory` + +Manage AgentKit Memory collections, supporting create, view, update, and delete operations. + +```bash +# Create memory collection (default provider-type: MEM0) +agentkit memory create --name my-memory --description "My memory collection" + +# Add external memory collection +agentkit memory add --provider-collection-id --provider-type VIKINGDB_MEMORY --name my-external-memory + +# List all memory collections (supports pagination and filtering) +agentkit memory list +agentkit memory list --name-contains "my" --limit 10 + +# View memory collection details +agentkit memory show -m + +# Update memory collection +agentkit memory update -m --description "Updated description" + +# Delete memory collection +agentkit memory delete -m + +# Get connection information +agentkit memory conn -m + +# View supported Provider types +agentkit memory provider-types +``` + +### `agentkit knowledge` + +Manage AgentKit Knowledge bases, supporting CRUD operations. + +```bash +# Add knowledge base (connect external knowledge base) +agentkit knowledge add --name my-kb --provider-knowledge-id --provider-type VIKINGDB_KNOWLEDGE + +# List all knowledge bases (supports pagination and filtering) +agentkit knowledge list +agentkit knowledge list --status Ready + +# View knowledge base details +agentkit knowledge show -k + +# Update knowledge base +agentkit knowledge update -k --description "Updated description" + +# Delete knowledge base +agentkit knowledge delete -k + +# Get connection information +agentkit knowledge conn -k + +# View supported Provider types +agentkit knowledge provider-types +``` + +### `agentkit tools` + +Manage AgentKit Tools and Sessions, including tool lifecycle management and session operations. + +```bash +# Tool management +# Create tool (needs to specify tool-type) +agentkit tools create --name my-tool --tool-type --description "My tool" +# List tools (supports pagination and filtering) +agentkit tools list +# View tool details +agentkit tools show -t +# Update tool +agentkit tools update -t --description "New description" +# Delete tool +agentkit tools delete -t + +# Session management +# Create session +agentkit tools session create -t --name my-session --ttl 30 --ttl-unit minute +# List sessions +agentkit tools session list -t +# View session details +agentkit tools session show -t -s +# Get session logs +agentkit tools session logs -t -s +# Set session TTL +agentkit tools session set-ttl -t -s --ttl 60 --ttl-unit minute +# Delete session +agentkit tools session delete -t -s +``` + +### `agentkit runtime` + +Manage AgentKit Runtime instances, supporting runtime create, update, delete, and version management. + +```bash +# Create runtime (needs to specify artifact info) +agentkit runtime create \ + --name my-runtime \ + --role-name \ + --artifact-type DockerImage \ + --artifact-url \ + --description "My runtime" + +# Create runtime and associate resources +agentkit runtime create \ + --name my-runtime \ + --role-name \ + --artifact-type DockerImage \ + --artifact-url \ + --memory-id mem-xxx \ + --knowledge-id kb-xxx \ + --tool-id tool-xxx \ + --mcp-toolset-id mcp-ts-xxx + +# Create runtime with private network access (VPC) +agentkit runtime create \ + --name my-runtime \ + --role-name \ + --artifact-type DockerImage \ + --artifact-url \ + --vpc-id vpc-xxxxxxxx \ + --subnet-ids subnet-aaaaaaaa \ + --enable-private-network \ + --enable-public-network false + +# List all runtimes (supports pagination and filtering) +agentkit runtime list + +# View runtime details +agentkit runtime get -r + +# Update runtime +agentkit runtime update -r --description "New description" + +> 💡 Tip: `agentkit runtime update` currently only supports updating artifact/description/env/tags and resource binding fields (`memory-id/knowledge-id/tool-id/mcp-toolset-id`), network configuration cannot be modified. + +# Delete runtime +agentkit runtime delete -r + +# Release new version +agentkit runtime release -r --version-number + +# View specific version details +agentkit runtime version -r --version-number + +# List all versions +agentkit runtime versions -r +``` + +--- + +## Common Workflows + +### 📝 Complete Development Workflow (Template Mode) + +Complete steps from zero to production: + +```bash +# 1️⃣ Create project +agentkit init weather_agent --template basic +cd weather_agent + +# 2️⃣ Configure app +agentkit config + +# 3️⃣ One-click deploy +agentkit launch + +# 4️⃣ Test functionality +agentkit invoke "How's the weather in Hangzhou?" + +# 5️⃣ Check status +agentkit status +``` + +### 🔄 Quick Deploy Existing Agent (Wrapper Mode) 🆕 + +Quickly deploy an existing Agent: + +```bash +# 1️⃣ Wrap existing Agent file +agentkit init --from-agent ~/my_projects/weather_agent.py + +# 2️⃣ Enter project directory +cd agentkit-weather_agent + +# 3️⃣ (Optional) Configure app +agentkit config + +# 4️⃣ One-click deploy +agentkit launch + +# 5️⃣ Test functionality +agentkit invoke "How's the weather today?" + +# 6️⃣ Check status +agentkit status +``` + +### 🔄 Quick Iteration Workflow + +Update workflow after code changes: + +```bash +# Method 1: Step-by-step (recommended for debugging) +agentkit build # Rebuild +agentkit deploy # Redeploy +agentkit invoke "test" # Test validation + +# Method 2: One-click update (recommended for daily development) +agentkit launch # Auto build+deploy +agentkit invoke "test" # Test validation +``` + +### 🌍 Multi-Environment Management + +Switch between dev, test, and production environments: + +```bash +# Development environment +agentkit launch --config-file agentkit.dev.yaml +agentkit invoke "test" --config-file agentkit.dev.yaml + +# Production environment +agentkit launch --config-file agentkit.prod.yaml +agentkit invoke "test" --config-file agentkit.prod.yaml +``` + +--- + +## FAQ + +Don't panic when you encounter errors, here are solutions! + +### ❌ Configuration file not found + +``` +Error: Configuration file not found: agentkit.yaml +``` + +**Cause**: No configuration file in current directory + +**Solution**: +```bash +# If new project +agentkit init my_agent + +# If existing project +agentkit config +``` + +### ❌ Docker not running (Local Mode) + +``` +Error: Docker daemon not running +``` + +**Cause**: Docker service not started + +**Solution**: +- Windows/Mac: Open Docker Desktop +- Linux: `sudo systemctl start docker` + +### ❌ Cloud credentials not configured (Cloud Mode) + +``` +Error: VOLC_ACCESSKEY or VOLC_SECRETKEY not set +``` + +**Cause**: Volcengine AK/SK not set + +**Solution**: +```bash +# Recommended: Use secure global config +agentkit config --global --init +agentkit config --global --set volcengine.access_key="your AccessKey" +agentkit config --global --set volcengine.secret_key="your SecretKey" + +# Or: Temporary environment variables (for dev/debugging) +export VOLC_ACCESSKEY="your AccessKey" +export VOLC_SECRETKEY="your SecretKey" +``` + +### ❌ Build failed + +``` +❌ Build failed: ... +``` + +**Possible causes and solutions**: +1. **Dependency issues** - Check if `requirements.txt` is correct +2. **Code errors** - Check if Python code has syntax errors +3. **Network issues** - Check network connection, retry build +4. **Permission issues** - Ensure you have Docker/cloud operation permissions + +### 💡 Debugging Tips + +**1. View detailed logs** +```bash +# Set verbose log level +export LOG_LEVEL=DEBUG +agentkit build +``` + +**2. Verify configuration file** +```bash +# Check if configuration is correct +cat agentkit.yaml +``` + +**3. Execute step by step** +```bash +# Execute separately, easier to locate issues +agentkit build # Build first +agentkit deploy # Then deploy +# Instead of using launch directly +``` + +**4. Check running status** +```bash +# Check if Agent is running normally +agentkit status +``` + +--- + +## Next Steps + +- 📖 [Configuration Guide](./3.configurations.md) - Deep dive into each configuration item +- 🚀 [Quick Start](../1.introduction/3.quickstart.md) - Follow the tutorial to practice +- ❓ [Troubleshooting](../1.introduction/4.troubleshooting.md) - More troubleshooting solutions \ No newline at end of file diff --git a/docs/en/content/2.agentkit-cli/3.configurations.md b/docs/en/content/2.agentkit-cli/3.configurations.md new file mode 100644 index 0000000..f6541cd --- /dev/null +++ b/docs/en/content/2.agentkit-cli/3.configurations.md @@ -0,0 +1,1263 @@ +--- +title: Configuration File Reference +--- + +# Configuration File Reference + +`agentkit.yaml` is the core configuration file for your Agent. It contains all runtime parameters. This document explains what each configuration field does. + +## Configuration system overview + +AgentKit uses a **two-level configuration** architecture: + +| Config file | Location | Purpose | +|------------|----------|---------| +| **Project config** | `./agentkit.yaml` | Project-level config. Each Agent project is independent. | +| **Global config** | `~/.agentkit/config.yaml` | User-level config shared across projects (for example, Volcengine credentials). | + +**Precedence**: + +``` +Environment variables > Project config > Global config > Defaults +``` + +## File structure + +The project config file has three sections: + +```yaml +common: + # Base config (shared by all launch types) + agent_name: my_agent + entry_point: my_agent.py + language: Python + launch_type: cloud + runtime_envs: {} # App-level environment variables + +launch_types: + local: + # Local-only settings + hybrid: + # Hybrid-only settings + cloud: + # Cloud-only settings + +docker_build: + # Docker build config (optional) + base_image: python:3.12-slim + build_script: scripts/setup.sh +``` + +**The three sections**: + +- **common** - shared configuration for all deployment modes +- **launch_types** - mode-specific configuration for different deployment modes +- **docker_build** - optional Docker build customization + +--- + +## `common` + +Base configuration required by all deployment modes. + +### Example + +```yaml +common: + agent_name: my_weather_agent # Agent name (required) + entry_point: my_weather_agent.py # Entry file (required) + description: Weather query agent # Description (optional) + language: Python # Programming language + language_version: '3.12' # Language version + dependencies_file: requirements.txt # Dependency file + launch_type: cloud # Launch type + runtime_envs: # App-level env vars (shared by all launch types) + LOG_LEVEL: info +``` + +### Fields + +#### `agent_name` (required) + +**The Agent name** + +- 📝 **What it does**: gives your Agent a name +- ✅ **Rules**: only letters, numbers, `_`, and `-` +- 🎯 **Used for**: + - Docker image name + - prefix for the cloud Runtime name + - default image repository name + +**Examples**: + +```yaml +agent_name: weather_agent # Recommended: simple and clear +agent_name: financial-analyzer-v2 # OK: includes a version +agent_name: customer_support_bot # OK: descriptive +``` + +#### `entry_point` (required) + +**The entry file for your Agent code** + +- 📝 **What it does**: specifies which file to run +- ✅ **Rules**: must end with `.py`, `.go`, or `.sh` +- 🎯 **Used for**: the container runs this file on startup + +**Examples**: + +```yaml +# Python project +entry_point: app.py +entry_point: server.py + +# Go project +entry_point: main.go +entry_point: cmd/server/main.go + +# Custom startup script +entry_point: start.sh +``` + +#### `description` (optional) + +**A description of the Agent** + +- 📝 **What it does**: briefly explains what the Agent does +- ✅ **Rules**: any text +- 🎯 **Used for**: helping teammates understand the purpose + +**Examples**: + +```yaml +description: "Weather query agent for major cities nationwide" +description: "Customer support assistant for common questions" +``` + +#### `language` (optional) + +**Programming language** + +- 📝 **What it does**: declares the language used by the project +- ✅ **Options**: `Python`, `Golang` +- ✅ **Default**: `Python` +- 🎯 **Used for**: choosing the Dockerfile template and build workflow + +**Examples**: + +```yaml +language: Python # Python project +language: Golang # Go project +``` + +#### `language_version` (optional) + +**Language runtime version** + +- 📝 **What it does**: specifies the language version +- ✅ **Python supported**: `3.10`, `3.11`, `3.12`, `3.13` +- ✅ **Golang supported**: `1.24` +- ✅ **Default**: Python `3.12`, Golang `1.24` + +**Examples**: + +```yaml +# Python project +language: Python +language_version: '3.12' + +# Go project +language: Golang +language_version: '1.24' +``` + +> ⚠️ **Note**: `python_version` is deprecated. Use `language_version` instead. + +#### `dependencies_file` (optional) + +**Dependency list file** + +- 📝 **What it does**: sets the path to your dependency file +- ✅ **Default**: `requirements.txt` for Python projects; `go.mod` for Go projects +- 🎯 **Used for**: installing dependencies during build + +**Examples**: + +```yaml +# Python project +dependencies_file: requirements.txt +dependencies_file: requirements/prod.txt + +# Go project +dependencies_file: go.mod +``` + +#### `launch_type` (required) + +**Deployment and runtime mode** + +- 📝 **What it does**: selects where to build and run +- ✅ **Options**: `local`, `hybrid`, `cloud` + +| Mode | Best for | Build location | Run location | +|------|----------|----------------|--------------| +| `local` | local development & debugging | your machine | your machine | +| `hybrid` | transition phase | your machine | cloud platform | +| `cloud` | production | cloud platform | cloud platform | + +**Examples**: + +```yaml +launch_type: local # local development +launch_type: hybrid # build locally + deploy to cloud +launch_type: cloud # production (recommended) +``` + +#### `cloud_provider` (optional) + +**Cloud provider (platform service provider)** + +- 📝 **What it does**: choose whether platform services use Volcano Engine (China) or BytePlus (Overseas) +- ✅ **Options**: `volcengine`, `byteplus` +- ✅ **Default**: `volcengine` +- 🎯 **Used for**: + - affects default region, endpoint, and credential namespace + - affects the default base image used for auto-generated Dockerfiles (when `docker_build.base_image` is not explicitly set) + +**Precedence (highest to lowest)**: + +``` +Environment variables > Project config (agentkit.yaml) > Global config (~/.agentkit/config.yaml) > Defaults +``` + +**How to configure**: + +```yaml +# 1) Project config (recommended: put it in agentkit.yaml) +common: + cloud_provider: byteplus +``` + +```bash +# 1.1) Project config (write to agentkit.yaml via non-interactive command) +agentkit config --cloud_provider byteplus +``` + +```yaml +# 2) Global config (applies across projects) +defaults: + cloud_provider: byteplus +``` + +```bash +# 3) Environment variables (temporary override) +export CLOUD_PROVIDER=byteplus +``` + +#### `runtime_envs` (optional) + +**App-level environment variables** + +- 📝 **What it does**: defines environment variables shared by all deployment modes +- 🎯 **Used for**: common configuration such as log level +- ⚠️ **Precedence**: policy-level `runtime_envs` override variables with the same name defined at the app level + +**Example**: + +```yaml +common: + runtime_envs: + LOG_LEVEL: info + APP_ENV: production +``` + +--- + +## Local launch type + +Build and run on local Docker. Best for development and debugging. + +### Example + +```yaml +launch_types: + local: + image_tag: latest # Image tag + invoke_port: 8000 # App port + container_name: my_agent # Container name (optional) + runtime_envs: # Policy-level env vars + MODEL_AGENT_API_KEY: xxx + ports: # Port mappings + - "8000:8000" + restart_policy: unless-stopped # Restart policy + memory_limit: 1g # Memory limit + cpu_limit: '1' # CPU limit +``` + +### Fields + +#### `image_tag` + +**Image version tag** + +- Default: `latest` +- Purpose: distinguishes different image versions +- Examples: `latest`, `v1.0`, `dev` + +#### `invoke_port` + +**The port your Agent listens on** + +- Default: `8000` +- Purpose: sets which port the app listens on +- ❗ Must match the port used in your code + +#### `container_name` + +**Docker container name** + +- Default: uses `agent_name` +- Purpose: assigns a name to the container +- Can be omitted; a name will be generated automatically + +#### `runtime_envs` + +**Policy-level runtime environment variables** + +Environment variables passed into the container, such as API keys and configuration parameters. +They are merged with `common.runtime_envs`; variables with the same name override the app-level ones. + +```yaml +runtime_envs: + MODEL_AGENT_API_KEY: your_api_key # Model API key + DEBUG: 'true' # Enable debugging + LOG_LEVEL: debug # Override LOG_LEVEL from common +``` + +#### `ports` + +**Port mappings** + +Maps container ports to host ports using `host_port:container_port`. + +```yaml +ports: + - "8080:8000" # Host 8080 maps to container 8000 + - "9090:9090" # Monitoring port +``` + +#### `volumes` + +**Volume mounts** + +Mounts host directories into the container using `host_path:container_path`. + +```yaml +volumes: + - "./data:/app/data" # Data directory + - "./logs:/app/logs" # Log directory +``` + +#### `restart_policy` + +**Container restart policy** + +- Default: `unless-stopped` +- Options: + - `no` - do not restart + - `on-failure` - restart on failures + - `always` - always restart + - `unless-stopped` - restart unless manually stopped + +#### `memory_limit` / `cpu_limit` + +**Resource limits** + +Limits the resources a container can use, preventing it from consuming too much. + +```yaml +memory_limit: 2g # Limit to 2GB memory +cpu_limit: '1' # Limit to 1 CPU core +``` + +### Auto-managed fields + +The following fields are generated and managed by the CLI; **you do not need to set them manually**: + +| Field | Description | +|------|-------------| +| `container_id` | Container ID after deployment | +| `image_id` | Image ID after build | +| `build_timestamp` | Build time | +| `deploy_timestamp` | Deployment time | +| `full_image_name` | Full image name (e.g. `my-agent:latest`) | + +--- + +## Cloud launch type + +Build and run on Volcengine. Best for production. + +### Example + +```yaml +launch_types: + cloud: + region: cn-beijing # Region + image_tag: "{{timestamp}}" # Image tag (template variables supported) + + # TOS (object storage) settings + tos_bucket: Auto # Auto-create bucket + + # Container Registry settings + cr_instance_name: Auto # CR instance name (Auto = auto-create) + cr_namespace_name: agentkit # CR namespace + cr_repo_name: "" # CR repo name (empty = use agent_name) + + # Runtime settings + runtime_name: Auto # Runtime name + runtime_role_name: Auto # IAM role name + runtime_apikey_name: Auto # API key secret name + + # Environment variables + runtime_envs: + MODEL_AGENT_API_KEY: xxx # Model API key + MODEL_AGENT_NAME: ep-xxx # Model endpoint +``` + +### Template variables + +Cloud mode supports **template variables**, rendered automatically during build/deploy: + +| Variable | Description | Example value | +|---------|-------------|---------------| +| `{{timestamp}}` | Current timestamp (YYYYMMDDHHmmss) | `20251128153042` | +| `{{account_id}}` | Volcengine account ID | `2100123456` | + +**Examples**: + +```yaml +image_tag: "{{timestamp}}" # Unique tag for each build +cr_instance_name: "agentkit-platform-{{account_id}}" # Account-isolated CR instance +tos_bucket: "agentkit-platform-{{account_id}}" # Account-isolated bucket +``` + +### The `Auto` keyword + +When a value is `Auto`, the CLI will automatically create or manage the corresponding resource: + +| Field | Auto behavior | +|------|---------------| +| `tos_bucket` | Auto-create bucket `agentkit-platform-{{account_id}}` | +| `cr_instance_name` | Auto-create CR instance `agentkit-platform-{{account_id}}` | +| `runtime_name` | Auto-create Runtime | +| `runtime_role_name` | Auto-create IAM role | +| `runtime_apikey_name` | Auto-create API key secret | + +### Fields + +#### `region` + +**Volcengine region** + +- Default: `cn-beijing` +- Purpose: selects the geographic location where the service runs +- Options: `cn-beijing` (currently only Beijing is supported) + +💡 **Tip**: choose the region closest to your users to reduce latency. + +#### `image_tag` + +**Image version tag** + +- Default: `{{timestamp}}` (generates a unique tag each build) +- Purpose: distinguishes different versions +- Examples: `{{timestamp}}`, `latest`, `v1.0.0` + +```yaml +# Option 1: use a timestamp (recommended; ensures uniqueness) +image_tag: "{{timestamp}}" + +# Option 2: fixed version +image_tag: v1.0.0 + +# Option 3: use latest (not recommended for production) +image_tag: latest +``` + +#### `tos_bucket` + +**Object storage bucket** + +- Default: `Auto` (auto-create) +- Purpose: stores the source code archive (for cloud builds) +- Security note: `tos_bucket` must belong to your current account. If you set another person's bucket name (e.g. a public read-write bucket), the CLI will block uploads and ask you to change it. + +```yaml +# Auto-create (recommended) +tos_bucket: Auto + +# Use an existing bucket +tos_bucket: my-existing-bucket +``` + +#### `cr_instance_name` + +**Container Registry instance name** + +- Default: `Auto` (auto-create) +- Purpose: selects which CR instance stores your Docker images + +```yaml +# Auto-create +cr_instance_name: Auto + +# Use an existing instance +cr_instance_name: my-existing-cr +``` + +#### `cr_namespace_name` + +**CR namespace** + +- Default: `agentkit` +- Purpose: organizes and manages images +- Auto-create: created automatically if missing + +#### `cr_repo_name` + +**CR repository name** + +- Default: empty (uses `agent_name`) +- Purpose: the repository that stores the image +- Auto-create: created automatically if missing + +#### `runtime_name` / `runtime_role_name` / `runtime_apikey_name` + +**Runtime-related settings** + +- Default: `Auto` (auto-create) +- Purpose: manages the cloud runtime instance and its authentication + +```yaml +runtime_name: Auto # Runtime name +runtime_role_name: Auto # IAM role +runtime_apikey_name: Auto # API key secret name +``` + +#### `runtime_envs` + +**Policy-level runtime environment variables** + +Configuration required by the Agent at runtime. The most important values are model API credentials. +They are merged with `common.runtime_envs`. + +**Required**: + +```yaml +runtime_envs: + MODEL_AGENT_API_KEY: xxx # Volcano Ark API key + MODEL_AGENT_NAME: ep-xxx # Volcano Ark endpoint ID +``` + +**Optional** (enhanced capabilities): + +```yaml +runtime_envs: + # Base settings + MODEL_AGENT_API_KEY: xxx + MODEL_AGENT_NAME: ep-xxx + + # Observability (logs, metrics, tracing) + OBSERVABILITY_OPENTELEMETRY_APMPLUS_API_KEY: xxx + OBSERVABILITY_OPENTELEMETRY_APMPLUS_ENDPOINT: http://apmplus-cn-beijing.volces.com:4317 + OBSERVABILITY_OPENTELEMETRY_APMPLUS_SERVICE_NAME: my_agent + + # Other settings + DEBUG: 'true' # Enable debug mode + LOG_LEVEL: info # Set log level +``` + +#### `build_timeout` + +**Build timeout** + +- Default: `3600` (seconds) +- Purpose: maximum wait time for a cloud build + +### Auto-managed fields + +The following fields are generated and managed by the CLI; **you do not need to set them manually**: + +**TOS storage-related** + +| Field | Description | +|------|-------------| +| `tos_prefix` | Object storage prefix (default `agentkit-builds`) | +| `tos_region` | TOS region | +| `tos_object_key` | Storage path for the code package | +| `tos_object_url` | URL for the code package | + +**Code Pipeline build-related** + +| Field | Description | +|------|-------------| +| `cp_workspace_name` | Build workspace name | +| `cp_pipeline_name` | Build pipeline name | +| `cp_pipeline_id` | Pipeline ID | + +**Image-related** + +| Field | Description | +|------|-------------| +| `cr_region` | Image registry region | +| `cr_image_full_url` | Full image URL | + +**Runtime-related** + +| Field | Description | +|------|-------------| +| `runtime_id` | Runtime instance ID | +| `runtime_endpoint` | Application access URL | +| `runtime_apikey` | Runtime API key | +| `build_timestamp` | Build time | +| `deploy_timestamp` | Deployment time | + +--- + +## Hybrid launch type + +Build locally and run in the cloud. This is useful during development and debugging: you can build images quickly on your machine and then run them on the cloud. + +### Example + +```yaml +launch_types: + hybrid: + region: cn-beijing # Cloud region + image_tag: "{{timestamp}}" # Image tag (template variables supported) + + # Container Registry settings + cr_instance_name: Auto # CR instance name + cr_namespace_name: agentkit # CR namespace + cr_repo_name: "" # CR repo name + + # Runtime settings + runtime_name: Auto # Runtime name + runtime_role_name: Auto # IAM role name + runtime_apikey_name: Auto # API key secret name + + # Environment variables + runtime_envs: + MODEL_AGENT_API_KEY: xxx # Model API key + MODEL_AGENT_NAME: ep-xxx # Model endpoint +``` + +### Differences from Cloud mode + +| Item | Hybrid | Cloud | +|------|--------|-------| +| **Build location** | Local Docker | Cloud Code Pipeline | +| **TOS settings** | Not required | Required (stores the code package) | +| **Build speed** | Fast (local) | Slower (upload + cloud build) | +| **Best for** | Development & debugging | Production | + +### Fields + +Hybrid mode is largely the same as Cloud mode, but **does not require TOS-related settings** (because local builds do not upload a source archive). + +#### `region` + +**Volcengine region** + +- Default: `cn-beijing` +- Purpose: selects the geographic location where the cloud service runs + +#### `image_tag` + +**Image version tag** + +- Default: `{{timestamp}}` +- Purpose: distinguishes different image versions +- Template variables supported + +#### `cr_instance_name` / `cr_namespace_name` / `cr_repo_name` + +**Container Registry settings** + +Same as Cloud mode. Used to store the locally built image. + +```yaml +cr_instance_name: Auto # Auto-create CR instance +cr_namespace_name: agentkit # Namespace +cr_repo_name: "" # Repo name (empty = use agent_name) +``` + +#### `runtime_name` / `runtime_role_name` / `runtime_apikey_name` + +**Runtime settings** + +Same as Cloud mode. Used to manage the cloud runtime instance. + +#### `runtime_envs` + +**Policy-level runtime environment variables** + +Same as Cloud mode. Environment variables passed to the cloud runtime. + +### Auto-managed fields + +The following fields are generated and managed by the CLI; **you do not need to set them manually**: + +| Field | Description | +|------|-------------| +| `image_id` | Image ID built locally | +| `build_timestamp` | Build time | +| `full_image_name` | Full image name | +| `cr_image_full_url` | Full image URL in CR | +| `runtime_id` | Runtime instance ID | +| `runtime_endpoint` | Application access URL | +| `runtime_apikey` | Runtime API key | + +--- + +## `docker_build` + +Customize the Docker build process. Supports custom base images, build scripts, and more. + +### Example + +```yaml +docker_build: + # Python project - string form + base_image: "python:3.12-slim" + + # Custom build script + build_script: "scripts/setup.sh" + + # Force regenerate Dockerfile + regenerate_dockerfile: false + + # Target platform (cross-platform builds) + platform: "linux/amd64" +``` + +**Multi-stage build for Go projects**: + +```yaml +docker_build: + base_image: + builder: "golang:1.24-alpine" # Builder stage image + runtime: "alpine:latest" # Runtime stage image + build_script: "scripts/install_certs.sh" +``` + +### Fields + +#### `base_image` + +**Custom base image** + +- Default: chosen automatically based on language +- Python default: uses AgentKit prebuilt base images and switches automatically according to `common.cloud_provider` + - volcengine: `agentkit-prod-public-cn-beijing.cr.volces.com/base/py-simple:python-bookworm-slim-latest` + - byteplus: `agentkit-prod-public-ap-southeast-1.cr.bytepluses.com/base/py-simple:python-bookworm-slim-latest` +- Golang default: `agentkit-cn-beijing.cr.volces.com/base/compile_basego:1.24` (build) + `agentkit-cn-beijing.cr.volces.com/base/runtime_basego:latest` (runtime) + +```yaml +# Python project - string +base_image: "python:3.12-alpine" + +# Go project - mapping (multi-stage build) +base_image: + builder: "golang:1.24-alpine" + runtime: "alpine:latest" +``` + +#### `build_script` + +**Custom build script** + +- Default: none +- Purpose: runs a custom script during Docker build +- Path: relative to the project root + +**Typical use cases**: + +- install system dependencies +- compile C extensions +- download additional resources + +```yaml +build_script: "scripts/setup.sh" +build_script: "docker/install_deps.sh" +``` + +#### `regenerate_dockerfile` + +**Force regenerate Dockerfile** + +- Default: `false` +- Purpose: regenerate even if a Dockerfile already exists +- CLI flag: `--regenerate-dockerfile` + +#### `platform` + +**Target CPU architecture** + +- Default: current system architecture +- Purpose: cross-platform builds +- CLI flag: `--platform` + +```yaml +platform: "linux/amd64" # x86_64 +platform: "linux/arm64" # ARM (e.g. Apple Silicon) +``` + +--- + +## Global configuration + +Global configuration is stored in `~/.agentkit/config.yaml` and shared across projects. + +### Location + +``` +~/.agentkit/config.yaml +``` + +### Example + +```yaml +# Volcengine credentials +volcengine: + access_key: "AKLTxxxxxxxx" + secret_key: "xxxxxxxx" + region: "cn-beijing" + +# Default Container Registry settings +cr: + instance_name: "my-team-cr-instance" + namespace_name: "my-team" + +# Default TOS settings +tos: + bucket: "my-team-bucket" + prefix: "agentkit-builds" + region: "cn-beijing" +``` + +### Precedence + +When a project config value is empty or set to `Auto`, AgentKit will automatically fall back to global config: + +``` +1. Explicit values in project config (highest) +2. Global config (~/.agentkit/config.yaml) +3. Defaults (lowest) +``` + +### Typical use cases + +**Shared team configuration** + +Teammates can share the same CR instance and TOS bucket: + +```yaml +# ~/.agentkit/config.yaml +cr: + instance_name: "team-shared-cr" + namespace_name: "team-agents" + +tos: + bucket: "team-shared-bucket" +``` + +Then in the project config, set the fields to `Auto` to reuse the team settings: + +```yaml +# agentkit.yaml +launch_types: + cloud: + cr_instance_name: Auto # Uses team-shared-cr from global config + tos_bucket: Auto # Uses team-shared-bucket from global config +``` + +--- + +## Best practices + +### 🌍 Multi-environment management + +Create separate config files for different environments: + +```bash +agentkit.dev.yaml # Development (local) +agentkit.test.yaml # Testing (hybrid) +agentkit.prod.yaml # Production (cloud) +``` + +**Usage**: + +```bash +# Development +agentkit launch --config-file agentkit.dev.yaml + +# Production +agentkit launch --config-file agentkit.prod.yaml +``` + +### 🔐 Secure handling of secrets + +**❌ Bad practice** (hard-coding): + +```yaml +runtime_envs: + MODEL_AGENT_API_KEY: c05d49af-1234-5678-abcd-xxxx # Don't do this! +``` + +**✅ Recommended approaches**: + +**Option 1**: interactive configuration + +```bash +agentkit config # Enter sensitive values interactively +``` + +**Option 2**: use `.gitignore` + +```bash +# .gitignore +agentkit.local.yaml # Don't commit local config +agentkit.prod.yaml # Don't commit prod config +*.secret.yaml # Any config file containing secrets +``` + +**Option 3**: create a config template + +```yaml +# agentkit.yaml.template (commit to Git) +runtime_envs: + MODEL_AGENT_API_KEY: + MODEL_AGENT_NAME: +``` + +### 📝 Add helpful comments + +Make config easier for teammates to understand: + +```yaml +common: + agent_name: weather_agent + entry_point: app.py + launch_type: cloud # Use cloud deployment for production + +launch_types: + cloud: + region: cn-beijing # Beijing region, closest to users + runtime_envs: + # Volcano Ark model access credentials + MODEL_AGENT_API_KEY: xxx + MODEL_AGENT_NAME: ep-xxx +``` + +### ✅ Validate configuration regularly + +Keep your config valid: + +```bash +# Option 1: run the config command to validate +agentkit config + +# Option 2: inspect the config file +cat agentkit.yaml + +# Option 3: try building (without deploying) +agentkit build +``` + +--- + +## Full examples + +### 📱 Local development config (Python) + +Good for rapid iteration and debugging: + +```yaml +common: + agent_name: dev_weather_agent + entry_point: app.py + description: Weather query agent for development + language: Python + language_version: '3.12' + launch_type: local + runtime_envs: + APP_ENV: development + +launch_types: + local: + image_tag: dev + invoke_port: 8000 + runtime_envs: + MODEL_AGENT_API_KEY: xxx + DEBUG: 'true' # Enable debugging + LOG_LEVEL: debug # Verbose logs + ports: + - "8000:8000" + memory_limit: 512m # Lower limits for dev + cpu_limit: '0.5' +``` + +### Golang project config + +An example configuration for a Go Agent: + +```yaml +common: + agent_name: go_agent + entry_point: main.go + description: Golang agent + language: Golang + language_version: '1.24' + dependencies_file: go.mod + launch_type: hybrid + +launch_types: + hybrid: + region: cn-beijing + image_tag: "{{timestamp}}" + cr_instance_name: Auto + cr_namespace_name: agentkit + runtime_envs: + MODEL_AGENT_API_KEY: xxx + +docker_build: + base_image: + builder: "golang:1.24-alpine" + runtime: "alpine:latest" +``` + +### Production config + +Suitable for going live: + +```yaml +common: + agent_name: prod_weather_agent + entry_point: server.py + description: Weather query agent for production + language: Python + language_version: '3.12' + launch_type: cloud + runtime_envs: + APP_ENV: production + LOG_LEVEL: info + +launch_types: + cloud: + region: cn-beijing + image_tag: "{{timestamp}}" # Use a timestamp to ensure uniqueness + + # CR settings + cr_instance_name: Auto + cr_namespace_name: production + cr_repo_name: weather_agent + + # TOS settings + tos_bucket: Auto + + # Runtime settings + runtime_name: Auto + runtime_role_name: Auto + runtime_apikey_name: Auto + + runtime_envs: + # Base settings + MODEL_AGENT_API_KEY: xxx + MODEL_AGENT_NAME: ep-xxx + + # Observability (recommended in production) + OBSERVABILITY_OPENTELEMETRY_APMPLUS_API_KEY: xxx + OBSERVABILITY_OPENTELEMETRY_APMPLUS_ENDPOINT: http://apmplus-cn-beijing.volces.com:4317 + OBSERVABILITY_OPENTELEMETRY_APMPLUS_SERVICE_NAME: prod_weather_agent + +docker_build: + base_image: "python:3.12-slim" +``` + +### 🎯 Minimal configuration examples + +**Local mode** (minimal): + +```yaml +common: + agent_name: simple-agent + entry_point: agent.py + launch_type: local +``` + +**Cloud mode** (minimal): + +```yaml +common: + agent_name: cloud-agent + entry_point: main.py + launch_type: cloud + +launch_types: + cloud: + region: cn-beijing + runtime_envs: + MODEL_AGENT_API_KEY: xxx +``` + +--- + +## FAQ + +### ❓ Configuration file not found + +``` +Error: Configuration file not found +``` + +**Fix**: + +```bash +agentkit init my_agent # Create a new project +# or +agentkit config # Create config +``` + +### ❓ Invalid YAML format + +``` +Error: Invalid YAML format +``` + +**Checklist**: + +- ✅ Use spaces for indentation (do not use tabs) +- ✅ Ensure there is a space after `:` +- ✅ Quote strings containing special characters +- ✅ Quote template variables: `"{{timestamp}}"` + +### ❓ Missing required fields + +``` +Error: agent_name is required +``` + +**Fix**: + +```bash +agentkit config # Reconfigure and fill required fields +``` + +### ❓ Template variables failed to render + +``` +Error: Config field 'cr_instance_name' template variables were not fully rendered +``` + +**Possible causes**: + +1. Volcengine credentials are not configured +2. Insufficient AK/SK permissions + +**Fix**: + +```bash +# Check environment variables +echo $VOLC_ACCESSKEY +echo $VOLC_SECRETKEY + +# Or check global config +cat ~/.agentkit/config.yaml +``` + +### ❓ Environment variables not taking effect + +**Possible causes**: + +1. Variable name typo +2. Config was not saved +3. Not redeployed +4. Confusing `common.runtime_envs` with policy-level `runtime_envs` + +**Fix**: + +```bash +# 1) Check config +cat agentkit.yaml + +# 2) Confirm env var placement +# common.runtime_envs - shared by all modes +# launch_types..runtime_envs - specific to the chosen mode + +# 3) Redeploy +agentkit deploy +``` + +### ❓ Legacy field names are incompatible + +If your config uses legacy field names (for example `ve_cr_instance_name` or `python_version`), update them to the new names: + +| Legacy field | New field | +|-------------|-----------| +| `python_version` | `language_version` | +| `ve_cr_instance_name` | `cr_instance_name` | +| `ve_cr_namespace_name` | `cr_namespace_name` | +| `ve_cr_repo_name` | `cr_repo_name` | +| `ve_runtime_id` | `runtime_id` | +| `ve_runtime_name` | `runtime_name` | +| `ve_runtime_endpoint` | `runtime_endpoint` | + +> 💡 **Tip**: the CLI still supports legacy field names (via aliases), but migration is recommended. + +--- + +## Configuration field quick reference + +### `common` fields + +| Field | Required | Default | Description | +|------|----------|---------|-------------| +| `agent_name` | ✅ | - | Agent name | +| `entry_point` | ✅ | - | Entry file | +| `description` | ❌ | empty | Description | +| `language` | ❌ | `Python` | Programming language | +| `language_version` | ❌ | `3.12`/`1.24` | Language version | +| `dependencies_file` | ❌ | auto-detected | Dependency file | +| `launch_type` | ❌ | `local` | Launch type | +| `runtime_envs` | ❌ | `{}` | App-level environment variables | + +### Cloud/Hybrid fields + +| Field | Default | Description | +|------|---------|-------------| +| `region` | `cn-beijing` | Volcengine region | +| `image_tag` | `{{timestamp}}` | Image tag | +| `cr_instance_name` | `Auto` | CR instance name | +| `cr_namespace_name` | `agentkit` | CR namespace | +| `cr_repo_name` | empty (uses agent_name) | CR repository name | +| `runtime_name` | `Auto` | Runtime name | +| `runtime_envs` | `{}` | Policy-level environment variables | + +### `docker_build` fields + +| Field | Default | Description | +|------|---------|-------------| +| `base_image` | auto-selected | Base image | +| `build_script` | none | Build script | +| `regenerate_dockerfile` | `false` | Force regenerate | +| `platform` | current arch | Target platform | + +--- + +## Next steps + +- 📖 [CLI Overview](./1.overview.md) - learn the main capabilities and concepts +- 🎮 [Commands](./2.commands.md) - learn how each command works +- 🚀 [Quick Start](../1.introduction/3.quickstart.md) - follow an end-to-end walkthrough diff --git a/docs/en/content/2.agentkit-cli/4.logging.md b/docs/en/content/2.agentkit-cli/4.logging.md new file mode 100644 index 0000000..3e09142 --- /dev/null +++ b/docs/en/content/2.agentkit-cli/4.logging.md @@ -0,0 +1,481 @@ +# Logging System + +AgentKit CLI comes with a flexible built-in logging system to help you understand command execution, debug issues, and track runtime status. + +## Default Behavior + +AgentKit defaults to the following: + +- ✅ **Console output**: Disabled (no logs displayed) +- ✅ **File logging**: Disabled (no logs recorded) +- 💡 **Enable on demand**: Turn logging on via environment variables as needed + +```bash +# By default, commands run with no log output +agentkit status + +# If you need logs, enable them via environment variables (see below) +``` + +**Log example**: + +``` +[2025-11-20 14:56:09] [INFO] [agentkit.toolkit.executors] Loading configuration... +[2025-11-20 14:56:09] [INFO] [agentkit.toolkit.executors] Using launch_type: cloud +[2025-11-20 14:56:09] [INFO] [agentkit.toolkit.executors] Querying status with cloud strategy... +[2025-11-20 14:56:09] [INFO] [agentkit.toolkit.executors] Status query completed: running +``` + +--- + +## Quick Start + +### Enable File Logging + +If you want to save logs to a file: + +```bash +# Enable file logging (default INFO level) +export AGENTKIT_FILE_ENABLED=true + +# Run a command +agentkit deploy + +# View the generated log file +cat .agentkit/logs/agentkit-$(date +%Y%m%d).log +``` + +### Enable Console Logging + +If you want to view logs in real time in the console: + +```bash +# Enable console logging +export AGENTKIT_LOG_CONSOLE=true + +# Run a command; now you can see logs in the console +agentkit status +``` + +### Enable Both Console and File Logging + +```bash +# Enable both console and file logging +export AGENTKIT_LOG_CONSOLE=true +export AGENTKIT_FILE_ENABLED=true + +# Run a command +agentkit build +``` + +### Debug Mode + +When you need detailed logs to investigate an issue: + +```bash +# Enable DEBUG-level logging (enable console and file output) +export AGENTKIT_LOG_LEVEL=DEBUG +export AGENTKIT_LOG_CONSOLE=true +export AGENTKIT_FILE_ENABLED=true + +# Run a command to view detailed debug information +agentkit build +``` + +--- + +## Environment Variable Configuration + +With environment variables, you can fully customize logging behavior. + +### Basic Configuration + +| Environment Variable | Description | Default | Example | +|----------|------|--------|------| +| `AGENTKIT_LOG_CONSOLE` | Whether to display logs in the console | `false` | `true` / `false` | +| `AGENTKIT_FILE_ENABLED` | Whether to save logs to a file | `false` | `true` / `false` | +| `AGENTKIT_LOG_LEVEL` | Log level (console and file) | `INFO` | `DEBUG` / `INFO` / `WARNING` / `ERROR` | +| `AGENTKIT_LOG_FILE` | Log file path (takes effect when file logging is enabled) | `.agentkit/logs/agentkit-YYYYMMDD.log` | `/tmp/my-agent.log` | + +### Advanced Configuration + +Control log levels for console and file separately: + +| Environment Variable | Description | Default | +|----------|------|--------| +| `AGENTKIT_CONSOLE_LOG_LEVEL` | Console log level | `INFO` | +| `AGENTKIT_FILE_LOG_LEVEL` | File log level | `INFO` | + +**Example**: + +```bash +# Show only important errors in the console, but record everything to a file +export AGENTKIT_LOG_CONSOLE=true +export AGENTKIT_CONSOLE_LOG_LEVEL=ERROR +export AGENTKIT_FILE_LOG_LEVEL=DEBUG + +agentkit launch +``` + +--- + +## Log Levels + +AgentKit supports 5 log levels. The higher the level, the fewer messages you see: + +| Level | Description | Typical Use Cases | +|------|------|----------| +| `DEBUG` | Detailed debugging information | Troubleshooting, development/debugging | +| `INFO` | General operational information (default) | Understanding command execution flow | +| `WARNING` | Warning messages | Tracking potential issues | +| `ERROR` | Error messages | Focusing on failed operations | +| `CRITICAL` | Critical errors | Seeing only fatal failures | + +--- + +## Common Scenarios + +### Scenario 1: Normal Use (Default Configuration) + +Suitable for day-to-day use: no log output to protect sensitive information. + +```bash +# No configuration needed; just use it +agentkit status +agentkit deploy +``` + +**Effect**: +- ✅ Console: clean and tidy, no log output +- ✅ Files: no log files generated, protecting sensitive information + +--- + +### Scenario 1.1: Need to Save Log Records + +Enable file logging to help trace operational history: + +```bash +# Enable file logging +export AGENTKIT_FILE_ENABLED=true + +# Run a command +agentkit deploy +``` + +**Effect**: +- ✅ Console: clean and tidy +- ✅ Logs: automatically saved to `.agentkit/logs/` at INFO level by default + +--- + +### Scenario 2: Debugging Issues + +When encountering errors or abnormal behavior, enable detailed logs: + +```bash +# Enable DEBUG logs for both console and file +export AGENTKIT_LOG_CONSOLE=true +export AGENTKIT_FILE_ENABLED=true +export AGENTKIT_LOG_LEVEL=DEBUG + +# Run a command +agentkit build +``` + +**Effect**: +- ✅ Console: shows detailed execution steps +- ✅ Log file: records full DEBUG details for post-incident analysis + +--- + +### Scenario 3: CI/CD Environment + +In CI, you typically want logs in the console and also keep a full record: + +```bash +# Set in your CI configuration file +export AGENTKIT_LOG_CONSOLE=true +export AGENTKIT_FILE_ENABLED=true +export AGENTKIT_CONSOLE_LOG_LEVEL=INFO +export AGENTKIT_FILE_LOG_LEVEL=DEBUG +export AGENTKIT_LOG_FILE=/var/log/agentkit/build-${BUILD_ID}.log + +# Run the build +agentkit launch +``` + +**Effect**: +- ✅ Console: shows key information for CI log review +- ✅ Log file: keeps detailed information for later analysis + +--- + +### Scenario 4: Production Environment + +In production, record only warnings and errors to a file: + +```bash +export AGENTKIT_FILE_ENABLED=true +export AGENTKIT_FILE_LOG_LEVEL=WARNING +export AGENTKIT_LOG_FILE=/var/log/agentkit/production.log + +# Run a command +agentkit deploy +``` + +**Effect**: +- ✅ Console: no output, stays clean +- ✅ Log file: records only warnings and errors, focusing on issues + +--- + +### Scenario 5: Fully Silent + +When you don’t need any logs (default behavior): + +```bash +# Default configuration is fully silent; no environment variables needed +agentkit status + +# Or set explicitly (to ensure previous env vars do not affect) +unset AGENTKIT_LOG_CONSOLE +unset AGENTKIT_FILE_ENABLED +``` + +**Effect**: +- ✅ Console: no log output +- ✅ Files: no log files generated + +--- + +## Log File Management + +### Log File Location + +When file logging is enabled (`AGENTKIT_FILE_ENABLED=true`), logs are stored under `.agentkit/logs/` in the project root: + +``` +your-project/ +├── .agentkit/ +│ └── logs/ +│ ├── agentkit-20251120.log # Today's logs +│ ├── agentkit-20251119.log # Yesterday's logs +│ └── agentkit-20251118.log # The day before yesterday's logs +├── agentkit.yaml +└── my_agent.py +``` + +### Automatic Cleanup of Old Logs + +Log files accumulate over time; it’s recommended to clean them up periodically: + +```bash +# Delete logs older than 7 days +find .agentkit/logs -name "agentkit-*.log" -mtime +7 -delete + +# Or delete manually +rm .agentkit/logs/agentkit-20251101.log +``` + +### Custom Log Path + +```bash +# Save to a specific location +export AGENTKIT_LOG_FILE=/tmp/my-custom-agent.log + +# Or save to a user directory +export AGENTKIT_LOG_FILE=$HOME/.agentkit-logs/agent.log + +agentkit deploy +``` + +--- + +## Configuration Precedence + +When multiple configuration methods are present, the precedence is (high to low): + +1. **Dedicated environment variables** - `AGENTKIT_CONSOLE_LOG_LEVEL` +2. **General environment variables** - `AGENTKIT_LOG_LEVEL` +3. **Default value** - `INFO` + +**Example**: + +```bash +# Set the general level to INFO +export AGENTKIT_LOG_LEVEL=INFO + +# Set a dedicated console level to WARNING (higher priority) +export AGENTKIT_CONSOLE_LOG_LEVEL=WARNING + +# Result: console shows WARNING, file records INFO +agentkit status +``` + +--- + +## Troubleshooting + +### No Log File Created + +**Possible causes**: +- File logging is disabled +- Insufficient directory permissions + +**How to fix**: + +```bash +# 1. Check whether file logging is disabled +echo $AGENTKIT_FILE_ENABLED # should be true or empty + +# 2. Check directory permissions +ls -la .agentkit/logs/ + +# 3. Create the directory manually +mkdir -p .agentkit/logs + +# 4. Ensure environment variables are correct +unset AGENTKIT_FILE_ENABLED # reset to default +``` + +--- + +### No Console Log Output + +**Possible causes**: +- Console logging is disabled by default +- Log level is set too high + +**How to fix**: + +```bash +# 1. Enable console logging +export AGENTKIT_LOG_CONSOLE=true + +# 2. Set an appropriate log level +export AGENTKIT_CONSOLE_LOG_LEVEL=INFO + +# 3. Run a command +agentkit status +``` + +--- + +### Too Many or Too Few Logs + +**Adjust the log level**: + +```bash +# Too many logs - show only important information +export AGENTKIT_LOG_LEVEL=WARNING + +# Too few logs - view detailed information +export AGENTKIT_LOG_LEVEL=DEBUG +``` + +--- + +## Best Practices + +### Recommended Development Configuration + +Optionally add to your `.bashrc` or `.zshrc`: + +```bash +# AgentKit development environment configuration (choose as needed) +# Option 1: Enable console logs only +export AGENTKIT_LOG_CONSOLE=true + +# Option 2: Enable both console and file logs +export AGENTKIT_LOG_CONSOLE=true +export AGENTKIT_FILE_ENABLED=true +export AGENTKIT_CONSOLE_LOG_LEVEL=INFO +export AGENTKIT_FILE_LOG_LEVEL=DEBUG +``` + +**Recommendations**: +- Keep it unconfigured by default to stay clean +- Enable temporarily when debugging +- Avoid accidentally recording sensitive information + +--- + +### Team Collaboration + +Create a `.env.example` file in the project root: + +```bash +# AgentKit logging configuration example +# Copy to .env and modify as needed + +# === Recommended dev configuration === +# Enable console logs (for real-time viewing) +AGENTKIT_LOG_CONSOLE=true + +# Enable file logging (optional; useful for tracing issues) +# AGENTKIT_FILE_ENABLED=true + +# Set log level +AGENTKIT_LOG_LEVEL=INFO + +# Custom log path (optional) +# AGENTKIT_LOG_FILE=./logs/my-agent.log +``` + +**Reminder**: +- Team members should adjust based on their needs +- `.env` should be in `.gitignore` to avoid committing personal configuration +- Keep file logging disabled by default to protect sensitive information + +--- + +### Production Deployment Recommendations + +```bash +# Production configuration +export AGENTKIT_LOG_CONSOLE=false # Disable console +export AGENTKIT_FILE_ENABLED=true # Enable file logging +export AGENTKIT_FILE_LOG_LEVEL=WARNING # Record warnings and errors only +export AGENTKIT_LOG_FILE=/var/log/agentkit/prod.log # Unified path +``` + +**Benefits**: +- Reduces unnecessary output +- Focuses on important issues +- Easier log management and monitoring + +--- + +## Summary + +AgentKit logging system design principles: + +- 🔒 **Security first** - no logs by default to avoid information leaks +- 🎯 **Enable on demand** - turn on via environment variables when needed +- 🔧 **Flexible configuration** - control console and file independently +- 📊 **Level-based control** - use different log levels for different scenarios +- 📁 **Automatic management** - split by date for easier lookup once enabled + +**Quick reference**: + +```bash +# 1. Enable file logging +export AGENTKIT_FILE_ENABLED=true + +# 2. Enable console debugging +export AGENTKIT_LOG_CONSOLE=true +export AGENTKIT_FILE_ENABLED=true +export AGENTKIT_LOG_LEVEL=DEBUG + +# 3. View log file (file logging must be enabled first) +cat .agentkit/logs/agentkit-$(date +%Y%m%d).log + +# 4. Use different levels for console and file +export AGENTKIT_LOG_CONSOLE=true +export AGENTKIT_FILE_ENABLED=true +export AGENTKIT_CONSOLE_LOG_LEVEL=ERROR +export AGENTKIT_FILE_LOG_LEVEL=DEBUG +``` + +If you run into issues, refer to the [Troubleshooting](#troubleshooting) section or contact technical support. diff --git a/docs/en/content/3.agentkit-sdk/1.overview.md b/docs/en/content/3.agentkit-sdk/1.overview.md new file mode 100644 index 0000000..f4e0251 --- /dev/null +++ b/docs/en/content/3.agentkit-sdk/1.overview.md @@ -0,0 +1,239 @@ +# AgentKit SDK Overview + +AgentKit SDK is a Python development toolkit for rapidly building Agent applications that comply with AgentKit Platform standards. The SDK provides a concise set of decorators and client interfaces, allowing developers to focus on implementing Agent business logic. + +## Core Architecture + +AgentKit SDK adopts a modular design, consisting of the following primary modules: + +### 1. Runtime Application Framework + +Provides multiple application patterns, encapsulating user code into HTTP services that comply with Platform standards: + +#### AgentkitSimpleApp +The most commonly used application framework, suitable for standard Agent applications. + +**Core Decorators**: +- `@app.entrypoint` - Defines the main entry function for the Agent +- `@app.ping` - Defines the health check function +- `@app.async_task` - Defines asynchronous tasks (planned) + +**Standard Routes**: +- `/invoke` - Agent invocation endpoint +- `/ping` - Health check +- `/health`, `/readiness`, `/liveness` - Kubernetes readiness probes + +#### AgentkitMCPApp +An application framework based on the MCP (Model Context Protocol) protocol, used to encapsulate tools as MCP services. + +**Core Decorators**: +- `@app.tool` - Registers a function as an MCP tool +- `@app.agent_as_a_tool` - Encapsulates an Agent as an MCP tool + +#### AgentkitA2aApp +An application framework based on the A2A (Agent-to-Agent) protocol, used to build Agents that can communicate with each other. + +**Core Decorators**: +- `@app.agent_executor` - Registers an Agent executor +- `@app.task_store` - Registers task storage (optional) + +### 2. Platform Service Clients + +Provides convenient client interfaces for accessing various services of the AgentKit Platform. + +#### AgentkitMemory +Memory service client for managing long-term and short-term memory of Agents. + +**Main Functions**: +- `create_memory_collection()` - Creates a memory collection +- `list_memory_collections()` - Lists memory collections +- `get_memory_collection()` - Gets memory collection details +- `update_memory_collection()` - Updates memory collection configuration +- `delete_memory_collection()` - Deletes a memory collection +- `get_memory_connection_info()` - Gets connection information + +**Design Philosophy**: Decoupling of control plane and data plane +- **Control Plane** (provided by SDK): Manages creation, configuration, and retrieval of connection information for memory collections +- **Data Plane** (implemented by ADK): Performs actual memory read/write operations through MemoryBase or Mem0 protocols + +#### AgentkitKnowledge +Knowledge base service client for managing vectorized knowledge bases of Agents. + +**Main Functions**: +- `list_knowledge_bases()` - Lists knowledge bases +- `add_knowledge_base()` - Adds a knowledge base +- `get_knowledge_connection_info()` - Gets knowledge base connection information +- `delete_knowledge_base()` - Deletes a knowledge base + +**Use Cases**: +- RAG (Retrieval-Augmented Generation) applications +- Document Q&A systems +- Knowledge graph integration + +#### AgentkitMCP +MCP Gateway client for managing and routing a large number of MCP tools. + +**Main Functions**: +- Registers and manages MCP services +- Tool aggregation and intelligent routing +- Reduces tool integration complexity + +#### AgentkitRuntime +Runtime management client for managing Agent runtime environments. + +**Main Functions**: +- Creates and manages Runtime instances +- Queries Runtime status +- Configures environment variables and resources + +### 3. Infrastructure Modules + +#### BaseAgentkitClient +Base class for all clients, providing unified configuration and HTTP request capabilities. + +**Configuration Items**: +- API endpoint configuration +- Authentication credential management +- Request retry and timeout +- Logging and monitoring + +#### Context Management +Uses `contextvars` to manage context information for each request, including: +- User identity +- Session ID +- Request metadata +- Tracing information + +## Module Dependencies + +``` +AgentKit SDK +│ +├── Runtime Apps (Application Framework Layer) +│ ├── AgentkitSimpleApp +│ ├── AgentkitMCPApp +│ ├── AgentkitA2aApp +│ └── AgentkitAgentServerApp +│ +├── Platform Clients (Service Client Layer) +│ ├── AgentkitMemory +│ ├── AgentkitKnowledge +│ ├── AgentkitMCP +│ └── AgentkitRuntime +│ +└── Infrastructure (Infrastructure Layer) + ├── BaseAgentkitClient + ├── Context + └── Telemetry (Observability) +``` + +## Key Features + +### 1. Decorator-Driven +Uses Python decorators to simplify application development; developers only need to focus on business logic: + +```python +from agentkit.apps import AgentkitSimpleApp + +app = AgentkitSimpleApp() + +@app.entrypoint +async def run(payload: dict, headers: dict) -> str: + # Business logic + return response +``` + +### 2. Framework-Agnostic +The SDK does not restrict the use of specific Agent frameworks; it supports: +- Volcengine ADK (veadk) +- Google ADK (gadk) +- LangChain +- Custom frameworks + +### 3. Automated Observability +Built-in OpenTelemetry support, automatically collects: +- Traces +- Metrics +- Logging + +### 4. Production-Ready +Provides complete production environment support: +- Health check endpoints +- Graceful shutdown +- Error handling +- Request retry + +### 5. Type Safety +Full Python type annotations provide: +- IDE autocomplete +- Type checking +- Better code maintainability + +## Quick Start + +### Installation + +```bash +pip install agentkit-sdk-python +``` + +### Create a Simple Agent + +```python +from agentkit.apps import AgentkitSimpleApp +from veadk import Agent, Runner +from veadk.tools.demo_tools import get_city_weather + +app = AgentkitSimpleApp() +agent = Agent(tools=[get_city_weather]) +runner = Runner(agent=agent) + +@app.entrypoint +async def run(payload: dict, headers: dict) -> str: + prompt = payload["prompt"] + user_id = headers["user_id"] + session_id = headers["session_id"] + + response = await runner.run( + messages=prompt, + user_id=user_id, + session_id=session_id + ) + return response + +@app.ping +def ping() -> str: + return "pong!" + +if __name__ == "__main__": + app.run(host="0.0.0.0", port=8000) +``` + +### Use Platform Services + +```python +from agentkit.sdk.memory import AgentkitMemory +from agentkit.base_client import ApiConfig + +# Initialize client +config = ApiConfig( + access_key="your_ak", + secret_key="your_sk" +) +memory_client = AgentkitMemory(config) + +# Create memory collection +response = memory_client.create_memory_collection( + name="my-memory", + short_term_configuration={...}, + long_term_configuration={...} +) +print(f"Memory ID: {response.id}") +``` + +## Next Steps + +- Check the [Annotation Usage Guide](./2.annotation.md) for detailed usage of various decorators +- Refer to complete examples in the `samples/` directory +- Read the API documentation for Platform service clients + diff --git a/docs/en/content/3.agentkit-sdk/2.annotation.md b/docs/en/content/3.agentkit-sdk/2.annotation.md new file mode 100644 index 0000000..d8f0f06 --- /dev/null +++ b/docs/en/content/3.agentkit-sdk/2.annotation.md @@ -0,0 +1,632 @@ +# Annotation Usage Guide + +AgentKit SDK provides a concise set of decorators (annotations) for rapidly building different types of Agent applications. This document details the usage and best practices for various annotations. + +## Simple Agent Annotations + +`AgentkitSimpleApp` is the most commonly used application framework, providing standard HTTP service endpoints. + +### @app.entrypoint + +Defines the main entry function for the Agent, handling invocation requests from the Platform. + +#### Function Signature + +```python +@app.entrypoint +async def run(payload: dict, headers: dict) -> str: + pass +``` + +#### Parameter Description + +- **payload** (dict): Request body, containing user input and configuration + - `prompt` (str): User input prompt + - Other custom fields + +- **headers** (dict): Request headers, containing context information + - `user_id` (str): User ID + - `session_id` (str): Session ID + - `request_id` (str): Request trace ID + - Other custom headers + +- **Return Value** (str): Agent's response result + +#### Complete Example + +```python +from agentkit.apps import AgentkitSimpleApp +from veadk import Agent, Runner +from veadk.tools.demo_tools import get_city_weather + +app = AgentkitSimpleApp() +agent = Agent(tools=[get_city_weather]) +runner = Runner(agent=agent) + +@app.entrypoint +async def run(payload: dict, headers: dict) -> str: + """Agent main entry function""" + # 1. Extract input parameters + prompt = payload.get("prompt", "") + user_id = headers.get("user_id", "anonymous") + session_id = headers.get("session_id", "default") + + # 2. Invoke Agent execution + response = await runner.run( + messages=prompt, + user_id=user_id, + session_id=session_id + ) + + # 3. Return result + return response +``` + +#### Notes + +1. **Must be async function**: Use `async def` to define +2. **Fixed parameter order**: First parameter is payload, second is headers +3. **Return string**: Return value is automatically encapsulated as JSON response +4. **Error handling**: Recommended to handle exceptions within the function + +#### Error Handling Example + +```python +import logging + +logger = logging.getLogger(__name__) + +@app.entrypoint +async def run(payload: dict, headers: dict) -> str: + try: + prompt = payload["prompt"] + response = await runner.run(messages=prompt) + return response + except KeyError as e: + logger.error(f"Missing required field: {e}") + return f"Error: Missing required field {e}" + except Exception as e: + logger.error(f"Agent execution failed: {e}") + return f"Error: {str(e)}" +``` + +### @app.ping + +Defines the health check function, used for Platform and Kubernetes health probes. + +#### Function Signature + +```python +@app.ping +def ping() -> str: + pass +``` + +#### Parameter Description + +- **No parameters**: Health check function does not accept any parameters +- **Return Value** (str): Health status information, usually returns "pong" or "ok" + +#### Basic Example + +```python +@app.ping +def ping() -> str: + """Health check""" + return "pong!" +``` + +#### Advanced Example: Including Dependency Checks + +```python +import redis +from sqlalchemy import create_engine + +# Initialize dependencies +redis_client = redis.Redis(host='localhost', port=6379) +db_engine = create_engine('postgresql://...') + +@app.ping +def ping() -> str: + """Health check, including dependency service detection""" + try: + # Check Redis connection + redis_client.ping() + + # Check database connection + with db_engine.connect() as conn: + conn.execute("SELECT 1") + + return "ok - all services healthy" + except Exception as e: + logger.error(f"Health check failed: {e}") + return f"degraded - {str(e)}" +``` + +#### Notes + +1. **No parameters**: Function signature must be `def ping() -> str:` +2. **Synchronous function**: Use `def` rather than `async def` +3. **Quick response**: Should return within 1 second to avoid timeout +4. **Lightweight check**: Avoid performing time-consuming operations + +#### Available Endpoints + +Health check functions are automatically registered to the following endpoints: +- `GET /ping` - Basic health check +- `GET /health` - Health status +- `GET /readiness` - Kubernetes readiness probe +- `GET /liveness` - Kubernetes liveness probe + +### @app.async_task (Planned) + +Used to define asynchronous tasks, supporting long-running operations. + +```python +@app.async_task +async def process_long_task(task_id: str, data: dict) -> dict: + """Process long-running tasks""" + # Long-running logic + result = await heavy_computation(data) + return result +``` + +> **Note**: This feature is planned and not yet implemented. + +## MCP Agent Annotations + +`AgentkitMCPApp` is used to build MCP (Model Context Protocol) services, encapsulating functions as standard MCP tools. + +### @app.tool + +Registers a function as an MCP tool for LLM invocation. + +#### Function Signature + +```python +@app.tool +def tool_name(param1: str, param2: int) -> dict: + pass +``` + +#### Parameter Description + +- **Function parameters**: Tool input parameters, must have type annotations +- **Return Value**: Tool execution result, recommended to return dict type +- **Docstring**: Used as tool description for LLM to understand tool purpose + +#### Basic Example + +```python +from agentkit.apps import AgentkitMCPApp + +mcp_app = AgentkitMCPApp() + +@mcp_app.tool +def get_city_weather(city: str) -> dict[str, str]: + """Get city weather information + + Args: + city: City name (must be in English) + + Returns: + Dictionary containing weather conditions and temperature + """ + weather_data = { + "beijing": {"condition": "Sunny", "temperature": 25}, + "shanghai": {"condition": "Cloudy", "temperature": 22}, + } + + city = city.lower().strip() + if city in weather_data: + info = weather_data[city] + return {"result": f"{info['condition']}, {info['temperature']}°C"} + else: + return {"result": f"Weather information not found for {city}"} +``` + +#### Async Tool Example + +```python +import aiohttp + +@mcp_app.tool +async def fetch_web_content(url: str) -> dict: + """Fetch web page content + + Args: + url: Web page URL + + Returns: + Dictionary containing web page content + """ + async with aiohttp.ClientSession() as session: + async with session.get(url) as response: + content = await response.text() + return { + "status": response.status, + "content": content[:1000] # Extract first 1000 characters + } +``` + +#### Notes + +1. **Type annotations required**: All parameters must have type annotations; MCP needs this information to generate tool schema +2. **Detailed docstrings**: Docstrings serve as tool descriptions to help LLM understand tool purpose +3. **Sync and async both supported**: Supports `def` and `async def` +4. **Return structured data**: Recommended to return dict type for easy LLM parsing +5. **Error handling**: Handle exceptions within the function to avoid tool call failures + +#### Complex Parameter Example + +```python +from typing import List, Optional +from pydantic import BaseModel + +class SearchQuery(BaseModel): + keywords: List[str] + max_results: int = 10 + filters: Optional[dict] = None + +@mcp_app.tool +def search_documents(query: SearchQuery) -> dict: + """Search documents + + Args: + query: Search query object, containing keywords, result count, and filter conditions + + Returns: + Search results list + """ + # Implement search logic + results = perform_search( + keywords=query.keywords, + max_results=query.max_results, + filters=query.filters + ) + return {"results": results, "count": len(results)} +``` + +### @app.agent_as_a_tool + +Encapsulates the entire Agent as an MCP tool, enabling Agent composition and collaboration. + +#### Function Signature + +```python +@app.agent_as_a_tool +async def agent_tool(prompt: str) -> str: + pass +``` + +#### Usage Example + +```python +from veadk import Agent, Runner +from veadk.tools.demo_tools import get_city_weather + +# Create a dedicated weather Agent +weather_agent = Agent(tools=[get_city_weather]) +weather_runner = Runner(agent=weather_agent) + +mcp_app = AgentkitMCPApp() + +@mcp_app.agent_as_a_tool +async def weather_assistant(prompt: str) -> str: + """Weather assistant Agent + + An Agent specifically designed to handle weather-related queries, capable of querying weather information for cities worldwide. + + Args: + prompt: User's weather query + + Returns: + Weather query result + """ + response = await weather_runner.run(messages=prompt) + return response +``` + +#### Multi-Agent Collaboration Example + +```python +# Create multiple dedicated Agents +weather_agent = Agent(tools=[get_city_weather]) +news_agent = Agent(tools=[get_latest_news]) +calendar_agent = Agent(tools=[check_schedule]) + +@mcp_app.agent_as_a_tool +async def weather_assistant(query: str) -> str: + """Weather assistant""" + return await Runner(agent=weather_agent).run(messages=query) + +@mcp_app.agent_as_a_tool +async def news_assistant(query: str) -> str: + """News assistant""" + return await Runner(agent=news_agent).run(messages=query) + +@mcp_app.agent_as_a_tool +async def calendar_assistant(query: str) -> str: + """Calendar assistant""" + return await Runner(agent=calendar_agent).run(messages=query) +``` + +#### Notes + +1. **Single Agent responsibility**: Each Agent should focus on a specific domain +2. **Clear descriptions**: Docstrings should clearly define the Agent's capability boundaries +3. **Async execution**: Usually an async function +4. **Reasonable timeout**: Set a reasonable execution timeout + +## A2A Agent Annotations + +`AgentkitA2aApp` is used to build A2A (Agent-to-Agent) applications, supporting communication and collaboration between Agents. + +### @app.agent_executor + +Registers an Agent executor, defining the Agent's execution logic. + +#### Function Signature + +```python +@app.agent_executor(runner=runner, **kwargs) +class MyAgentExecutor(A2aAgentExecutor): + pass +``` + +#### Parameter Description + +- **runner**: Agent runner instance +- **kwargs**: Other configuration parameters + +#### Basic Example + +```python +from agentkit.apps import AgentkitA2aApp +from google.adk.a2a.executor.a2a_agent_executor import A2aAgentExecutor +from veadk import Agent, Runner +from veadk.a2a.agent_card import get_agent_card +from veadk.tools.demo_tools import get_city_weather + +# Create A2A application +a2a_app = AgentkitA2aApp() + +# Create Agent +agent = Agent(tools=[get_city_weather]) +runner = Runner(agent=agent) + +# Register executor +@a2a_app.agent_executor(runner=runner) +class WeatherAgentExecutor(A2aAgentExecutor): + """Weather query Agent executor""" + pass + +# Run application +if __name__ == "__main__": + a2a_app.run( + agent_card=get_agent_card(agent=agent, url="http://127.0.0.1:8000"), + host="127.0.0.1", + port=8000, + ) +``` + +#### Custom Executor Example + +```python +from a2a.server.agent_execution import AgentExecutor +from a2a.server.agent_execution.context import RequestContext +from a2a.server.events.event_queue import EventQueue + +@a2a_app.agent_executor(runner=runner) +class CustomAgentExecutor(AgentExecutor): + """Custom Agent executor""" + + async def execute( + self, + context: RequestContext, + event_queue: EventQueue + ) -> str: + """Execute Agent logic + + Args: + context: Request context, containing input messages and history + event_queue: Event queue, used for sending intermediate results + + Returns: + Agent's response result + """ + # Extract input from context + user_message = context.current_input + + # Send intermediate events (optional) + await event_queue.put({ + "type": "thinking", + "content": "Thinking..." + }) + + # Execute Agent + response = await self.runner.run(messages=user_message) + + return response +``` + +#### Notes + +1. **Inherit AgentExecutor**: Must inherit from `AgentExecutor` or its subclasses +2. **Provide runner**: Must pass runner instance through parameters +3. **Implement execute method**: To customize logic, override the `execute` method +4. **Use event_queue**: Send intermediate states through the event queue + +### @app.task_store + +Registers task storage for persisting A2A task states. + +#### Function Signature + +```python +@app.task_store(**kwargs) +class MyTaskStore(TaskStore): + pass +``` + +#### Using Default Storage + +```python +# Without specifying task_store, in-memory storage (InMemoryTaskStore) will be used +a2a_app = AgentkitA2aApp() + +@a2a_app.agent_executor(runner=runner) +class MyExecutor(A2aAgentExecutor): + pass +``` + +#### Custom Task Storage Example + +```python +from a2a.server.tasks.task_store import TaskStore +from a2a.types import Task +import redis + +@a2a_app.task_store(redis_url="redis://localhost:6379") +class RedisTaskStore(TaskStore): + """Redis-based task storage""" + + def __init__(self, redis_url: str): + self.redis_client = redis.from_url(redis_url) + + async def save_task(self, task: Task) -> None: + """Save task""" + task_data = task.model_dump_json() + self.redis_client.set(f"task:{task.id}", task_data) + + async def get_task(self, task_id: str) -> Task | None: + """Get task""" + task_data = self.redis_client.get(f"task:{task_id}") + if task_data: + return Task.model_validate_json(task_data) + return None + + async def delete_task(self, task_id: str) -> None: + """Delete task""" + self.redis_client.delete(f"task:{task_id}") +``` + +#### Notes + +1. **Optional decorator**: If not specified, in-memory storage is used +2. **Inherit TaskStore**: Must inherit from `TaskStore` +3. **Implement required methods**: Implement `save_task`, `get_task`, `delete_task`, and other methods +4. **Persistent storage**: For production environments, persistent storage (Redis, database, etc.) is recommended + +## Best Practices + +### 1. Error Handling + +All decorated functions should have good error handling: + +```python +import logging + +logger = logging.getLogger(__name__) + +@app.entrypoint +async def run(payload: dict, headers: dict) -> str: + try: + # Business logic + result = await process(payload) + return result + except ValueError as e: + logger.warning(f"Invalid input: {e}") + return f"Invalid input: {str(e)}" + except Exception as e: + logger.error(f"Unexpected error: {e}", exc_info=True) + return "An error occurred. Please try again later." +``` + +### 2. Logging + +Add appropriate logs for problem tracking: + +```python +@app.entrypoint +async def run(payload: dict, headers: dict) -> str: + request_id = headers.get("request_id", "unknown") + logger.info(f"[{request_id}] Processing request: {payload}") + + try: + response = await runner.run(messages=payload["prompt"]) + logger.info(f"[{request_id}] Request completed successfully") + return response + except Exception as e: + logger.error(f"[{request_id}] Request failed: {e}") + raise +``` + +### 3. Type Annotations + +Use complete type annotations to improve code quality: + +```python +from typing import Dict, Any + +@app.entrypoint +async def run(payload: Dict[str, Any], headers: Dict[str, str]) -> str: + prompt: str = payload["prompt"] + user_id: str = headers.get("user_id", "anonymous") + # ... +``` + +### 4. Docstrings + +Add detailed docstrings for all functions: + +```python +@mcp_app.tool +def calculate_distance(lat1: float, lon1: float, lat2: float, lon2: float) -> dict: + """Calculate the distance between two geographic coordinates + + Uses the Haversine formula to calculate the great-circle distance between two points on the Earth's surface. + + Args: + lat1: Starting latitude (degrees) + lon1: Starting longitude (degrees) + lat2: Ending latitude (degrees) + lon2: Ending longitude (degrees) + + Returns: + Dictionary containing distance information, distance unit is kilometers + + Example: + >>> calculate_distance(39.9, 116.4, 31.2, 121.5) + {"distance_km": 1067.5} + """ + # Implementation logic +``` + +### 5. Performance Optimization + +Avoid performing time-consuming initialization in decorated functions: + +```python +# ❌ Bad practice +@app.entrypoint +async def run(payload: dict, headers: dict) -> str: + agent = Agent(tools=[...]) # Created on every request + runner = Runner(agent=agent) + return await runner.run(messages=payload["prompt"]) + +# ✅ Good practice +agent = Agent(tools=[...]) # Created only once +runner = Runner(agent=agent) + +@app.entrypoint +async def run(payload: dict, headers: dict) -> str: + return await runner.run(messages=payload["prompt"]) +``` + +## Next Steps + +- Check the complete example code in the `samples/` directory +- Read the [SDK Overview](./1.overview.md) to understand the overall architecture +- Deploy the application to AgentKit Platform + diff --git a/docs/en/content/4.runtime/1.runtime_quickstart.md b/docs/en/content/4.runtime/1.runtime_quickstart.md new file mode 100644 index 0000000..faf08de --- /dev/null +++ b/docs/en/content/4.runtime/1.runtime_quickstart.md @@ -0,0 +1,289 @@ +# AgentKit Runtime: From Local Development to Cloud Deployment + +**AgentKit Runtime** is a unified, managed **Agent** execution environment designed to provide you with a secure, efficient, and scalable serverless platform, allowing you to focus on **Agent** business logic rather than tedious infrastructure operations. + +## What Does AgentKit Runtime Solve for You? + +- **Heavy Operational Burden**: Have you ever spent significant time on environment setup, network configuration, dependency installation, manual scaling, and troubleshooting? +- **Lack of Unified Management Platform**: Does creating and managing separate environments for different **Agents** or sessions make scheduling chaotic and maintenance difficult? +- **Security and Isolation Challenges**: Are you concerned about permission conflicts, data leakage, or malicious access risks in multi-user or multi-**Agent** scenarios? +- **Missing Monitoring and Logs**: Do you need to spend extra resources configuring logging systems, metrics collection, and alerting rules to monitor **Agent** health in real-time? + +**AgentKit Runtime** systematically addresses all these problems by providing a serverless managed environment. + + +## Core Advantages + +### 1. Serverless Architecture: Simplified Operations, Optimized Costs + +- **Zero Infrastructure Management**: No need to worry about underlying servers and complex environment configurations, achieving true "code as a service." +- **Unified Runtime Platform**: Efficiently run and schedule multiple **Agent** instances (Sessions) in the same environment, with unified access points. +- **Automated Lifecycle Management**: Automatically scale from zero to large-scale concurrency based on real-time traffic, enabling unattended elastic scaling. +- **Pay-as-You-Go**: Only incur costs when **Agents** are running; resources automatically scale to zero when there's no traffic, maximizing cloud cost savings. +- **Built-in Monitoring and Logs**: Out-of-the-box real-time monitoring and logging systems make it easy to track **Agent** status and quickly locate issues. + +### 2. Enterprise-Grade Security Isolation + +- **Multiple Isolation Safeguards**: Based on mature cloud vendor virtualization and container technologies, ensuring each **Agent Runtime** runs in an independent, protected environment. +- **Fine-Grained Access Control**: Deep integration with **Identity** and gateway authentication, strictly isolating session context and access permissions, effectively preventing data cross-contamination and unauthorized access risks. + +### 3. Framework-Agnostic Quick Integration + +- **Broad Framework Support**: Deeply integrated with **veADK** while compatible with mainstream Python Agent frameworks, requiring minimal adaptation for quick onboarding. +- **Multi-Protocol Support**: Native support for HTTP, MCP, A2A, and other communication protocols to meet diverse application scenario needs. +- **One-Click Deployment**: Through **AgentKit SDK**, you can easily achieve one-click deployment from your local IDE to the cloud **Runtime**. + +--- + +## Three-Step Guide: From Local Development to Cloud Deployment + +This guide will walk you through the complete process from environment configuration and local development debugging to ultimately deploying your **Agent** to a production environment. + +### Prerequisites + +Before starting, please ensure you have: + +1. A Volcengine account with **AgentKit** service activated, and obtain your **AccessKey & SecretKey**. + > **Note**: Please ensure your AccessKey has `AgentKitFullAccess` permissions. +2. **Python 3.10+** installed locally. + +### Step 1: Environment Configuration + +> We recommend using `uv` or `python3 -m venv` to manage your Python virtual environment. The following examples will use `uv`. +> +> For `uv` installation instructions, please refer to: [uv installation](https://docs.astral.sh/uv/getting-started/installation/) + +**1. Create and Activate Virtual Environment** + +```bash +mkdir agentkit-runtime-quickstart +cd agentkit-runtime-quickstart +uv venv --python 3.12.0 +source .venv/bin/activate +``` + +**2. Install Core Dependencies** + +> You can specify a mirror source via the `--index` parameter to speed up installation. + +```bash +uv add veadk-python +uv add agentkit-sdk-python +``` + +### Step 2: Create and Debug Agent Locally + +#### 1. Initialize Agent Project + +We strongly recommend using `agentkit-cli` to quickly bootstrap your project. The `init` command creates a well-structured **Agent** project with streaming support from a template. + +```bash +# Use agentkit-cli to create project from template +agentkit init +``` + +This automatically generates a project structure containing `simple_agent.py` and `requirements.txt`, allowing you to start development immediately. + +#### 2. Agent Code Overview + +The core code of `simple_agent.py` generated using the `basic_stream` template is shown below. It demonstrates how to wrap a **veADK** **Agent** with **AgentkitSimpleApp**, execute it through **Runner**, and return results as SSE (Server-Sent Events) streams. + +```python +# Copyright (c) 2025 Beijing Volcano Engine Technology Co., Ltd. and/or its affiliates. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import json +import logging + +from google.adk.agents import RunConfig +from google.adk.agents.run_config import StreamingMode +from google.genai.types import Content, Part +from veadk import Agent, Runner + +from agentkit.apps import AgentkitSimpleApp +from veadk.prompts.agent_default_prompt import DEFAULT_DESCRIPTION, DEFAULT_INSTRUCTION + +logger = logging.getLogger(__name__) +logger.setLevel(logging.INFO) + +app = AgentkitSimpleApp() + +app_name = "simple_streamable_app" + +agent_name = "Agent" +description = DEFAULT_DESCRIPTION +system_prompt = DEFAULT_INSTRUCTION + + +tools = [] + +# from veadk.tools.builtin_tools.web_search import web_search +# tools.append(web_search) + + +agent = Agent( + name=agent_name, + description=description, + instruction=system_prompt, + tools=tools, +) +agent.model._additional_args["stream_options"] = {"include_usage": True} +runner = Runner(agent=agent, app_name=app_name) + + +@app.entrypoint +async def run(payload: dict, headers: dict): + prompt = payload["prompt"] + user_id = headers["user_id"] + session_id = headers["session_id"] + + logger.info( + f"Running agent with prompt: {prompt}, user_id: {user_id}, session_id: {session_id}" + ) + + session_service = runner.short_term_memory.session_service # type: ignore + + # prevent session recreation + session = await session_service.get_session( + app_name=app_name, user_id=user_id, session_id=session_id + ) + if not session: + await session_service.create_session( + app_name=app_name, user_id=user_id, session_id=session_id + ) + + new_message = Content(role="user", parts=[Part(text=prompt)]) + try: + async for event in runner.run_async( + user_id=user_id, + session_id=session_id, + new_message=new_message, + run_config=RunConfig(streaming_mode=StreamingMode.SSE), + ): + # Format as SSE data + sse_event = event.model_dump_json(exclude_none=True, by_alias=True) + logger.debug("Generated event in agent run streaming: %s", sse_event) + yield sse_event + except Exception as e: + logger.exception("Error in event_generator: %s", e) + # You might want to yield an error event here + error_data = json.dumps({"error": str(e)}) + yield error_data + + +@app.ping +def ping() -> str: + return "pong!" + + +if __name__ == "__main__": + app.run(host="0.0.0.0", port=8000) +``` + +**Code Highlights**: +- Uses Volcengine Ark Doubao model by default and automatically handles model API Key retrieval. +- Built-in session management logic ensures multi-turn conversation continuity. +- Achieves seamless integration with **AgentKit Runtime** through `AgentkitSimpleApp`. + +#### 3. Configure Environment Variables + +Before starting the **Agent** service, you need to configure Volcengine access credentials: + +```bash +# Required: Configure your Volcengine access credentials +export VOLCENGINE_ACCESS_KEY=your_ak +export VOLCENGINE_SECRET_KEY=your_sk +``` + +> **Important**: Please replace `your_ak` and `your_sk` with your actual credentials. + +#### 4. Start and Invoke Service Locally + +Once everything is ready, run the following command to start the **Agent** service: + +```bash +python simple_agent.py +``` + +The service will listen on `http://0.0.0.0:8000`. Now, open another terminal and test your **Agent** using `curl`: + +```bash +curl --location 'http://localhost:8000/invoke' \ + --header 'Content-Type: application/json' \ + --header 'user_id: test' \ + --header 'session_id: local_session' \ + --data '{"prompt": "Tell me a joke!"}' +``` + +**Parameter Reference:** + +- `user_id`: User identifier +- `session_id`: Session identifier +- `prompt`: User's natural language request + +**Sample Execution Log:** + +After successful invocation, the console will output detailed execution logs: +``` +INFO: Started server process [38120] +INFO: Waiting for application startup. +INFO: Application startup complete. +INFO: Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit) +INFO: 127.0.0.1:60807 - "POST /invoke HTTP/1.1" 200 OK +INFO:__main__:Running agent with prompt: Tell me a joke!, user_id: test, session_id: local_session +2025-12-01 20:12:50 | DEBUG | runner.py:151 - Event output: Why +2025-12-01 20:12:50 | DEBUG | runner.py:151 - Event output: did +2025-12-01 20:12:50 | DEBUG | runner.py:151 - Event output: the +2025-12-01 20:12:50 | DEBUG | runner.py:151 - Event output: AI +2025-12-01 20:12:50 | DEBUG | runner.py:151 - Event output: apply +2025-12-01 20:12:50 | DEBUG | runner.py:151 - Event output: for +2025-12-01 20:12:50 | DEBUG | runner.py:151 - Event output: a +2025-12-01 20:12:50 | DEBUG | runner.py:151 - Event output: job +2025-12-01 20:12:50 | DEBUG | runner.py:151 - Event output: at +2025-12-01 20:12:50 | DEBUG | runner.py:151 - Event output: the +2025-12-01 20:12:51 | DEBUG | runner.py:151 - Event output: bakery +2025-12-01 20:12:51 | DEBUG | runner.py:151 - Event output: ? +2025-12-01 20:12:51 | DEBUG | runner.py:151 - Event output: Because +2025-12-01 20:12:51 | DEBUG | runner.py:151 - Event output: it +2025-12-01 20:12:51 | DEBUG | runner.py:151 - Event output: wanted +2025-12-01 20:12:51 | DEBUG | runner.py:151 - Event output: to +2025-12-01 20:12:51 | DEBUG | runner.py:151 - Event output: work +2025-12-01 20:12:51 | DEBUG | runner.py:151 - Event output: on +2025-12-01 20:12:51 | DEBUG | runner.py:151 - Event output: its +2025-12-01 20:12:51 | DEBUG | runner.py:151 - Event output: ** +2025-12-01 20:12:51 | DEBUG | runner.py:151 - Event output: d +2025-12-01 20:12:51 | DEBUG | runner.py:151 - Event output: ough +2025-12-01 20:12:51 | DEBUG | runner.py:151 - Event output: ** +2025-12-01 20:12:51 | DEBUG | runner.py:151 - Event output: processing +2025-12-01 20:12:51 | DEBUG | runner.py:151 - Event output: skills +2025-12-01 20:12:51 | DEBUG | runner.py:151 - Event output: ! +2025-12-01 20:12:51 | DEBUG | runner.py:151 - Event output: 😄 +2025-12-01 20:12:51 | DEBUG | runner.py:151 - Event output: Why did the AI apply for a job at the bakery? + +Because it wanted to work on its **dough** processing skills! 😄 +``` + +### Step 3: Deploy to Production Environment + +After completing local development and testing, you can deploy your agent to the AgentKit platform: + +1. **Package Code**: Ensure all dependencies are correctly configured in `requirements.txt`. The code generated using the template already includes all necessary dependencies. +2. **Platform Deployment**: Following the [Quick Start](../1.introduction/3.quickstart.md) guide, use the `agentkit config` and `agentkit launch` commands to configure and deploy your application. +3. **Invoke Application**: After deployment, you can invoke your agent through the platform's API or SDK. Example invocation: + ```bash + agentkit invoke "Tell me a joke!" + ``` + +You have now successfully completed the entire process from local development to cloud deployment! + diff --git a/docs/en/content/5.tools/1.sandbox_quickstart.md b/docs/en/content/5.tools/1.sandbox_quickstart.md new file mode 100644 index 0000000..9149787 --- /dev/null +++ b/docs/en/content/5.tools/1.sandbox_quickstart.md @@ -0,0 +1,192 @@ +# AgentKit Built-in Tools Quick Start Guide + +Built-in Tools provide Agents with standardized sandbox runtime environments and tool interfaces. The all-in-one sandbox image integrates core capabilities including code execution, browser automation, and terminal operations, supporting standardized integration and API calls. + +## Core Capabilities + +- **Code Sandbox**: Enables Agents to safely "run code" +- **Browser Sandbox**: Enables Agents to "interact with web pages like humans" +- **Terminal Sandbox**: Enables Agents to "operate the operating system console (Terminal) like humans" +- **File System**: Enables Agents to upload and download files + +This document provides detailed instructions on how to integrate and use Built-in Tools in your Agent code, with a focus on the code execution sandbox functionality. By following this guide, you will learn how to create, configure, and invoke sandbox tools. + +## Prerequisites: Creating a Sandbox Tool + +Before writing code, you need to create a sandbox tool instance in the Volcengine console: + +1. Visit the [AgentKit Built-in Tools Console](https://console.volcengine.com/agentkit/region:agentkit+cn-beijing/builtintools) +2. Create a new sandbox tool instance +3. Record the generated `TOOL_ID` for use in subsequent configuration + +## Agent Code Example + +The following code demonstrates how to use [VeADK](https://github.com/volcengine/veadk-python) to build an Agent with code execution capabilities. By integrating the Built-in Tools `run_code` tool, your Agent will be able to execute code safely within a sandbox environment. + +We recommend using `agentkit-cli` to create a project from the Basic Agent template. After the template is created, you need to make the following modifications: +- Add the code execution tool `run_code` to your Agent +- Configure the environment variable `AGENTKIT_TOOL_ID` with your sandbox tool instance ID + +Your final code file should look like this: + +### Complete Code + +Save the code as `simple_agent_tool.py`: + +```python +from veadk import Agent, Runner +from veadk.tools.builtin_tools.run_code import run_code +from agentkit.apps import AgentkitSimpleApp + +app = AgentkitSimpleApp() +agent: Agent = Agent( + tools=[run_code], +) +runner = Runner(agent=agent) + +@app.entrypoint +async def run(payload: dict, headers: dict) -> str: + prompt = payload["prompt"] + user_id = headers["user_id"] + session_id = headers["session_id"] + + response = await runner.run( + messages=prompt, + user_id=user_id, + session_id=session_id + ) + return response + +@app.ping +def ping() -> str: + return "pong!" + +if __name__ == "__main__": + app.run(host="0.0.0.0", port=8000) +``` + +### Code Explanation + +- **`run_code` Tool**: Provides a secure code execution environment supporting multiple programming languages including Python and JavaScript +- **`session_id`**: Used to identify user sessions; requests with the same `session_id` will share the same sandbox instance +- **Asynchronous Processing**: Uses `async/await` syntax to support high-concurrency requests + +## Local Debugging + +### 1. Install VeADK from Official Source + +You can install [veadk-python](https://volcengine.github.io/veadk-python/introduction/installation) directly using the Python package manager pip from the PyPI platform: + +```bash +pip install veadk-python +``` + +> **Note**: The veadk-python version that supports calling built-in tools is 0.2.15 and above. + +### 2. Configure Environment Variables + +Before starting the Agent, you need to configure the following environment variables: + +```bash +# Required: Sandbox tool ID (obtained from the console) +export AGENTKIT_TOOL_ID=t-ye7fhfmghsc1kdxxxxxx + +# Required: Volcengine access credentials +export VOLCENGINE_ACCESS_KEY=your_ak +export VOLCENGINE_SECRET_KEY=your_sk +``` + +**📝 Important Notes:** + +- Replace placeholders like `your_ak`, `your_sk` with your actual configuration values +- `AGENTKIT_TOOL_ID` is obtained after creating the sandbox tool in the Volcengine console + +### 3. Start the Agent Service Locally + +After configuring the environment variables, run the following command to start the Agent: + +```bash +python simple_agent_tool.py +``` + +Once the service starts successfully, it will listen on `http://0.0.0.0:8000`, and you can invoke the Agent through this address. + +### 4. Invoke the Agent + +#### Tool Instance Invocation Mechanism + +Tool instances support intelligent session-based scheduling management: + +- **Automatic Creation**: When you first use a specific `session_id` to invoke, the system will automatically create the corresponding sandbox session instance +- **Session Reuse**: Multiple requests with the same `session_id` will share the same sandbox instance, maintaining continuity of code execution context +- **Lifecycle**: Each session instance has a default validity period of 30 minutes, after which it will be automatically destroyed +- **Isolation**: Requests with different `session_id` values use independent sandbox environments with no interference between them + +#### Invocation Example + +Use the following curl command to test the Agent's code execution capability: + +```bash +curl --location 'http://localhost:8000/invoke' \ + --header 'Content-Type: application/json' \ + --header 'user_id: veadk-test' \ + --header 'session_id: local_session' \ + --data '{"prompt": "Give me a random prime number between 50 and 100"}' +``` + +**Parameter Description:** + +- `user_id`: User identifier +- `session_id`: Session identifier, used to associate with the sandbox instance +- `prompt`: User's natural language request + +#### Execution Log Example + +After a successful invocation, the console will output detailed execution logs: + +``` +2025-11-23 21:10:24 | DEBUG | runner.py:578 - Function call: id='call_jwrcwdayjj8xnlgalyzzcoqq' args={'code': 'import random\n\ndef is_prime(n):\n if n <= 1:\n return False\n if n == 2:\n return True\n if n % 2 == 0:\n return False\n for i in range(3, int(n**0.5) + 1, 2):\n if n % i == 0:\n return False\n return True\n\nprimes_between = [p for p in range(50, 101) if is_prime(p)]\nrandom_prime = random.choice(primes_between)\nprint(random_prime)', 'language': 'python3'} name='run_code' +2025-11-23 21:10:24 | DEBUG | run_code.py:48 - tools endpoint: agentkit.cn-beijing.volces.com +2025-11-23 21:10:24 | DEBUG | run_code.py:54 - tool_user_session_id: veAgent_veadk-test_local_session +2025-11-23 21:10:24 | DEBUG | run_code.py:56 - Running code in language: python3, session_id=local_session, code=import random + +def is_prime(n): + if n <= 1: + return False + if n == 2: + return True + if n % 2 == 0: + return False + for i in range(3, int(n**0.5) + 1, 2): + if n % i == 0: + return False + return True + +primes_between = [p for p in range(50, 101) if is_prime(p)] +random_prime = random.choice(primes_between) +print(random_prime), tool_id=t-ye7yhff668o2eybtfvr0, host=agentkit.cn-beijing.volces.com, service=agentkit, region=cn-beijing +2025-11-23 21:10:24 | DEBUG | run_code.py:65 - Get AK/SK from tool context failed. +2025-11-23 21:10:24 | DEBUG | run_code.py:77 - Successfully get AK/SK from environment variables. +2025-11-23 21:10:25 | DEBUG | run_code.py:103 - Invoke run code response: {'ResponseMetadata': {'RequestId': '****', 'Action': 'InvokeTool', 'Version': '2025-10-30', 'Service': 'agentkit', 'Region': 'cn-beijing'}, 'Result': {'ToolId': 't-****', 'UserSessionId': '****', 'SessionId': 's-****', 'Endpoint': '', 'InternalEndpoint': '', 'Result': '{\n "success": true,\n "message": "Code executed successfully",\n "data": {\n "kernel_name": "python3",\n "session_id": "****",\n "status": "ok",\n "execution_count": 1,\n "outputs": [\n {\n "output_type": "stream",\n "name": "stdout",\n "text": "67\\n",\n "data": null,\n "metadata": {},\n "execution_count": null,\n "ename": null,\n "evalue": null,\n "traceback": null\n }\n ],\n "code": "import random\\n\\ndef is_prime(n):\\n if n \\u003c= 1:\\n return False\\n if n == 2:\\n return True\\n if n % 2 == 0:\\n return False\\n for i in range(3, int(n**0.5) + 1, 2):\\n if n % i == 0:\\n return False\\n return True\\n\\nprimes_between = [p for p in range(50, 101) if is_prime(p)]\\nrandom_prime = random.choice(primes_between)\\nprint(random_prime)",\n "msg_id": "****"\n }\n}'}} +2025-11-23 21:10:38 | DEBUG | runner.py:586 - Event output: The random prime number between 50 and 100 is: 67 +2025-11-23 21:10:38 | WARNING | runner.py:652 - No tracer is configured in the agent, no trace id provided. +INFO: 127.0.0.1:52785 - "POST /invoke HTTP/1.1" 200 OK +``` + +## Deploying to Production + +After completing local development and testing, you can deploy your Agent to the AgentKit platform: + +1. **Package Code**: Ensure all dependencies are properly configured in `requirements.txt` +2. **Platform Deployment**: Refer to the [Quick Start](../1.introduction/3.quickstart.md) section in Runtime to deploy the tool. The main steps are: + - Run the `agentkit init` command in the project root directory to initialize the project, which will generate the `agentkit.yaml` file (skip this step if already executed) + - Ensure the `agentkit.yaml` file is configured with the application entry point set to your working application code `simple_agent_tool.py`: + ```yaml + entry_point: simple_agent_tool.py + ``` + - Ensure all dependencies are properly configured in `requirements.txt` + - Follow the [Quick Start](/en/content/1.introduction/3.quickstart) guide and use the `agentkit config` and `agentkit launch` commands to configure and deploy the application +3. **Invoke Application**: After deployment, you can invoke the Agent through the API or SDK provided by the platform. Example invocation: + ```bash + agentkit invoke "Give me a random prime number between 50 and 100" + ``` diff --git a/docs/en/content/6.memory/1.memory_quickstart.md b/docs/en/content/6.memory/1.memory_quickstart.md new file mode 100644 index 0000000..de2e46f --- /dev/null +++ b/docs/en/content/6.memory/1.memory_quickstart.md @@ -0,0 +1,168 @@ +# AgentKit Memory Quick Start Guide + +AI Agents face increasingly complex multi-turn tasks and context window limitations during operation. They require memory capabilities for context retention and personalization. AgentKit Memory provides a unified memory store interface and integrates with mainstream frameworks, offering cross-session, context-aware, and personalized interactions for Agents, enabling continuous learning and evolution. This chapter guides you through installing dependencies and implementing long-term memory functionality. + +# Usage Examples + +The following example demonstrates how to use AgentKit Memory to implement long-term memory functionality. + +Steps: +- Create a memory resource with semantic policies +- Write events (conversation history) to the memory resource +- Retrieve memory records from long-term memory + +## Creating a Memory Store + +Create a memory store for your agent through the Volcano Engine Console: [Agentkit-Memory](https://console.volcengine.com/agentkit/region:agentkit+cn-beijing/memory) + +### Obtaining Memory Resource Connection Information + +On the Memory Details - Integration Code page, obtain the connection information. + +- For Mem0-type memory resources, you will see environment variables similar to: + +``` +DATABASE_MEM0_BASE_URL="https://mem0-your-mem-url.mem0.volces.com:8000" +DATABASE_MEM0_API_KEY="xxxxxx-xxxxxxx" +``` + +- For VikingDB-type memory resources, you will see environment variables similar to: + +``` +DATABASE_VIKINGMEM_COLLECTION= #index +DATABASE_VIKINGMEM_MEMORY_TYPE=memory_summary_04uyfx # memory type, separate multiple by comma, e.g. event_v1,event_v2 +``` + +## Building an Agent with Long-Term Memory + +[VeADK](https://github.com/volcengine/veadk-python) is an open-source agent development framework that provides development, execution, and debugging capabilities for agents, maintained by the Volcano Engine team. +The following example demonstrates how to use VeADK to build an agent with long-term memory capabilities, using mem0 as the memory store backend. The agent can store user preferences, conversation summaries, and other personalized interaction information using long-term memory based on user input. + +You don't need to build a VeADK project from scratch. We recommend using agentkit-cli to create a project from the Basic Agent App template (the template uses the VeADK framework). After the template is created, you need to make the following modifications: + +- Add `LongTermMemory` to the Agent +- Configure the environment variables obtained in the previous section to `agentkit.yaml` +- Add `mem0ai==0.1.118` to `requirements.txt` +- Explicitly call `runner.save_session_to_long_term_memory` after each round of conversation to save the dialogue results to long-term memory + +Finally, your code file should look like this: + +```python +''' +**simple agent demo app** + +Before running, the user must set the following environment variables; otherwise, runtime exceptions will inevitably occur: +- MODEL_AGENT_NAME # model id in Volcano Engine Ark platform +- MODEL_AGENT_API_KEY # model api key in Volcano Engine Ark platform + +MODEL_AGENT_NAME and MODEL_AGENT_API_KEY are used to access the model service of the Volcano Engine Ark platform. +''' +import logging +import os + +from veadk import Agent, Runner +from veadk.memory.long_term_memory import LongTermMemory + + +from agentkit.apps import AgentkitSimpleApp + +logger = logging.getLogger(__name__) + +index = "simple_app" # required for viking backend, arbitrary for mem0 backend + +backend = "mem0" # one of "mem0", "viking_mem" +if backend == "viking_mem": + collection_name = os.getenv("DATABASE_VIKINGMEM_COLLECTION") + if not collection_name: + raise ValueError("DATABASE_VIKINGMEM_COLLECTION environment variable is not set") + index = collection_name + +app = AgentkitSimpleApp() +long_term_memory = LongTermMemory( + backend=backend, + index=index +) + +agent = Agent( + name="simple_app_agent", + instruction="You are a helpful assistant.", + long_term_memory=long_term_memory +) +runner = Runner(agent=agent) + + +@app.entrypoint +async def run(payload: dict, headers: dict) -> str: + prompt = payload["prompt"] + user_id = headers["user_id"] + session_id = headers["session_id"] + + logger.info( + f"Running agent with prompt: {prompt}, user_id: {user_id}, session_id: {session_id}" + ) + response = await runner.run(messages=prompt, user_id=user_id, session_id=session_id) + + logger.info(f"Run response: {response}") + + # save the teaching prompt and answer in long term memory + await runner.save_session_to_long_term_memory(session_id=session_id, user_id=user_id) + + return response + + +@app.ping +def ping() -> str: + return "pong!" + + +if __name__ == "__main__": + app.run(host="0.0.0.0", port=8000) + +``` + +## Environment Configuration + +Please add the following configuration to your `agentkit.yaml` file: + +``` +# When the long-term memory backend is mem0, add the following configuration +launch_types: + cloud: + runtime_envs: + DATABASE_MEM0_BASE_URL: + DATABASE_MEM0_API_KEY: + +# When the long-term memory backend is VikingDB, add the following configuration +launch_types: + cloud: + runtime_envs: + DATABASE_VIKINGMEM_COLLECTION: + DATABASE_VIKINGMEM_MEMORY_TYPE: +``` + +## Starting the Service + +Run `agentkit launch`. The Runtime connection information will be automatically saved to the `agentkit.yaml` file. + +## How to Invoke + +Execute the following command to invoke: + +``` +agentkit invoke "My secret is 0xabcd" +``` + +This will automatically use `user_id="agentkit_user"`, `session_id="agentkit_sample_session"` to invoke the agent. + +## Verifying Memory Store Functionality + +In the first invocation, you saved the password. We need to change the `session_id` to verify whether the Agent can correctly read information from the memory store. We recommend waiting approximately 1 minute for the long-term memory extraction to complete before invoking again. + +``` +agentkit invoke \ + --payload '{"prompt": "What is my secret?"}' \ + --headers '{"user_id": "agentkit_user", "session_id": "s123"}' +``` + +You will see that the Agent successfully reads information from the memory store and tells you the password is `0xabcd`. + diff --git a/docs/en/content/7.knowledge/1.knowledge_quickstart.md b/docs/en/content/7.knowledge/1.knowledge_quickstart.md new file mode 100644 index 0000000..21005a1 --- /dev/null +++ b/docs/en/content/7.knowledge/1.knowledge_quickstart.md @@ -0,0 +1,175 @@ +# AgentKit Knowledge Quickstart Guide + +AgentKit Knowledge provides one-click configuration and import capabilities for mainstream knowledge bases, enabling easy association with knowledge bases on the AgentKit platform. It offers unified knowledge base interfaces and framework integration, enhancing the convenience of using different knowledge bases for Agents. + +# Usage Example + +The steps are as follows: + +- Create a knowledge base resource +- Add template files to the knowledge base +- Retrieve records from the knowledge base + +## Creating a Knowledge Base + +Through the Volcano Engine Console, create a knowledge base for your agent using [VikingDB-Knowledge](https://console.volcengine.com/vikingdb/knowledge), and add the following content as `qa.md` to the `customer_support` knowledge base. + +```md +# Intelligent Customer Service Knowledge Base + +## 1. Company Introduction + +VE Technology is a high-tech company specializing in intelligent customer service and knowledge management. Our core product is the **Intelligent Customer Service System**, which provides efficient and intelligent automated customer service solutions for enterprise clients through natural language processing and knowledge base retrieval. + +## 2. Product Features + +- **Automatic Q&A**: Quickly respond to common questions based on the knowledge base. +- **Multi-channel Access**: Support for web, App, WeChat, Feishu, and other channels. +- **Intelligent Recommendations**: Recommend relevant answers based on context. +- **Data Analytics**: Provide user question statistics and customer service performance reports. +- **Self-service Knowledge Base Management**: Support for non-technical personnel to quickly edit knowledge content. + +--- + +## 3. Frequently Asked Questions (FAQ) + +### Q1: What languages does the Intelligent Customer Service System support? + +A1: Currently supports **Chinese** and **English**, with Japanese, Korean, and other multi-language support to be added gradually. + +### Q2: Can the system integrate with existing CRMs? + +A2: Yes. Our system supports seamless integration with mainstream CRM systems (such as Salesforce, Zoho, Kingdee) through APIs. + +### Q3: What happens if the bot cannot answer a user's question? + +A3: The system will automatically transfer the question to a human customer service agent and record the question in the backend for administrators to add to the knowledge base. + +### Q4: How often is the knowledge base content updated? + +A4: The knowledge base supports **real-time updates**, taking effect immediately after administrators submit changes. + +## 4. Contact Us + +- Website: [https://www.example.com](https://www.example.com) +- Support Email: support@volcengine.com +- Service Hotline: 400-123-4567 +``` + +## Importing the Knowledge Base + +Through the Volcano Engine Console, import the knowledge base for your agent using [Agentkit-Knowledge](https://console.volcengine.com/agentkit/region:agentkit+cn-beijing/knowledge) + +### Obtaining Connection Information for Memory Resources + +On the memory details - integration code page, obtain the connection information. + +- For VikingDB Knowledge type memory resources, you will see environment variables similar to the following: + +```bash +export DATABASE_VIKING_COLLECTION=customer_support +export DATABASE_VIKING_PROJECT=default +export DATABASE_VIKING_REGION=cn-beijing +``` + +## Building an Agent with Knowledge Base Capabilities + +[VeADK](https://github.com/volcengine/veadk-python) is an open-source agent development framework that provides development, runtime, and debugging capabilities for agents, maintained by the Volcano Engine team. + +The following example demonstrates how to use VeADK to build an agent with knowledge base capabilities, using VikingDB Knowledge as the knowledge base backend. The agent can answer user questions based on the knowledge base according to user input. + +You don't need to build a veadk project from scratch. It is recommended to use agentkit-cli to create a project from the Basic Agent App template (the template uses the VeADK framework). After the template is created, you need to make the following modifications: + +- Add `Knowledgebase` to the Agent +- Configure the environment variables obtained in the previous section to `agentkit.yaml` + +Finally, your code file should look like this: + +```python +''' +**simple agent demo app** + +Before running, the user must set the following environment variables; otherwise, runtime exceptions will inevitably occur: +- MODEL_AGENT_NAME # model id in Volcano Engine Ark platform +- MODEL_AGENT_API_KEY # model api key in Volcano Engine Ark platform + +MODEL_AGENT_NAME and MODEL_AGENT_API_KEY are used to access the model service of the Volcano Engine Ark platform. +''' +import logging +import os + +from veadk import Agent, Runner +from veadk.knowledgebase import KnowledgeBase + + +from agentkit.apps import AgentkitSimpleApp + +logger = logging.getLogger(__name__) + +collection_name = os.getenv("DATABASE_VIKING_COLLECTION") +if not collection_name: + raise ValueError("DATABASE_VIKING_COLLECTION environment variable is not set") + +model_name = "doubao-seed-1-6-250615" + +app = AgentkitSimpleApp() +knowledgebase = KnowledgeBase(backend="viking", index=collection_name) + + +agent = Agent( + instruction="Answer customer's questions according to your knowledgebase.", + model_name=model_name, + knowledgebase=knowledgebase +) +runner = Runner(agent=agent) + + +@app.entrypoint +async def run(payload: dict, headers: dict) -> str: + prompt = payload["prompt"] + user_id = headers["user_id"] + session_id = headers["session_id"] + + logger.info( + f"Running agent with prompt: {prompt}, user_id: {user_id}, session_id: {session_id}" + ) + response = await runner.run(messages=prompt, user_id=user_id, session_id=session_id) + + logger.info(f"Run response: {response}") + return response + + +@app.ping +def ping() -> str: + return "pong!" + + +if __name__ == "__main__": + app.run(host="0.0.0.0", port=8000) +``` + +## Environment Configuration + +Please add the following configuration to your `agentkit.yaml` file: + +``` +launch_types: + cloud: + runtime_envs: + DATABASE_VIKING_COLLECTION: + +``` + +## Starting the Service + +Run `agentkit launch`. The built Runtime connection information will be automatically saved in the `agentkit.yaml` file. + +## How to Initiate a Call + +Execute the following to initiate a call: + +``` +agentkit invoke "What products do you have?" +``` + +You will see the Agent successfully retrieve information from the knowledge base and reorganize the language from `qa.md` to answer you. diff --git a/docs/en/content/8.mcp/1.overview.md b/docs/en/content/8.mcp/1.overview.md new file mode 100644 index 0000000..2da200c --- /dev/null +++ b/docs/en/content/8.mcp/1.overview.md @@ -0,0 +1,43 @@ +# AgentKit MCP + +AgentKit MCP provides a unified MCP gateway and tool governance hub. Through shared instances, pre-built authentication plugins, and automatic search capabilities, it lowers the barrier to entry, reduces token costs, improves tool hit rates and reliability—allowing teams to focus on business logic and user experience refinement. + +**Core Positioning:** Unified entry point, low-barrier access, and a governable tool ecosystem. It handles MCP access and session persistence, combined with OAuth2 and API-Key authentication plugins, as well as cross-tool semantic search capabilities, forming an engineering backbone that is "easy to integrate, governable, and low-cost." + +## AgentKit MCP Features + +AgentKit MCP mainly includes MCP Services and MCP Toolsets. + +### MCP Services + +Supports quickly bringing enterprise existing Web/HTTP services and third-party interfaces into Agents. AgentKit supports two paths: + +1. **Direct MCP Server forwarding** – For backends that already have MCP capabilities +2. **HTTP-to-MCP conversion** – Upload Swagger definitions and rule validations to automatically generate tools and parameter descriptions, allowing historical assets to quickly enter the MCP capability set + +**Applicable Scenarios:** + +- Targeting specific backends (MCP Server or HTTP) +- Providing access domains and session persistence +- Authentication pre-configured at the service level (API-Key, OAuth) +- Suitable for scenarios with controllable and well-defined tool scale + +### MCP Toolsets + +As the number of tools grows or when clients have tool limits (e.g., Trae supports up to 50 tools), automatic search condenses the exposure of the "full tool set" to the LLM into two encapsulated tools: `search` and `use`. Vector retrieval selects high-match tools, reducing context redundancy and latency while improving call accuracy. + +**Applicable Scenarios:** + +- Combining tool collections from multiple MCP services +- Selecting optimal tools through semantic retrieval +- Exposing only two tools, `search` and `use`, to the LLM +- Suitable for scenarios with large tool quantities or client tool limits + +### Authentication & Security + +AgentKit MCP authentication primarily adopts the **OAuth2 Client Credentials** pattern, suitable for frontend applications accessing Agent runtime, server-side tasks accessing Agent runtime, and Agents accessing MCP Servers. It also provides API-Key as a low-dependency alternative, with rotation and hosting planned for future releases. + +**Authentication Mode Distinctions:** + +- **Inbound:** Agent and MCP inbound authentication (OAuth2, API-Key), refined to individual authorization codes and client credentials +- **Outbound:** Gateway credential pass-through or transformation when accessing MCP Servers (API-Key, OAuth client) diff --git a/docs/en/content/8.mcp/2.mcp_quickstart.md b/docs/en/content/8.mcp/2.mcp_quickstart.md new file mode 100644 index 0000000..b81f65e --- /dev/null +++ b/docs/en/content/8.mcp/2.mcp_quickstart.md @@ -0,0 +1,290 @@ +# AgentKit MCP Quick Start + +## Prerequisites + +Before you begin, you need to prepare: + +1. **AccessKey & SecretKey** from a Volcengine account with AgentKit enabled + + > **Tip:** Make sure the AccessKey has `AgentKitFullAccess` permission. + +2. **MCP Service** (can be deployed on VeFaaS or publicly accessible locations) + + - Existing backend services that support MCP + - Existing HTTP services with Swagger API definition JSON. See [Swagger](https://swagger.io/) for details. + +3. **Python 3.10+** installed + +4. **Ark API Key** + +## Step 1: Configure Local Environment + +> You can use `uv` or `python3 -m venv` for virtual environment management. Below we'll use `uv` as an example. +> +> `uv` installation reference: [uv install](https://docs.astral.sh/uv/getting-started/installation/) + +**Virtual Environment Setup** + +```bash +mkdir agentkit-mcp-quickstart +cd agentkit-mcp-quickstart +uv venv --python 3.12.0 +source .venv/bin/activate +``` + +**Install Dependencies** + +> You can specify a mirror source with `--index` to speed up installation. + +```bash +uv pip install veadk-python +uv pip install google-adk +pip install agentkit-sdk-python +``` + +## Step 2: Create AgentKit MCP + +1. Log in to the [AgentKit Console](https://console.volcengine.com/agentkit/region:agentkit+cn-beijing/gateway/mcpservice) on Volcengine. + +2. [Create an MCP Service](https://console.volcengine.com/agentkit/region:agentkit+cn-beijing/gateway/mcpservice/create) for your prepared backend. + +3. Obtain the MCP Service Endpoint and ApiKey after creation. You will see output similar to: + + > `httpUrl` is the MCP Service Endpoint, `Authorization` is the ApiKey. + +```json +{ + "mcpServers": { + "create-http-334df4": { + "httpUrl": "https://sd4fc6lpoh486npgcaav0.apigateway-cn-beijing.volceapi.com/mcp/create-http-334df4", + "headers": { + "Authorization": "Bearer P66l-rpaLbxxxxxxxxxxxxxxo2PQ" + } + } + } +} +``` + +## Step 3: Set Environment Variables and Run Agent + +**Environment Variable Configuration** + +```bash +export MCP_ENDPOINT={{Endpoint obtained in Step 2}} +export MCP_AUTH_KEY={{ApiKey obtained in Step 2}} +export API_KEY={{Ark API Key}} +``` + +**Code Example** + +> In the code example below, we use the VeADK framework to create a simple agent for calling MCP services. + +```python +import logging + +from veadk import Agent, Runner +from veadk.config import getenv +from agentkit.apps import AgentkitSimpleApp +from google.adk.tools.mcp_tool.mcp_toolset import MCPToolset, StreamableHTTPConnectionParams + +logger = logging.getLogger(__name__) + + +url = getenv("MCP_ENDPOINT") +mcp_auth_key = getenv("MCP_AUTH_KEY") +apikey = getenv("API_KEY") + +mcp_ecs_toolset = MCPToolset( + connection_params=StreamableHTTPConnectionParams( + url=url, + headers={"Authorization": f"Bearer {mcp_auth_key}"} + ), +) + +app = AgentkitSimpleApp() + +root_agent = Agent( + name="ecs_helper", + model_name="doubao-1-5-pro-256k-250115", + instruction=''' + Help user find ECS instances and their details. + ''', + description="ECS Helper Agent", + tools=[mcp_ecs_toolset] +) + +runner = Runner(agent=root_agent) + + +@app.entrypoint +async def run(payload: dict, headers: dict) -> str: + prompt = payload["prompt"] + user_id = headers["user_id"] + session_id = headers["session_id"] + + logger.info( + f"Running agent with prompt: {prompt}, user_id: {user_id}, session_id: {session_id}" + ) + + # Run agent, automatically handling tool calls + response = await runner.run( + messages=prompt, + user_id=user_id, + session_id=session_id + ) + + logger.info(f"Run response: {response}") + return response + +@app.ping +def ping() -> str: + """Health check endpoint""" + return "pong!" + +if __name__ == "__main__": + # Start local development server + app.run(host="0.0.0.0", port=8000) +``` + +**Execute Request** + +```bash +curl --location 'http://localhost:8000/invoke' \ + --header 'Content-Type: application/json' \ + --header 'user_id: veadk-test' \ + --header 'session_id: local_session' \ + --data '{"prompt": "Analyze my ECS instances"}' +``` + +**Execution Result** + +```text +2025-10-24 20:17:33 | INFO | ark_veauth.py:25 - Fetching ARK token... +2025-10-24 20:17:33 | INFO | agent.py:118 - Model extra config: {'extra_headers': {'x-is-encrypted': 'true', 'veadk-source': 'veadk', 'veadk-version': '0.2.13', 'User-Agent': 'VeADK/0.2.13', 'X-Client-Request-Id': 'veadk/0.2.13'}, 'extra_body': {'caching': {'type': 'enabled'}, 'expire_at': 1761311852}} +2025-10-24 20:17:33 | DEBUG | agent.py:127 - LiteLLM client created with config: {'extra_headers': {'x-is-encrypted': 'true', 'veadk-source': 'veadk', 'veadk-version': '0.2.13', 'User-Agent': 'VeADK/0.2.13', 'X-Client-Request-Id': 'veadk/0.2.13'}, 'extra_body': {'caching': {'type': 'enabled'}, 'expire_at': 1761311852}} +2025-10-24 20:17:33 | INFO | agent.py:153 - VeADK version: 0.2.13 +2025-10-24 20:17:33 | INFO | agent.py:155 - Agent `ecs_helper` init done. +2025-10-24 20:17:33 | DEBUG | agent.py:156 - Agent: {'name': 'ecs_helper', 'tools': [], 'model_name': 'doubao-1-5-pro-256k-250115', 'model_api_base': 'https://ark.cn-beijing.volces.com/api/v3/'} +2025-10-24 20:17:33 | WARNING | runner.py:198 - No short term memory or session service provided, use an in-memory one instead. +2025-10-24 20:17:33 | INFO | runner.py:217 - No long term memory provided. +INFO: Started server process [1330124] +INFO: Waiting for application startup. +INFO: Application startup complete. +INFO: Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit) +2025-10-24 20:18:35 | INFO | runner.py:250 - Run config: speech_config=None response_modalities=None save_input_blobs_as_artifacts=False support_cfc=False streaming_mode= output_audio_transcription=AudioTranscriptionConfig() input_audio_transcription=AudioTranscriptionConfig() realtime_input_config=None enable_affective_dialog=None proactivity=None session_resumption=None context_window_compression=None save_live_audio=False max_llm_calls=100 +2025-10-24 20:18:35 | DEBUG | runner.py:265 - Auto create session: local_session, user_id: veadk-test, app_name: veadk_default_app +2025-10-24 20:18:38 | DEBUG | runner.py:280 - Function call: id='call_xbyfcvc86wc26mbxz39vst12' args={'region': 'cn-beijing', 'needNum': 10} name='describe_instances' +2025-10-24 20:19:14 | DEBUG | runner.py:288 - Event output: Here are your ECS instance details: +1. **Instance 1**: + - **Instance ID**: i-ye7irm2sqobw80cqxd40 + - **Creation Time**: 2025-10-23T21:36:31+08:00 + - **Billing Method**: PostPaid (Pay-as-you-go) + - **Instance Type**: ecs.e-c1m2.xlarge + - **CPU**: 4 cores (2 cores, 2 threads per core) + - **Memory**: 8192MB + - **OS**: Windows Server 2022 Datacenter Edition 64-bit Chinese + - **Image ID**: image-ye5907jc6ikhx1exow93 + - **Status**: RUNNING + - **Availability Zone**: cn-beijing-a +2. **Instance 2**: + - **Instance ID**: i-ye7ipm0dtsqc6imh310d + - **Creation Time**: 2025-10-23T21:05:44+08:00 + - **Billing Method**: PostPaid (Pay-as-you-go) + - **Instance Type**: ecs.e-c1m2.xlarge + - **CPU**: 4 cores (2 cores, 2 threads per core) + - **Memory**: 8192MB + - **OS**: Debian 12 64 bit + - **Image ID**: image-ydzwsvy72n46nmxzvafi + - **Status**: RUNNING + - **Availability Zone**: cn-beijing-a +3. **Instance 3**: + - **Instance ID**: i-ye7ilsbbpcbw80ca2ymj + - **Creation Time**: 2025-10-23T20:06:54+08:00 + - **Billing Method**: PostPaid (Pay-as-you-go) + - **Instance Type**: ecs.e-c1m2.xlarge + - **CPU**: 4 cores (2 cores, 2 threads per core) + - **Memory**: 8192MB + - **OS**: Windows Server 2022 Datacenter Edition 64-bit Chinese + - **Image ID**: image-ye5907jc6ikhx1exow93 + - **Status**: RUNNING + - **Availability Zone**: cn-beijing-a +4. **Instance 4**: + - **Instance ID**: i-ye7fg1hgqoxjd1utrfy3 + - **Creation Time**: 2025-10-22T14:57:49+08:00 + - **Billing Method**: PostPaid (Pay-as-you-go) + - **Instance Type**: ecs.e-c1m2.xlarge + - **CPU**: 4 cores (2 cores, 2 threads per core) + - **Memory**: 8192MB + - **OS**: Windows Server 2022 Datacenter Edition 64-bit Chinese + - **Image ID**: image-ye5907jc6ikhx1exow93 + - **Status**: RUNNING + - **Availability Zone**: cn-beijing-a +5. **Instance 5**: + - **Instance ID**: i-ye5ejwoow0cva4fqydfc + - **Creation Time**: 2025-09-24T14:25:37+08:00 + - **Billing Method**: PostPaid (Pay-as-you-go) + - **Instance Type**: ecs.e-c1m2.xlarge + - **CPU**: 4 cores (2 cores, 2 threads per core) + - **Memory**: 8192MB + - **OS**: Windows Server 2022 Datacenter Edition 64-bit Chinese + - **Image ID**: image-ye5907jc6ikhx1exow93 + - **Status**: RUNNING + - **Availability Zone**: cn-beijing-a +6. **Instance 6**: + - **Instance ID**: i-ye5ejub08wbw80bpd7hr + - **Creation Time**: 2025-09-24T14:24:35+08:00 + - **Billing Method**: PostPaid (Pay-as-you-go) + - **Instance Type**: ecs.e-c1m2.xlarge + - **CPU**: 4 cores (2 cores, 2 threads per core) + - **Memory**: 8192MB + - **OS**: Windows Server 2022 Datacenter Edition 64-bit Chinese + - **Image ID**: image-ye5907jc6ikhx1exow93 + - **Status**: RUNNING + - **Availability Zone**: cn-beijing-a +7. **Instance 7**: + - **Instance ID**: i-ye5e5jyq68bw80c889i5 + - **Creation Time**: 2025-09-24T10:44:54+08:00 + - **Billing Method**: PostPaid (Pay-as-you-go) + - **Instance Type**: ecs.e-c1m2.xlarge + - **CPU**: 4 cores (2 cores, 2 threads per core) + - **Memory**: 8192MB + - **OS**: Windows Server 2022 Datacenter Edition 64-bit Chinese + - **Image ID**: image-ye5907jc6ikhx1exow93 + - **Status**: RUNNING + - **Availability Zone**: cn-beijing-a +8. **Instance 8**: + - **Instance ID**: i-ye5c4jbx8gqc6ily6b30 + - **Creation Time**: 2025-09-23T16:02:05+08:00 + - **Billing Method**: PostPaid (Pay-as-you-go) + - **Instance Type**: ecs.e-c1m2.xlarge + - **CPU**: 4 cores (2 cores, 2 threads per core) + - **Memory**: 8192MB + - **OS**: Windows Server 2022 Datacenter Edition 64-bit Chinese + - **Image ID**: image-ye5907jc6ikhx1exow93 + - **Status**: RUNNING + - **Availability Zone**: cn-beijing-a +9. **Instance 9**: + - **Instance ID**: i-ye5c4end34xjd1umbfns + - **Creation Time**: 2025-09-23T16:00:05+08:00 + - **Billing Method**: PostPaid (Pay-as-you-go) + - **Instance Type**: ecs.e-c1m2.xlarge + - **CPU**: 4 cores (2 cores, 2 threads per core) + - **Memory**: 8192MB + - **OS**: Debian 12 64 bit + - **Image ID**: image-ydzwsvfxhokhx11pdmlv + - **Status**: RUNNING + - **Availability Zone**: cn-beijing-a +10. **Instance 10**: + - **Instance ID**: i-ye5blj0xdsxjd1tk1vfh + - **Creation Time**: 2025-09-23T11:09:46+08:00 + - **Billing Method**: PostPaid (Pay-as-you-go) + - **Instance Type**: ecs.e-c1m2.xlarge + - **CPU**: 4 cores (2 cores, 2 threads per core) + - **Memory**: 8192MB + - **OS**: Debian 12 64 bit + - **Image ID**: image-ydzwsvfxhokhx11pdmlv + - **Status**: RUNNING + - **Availability Zone**: cn-beijing-a + +All 10 instances are pay-as-you-go with type ecs.e-c1m2.xlarge. Most use Windows Server 2022 Datacenter Edition 64-bit Chinese, with a few using Debian 12 64-bit. All are currently running in availability zone cn-beijing-a. If you need further analysis or have other operation requirements, feel free to ask. +``` diff --git a/docs/en/index.md b/docs/en/index.md new file mode 100644 index 0000000..feb344b --- /dev/null +++ b/docs/en/index.md @@ -0,0 +1,40 @@ +--- +layout: home + +hero: + name: AgentKit + text: Python SDK & CLI + tagline: Quickly build and deploy Agent applications to the Volcengine AgentKit Platform + actions: + - theme: brand + text: Quick Start + link: /en/content/1.introduction/3.quickstart + - theme: alt + text: View Docs + link: /en/content/1.introduction/1.overview + +features: + - icon: 🚀 + title: Quick Initialization + details: Use the agentkit init command to generate a project template with one click, with multiple built-in app types (Basic App, Stream App, etc.) + + - icon: 🛠️ + title: Simple SDK + details: Elegant decorator-based API; define the entry function with @app.entrypoint and focus on business logic development + + - icon: ☁️ + title: Multiple Deployment Modes + details: Supports three deployment modes—Local, Hybrid, and Cloud—flexibly meeting different scenario requirements + + - icon: 🔧 + title: Interactive Configuration + details: Use the agentkit config command for guided configuration of deployment parameters, environment variables, and image registry + + - icon: 📦 + title: One-Click Build & Deploy + details: The agentkit launch command combines build and deploy to automatically build the image and deploy to Runtime + + - icon: 🔌 + title: Platform Integration + details: Seamlessly integrates platform services such as Memory, Knowledge, and MCP Gateway—ready to use out of the box +--- diff --git a/docs/index.md b/docs/index.md index ebea160..0df5f7f 100644 --- a/docs/index.md +++ b/docs/index.md @@ -8,7 +8,7 @@ hero: actions: - theme: brand text: 快速开始 - link: /content/1.introduction/3.quickstart.md + link: /content/1.introduction/3.quickstart - theme: alt text: 查看文档 link: /content/1.introduction/1.overview