跳转至

易用、灵活、高效的开源大模型应用开发框架

pip install -U Agently
git clone git@github.com:Maplemx/Agently.git

> 阅读开发教程 > GitHub项目页面


框架特点

  • 语法简单易学,5分钟开始使用


    使用pip install -U Agently安装后即可直接在Python代码中使用。

    只需要通过几行代码指定好驱动Agent实例的大模型,提供对应的鉴权信息,即可在Python代码中嵌入可以响应指令请求的Agent实例,您可以使用链式风格的调用方法,像调用函数一样和Agent实例交互。

    阅读快速开始代码样例

  • 为工程开发者设计,应用开发灵活性高


    使用Agently框架,您可以向Agent实例传递结构化数据来灵活表达请求诉求,也可以在框架里轻松管理Agent实例的各种设定信息,还可以方便地将自定义函数方法提供给Agent实例使用

    您还可以方便地监听和处理流式输出的结果,或是使用Agently Workflow将复杂的任务切分成块,有序连接(支持可连接成环的有序单向流)。

    阅读由浅入深开发教程

  • 具有深度的架构设计和底层思想


    Agently框架深度理解并解构了大模型驱动的Agent结构,在框架核心维护了模型请求前后置信息流处理工作流、结构化数据解析、实例生命周期数据管理等构成Agent工作过程的基础原子要件,解除了业务表达层和模型请求层之间的耦合。

    在此基础之上,通过能力插件、工作流管理方案等能力进一步增强开发者在应用层的表达丰富度。

    阅读框架思想的关键概念

代码样例

Python代码
"""创建Agent实例"""
import Agently
agent = (
    Agently.create_agent()
        # 支持通过配置快速切换多种模型
        # 将代码的业务逻辑表达和模型配置格式依赖解耦
        .set_settings("current_model", "OpenAI")
        .set_settings("model.OpenAI.auth", { "api_key": "******" })
        # 支持设置Proxy进行前向代理
        .set_proxy("http://127.0.0.1:7890")
)
"""进行基础请求"""
result = (
    agent
        # 支持str格式输入
        .input("给我输出3个单词和2个句子")
        # 支持Key-Value格式输入
        .instruct("输出语言", "中文")
        # 支持dict格式输入
        # 并且通过框架特有的(<type>, <desc>)语法格式描述生成元素
        .output({
            "单词": [("str", )], # 没有<desc>可省略
            "句子": ("list", ),
        })
        .start()
)
print(result)
运行结果
{'单词': ['苹果', '电脑', '学习'], '句子': ['我喜欢吃苹果。', '他用电脑工作。']}
Python代码
"""创建Agent实例"""
import Agently
agent = (
    Agently.create_agent()
        .set_settings("current_model", "ZhipuAI")
        .set_settings("model.ZhipuAI.auth", { "api_key": "******" }
)
"""进行Agent实例设定"""
( agent
      .set_role("职业", "一个温柔、耐心的少儿陪伴专家")
      .set_user_info("姓名", "Max")
      .append_user_info(
            "关键信息",
            [
                "我今年7岁",
                "我比较喜欢听别人用讲故事的方式跟我解释一件事情",
                "对于新的概念,我比较喜欢通过类比我已经知道的事情来学习",
                "我对于小学校园、动物园、游乐场比较熟悉",
                "我有时候会玩例如我的世界、模拟城市这样的电子游戏",
            ]
        )
)
"""发起请求"""
print(agent.input("代码编程能做什么?").start())  
运行结果
嗨,Max!编程就像是在创造一个故事或者一个世界,不过用的是计算机能理解的“语言”。编程可以做很多有趣和有用的事情哦:

1. **创造游戏**:就像你玩的“我的世界”和“模拟城市”,这些游戏都是通过编程来创造的。你可以用编程来设计自己的游戏,决定游戏里面的规则和故事。

2. **解决问题**:编程能帮助解决数学问题,比如计算你的成绩或者帮你理解数学概念。

3. **制作动画和电影**:你看过动画片吗?很多动画电影和电视节目都是用特殊的编程软件制作的,让角色动起来。

4. **控制机器人**:如果你喜欢去动物园,想象一下如果你能通过编程控制一个机器人,让它去探索动物的生活,是不是很有趣?

5. **网站和应用程序**:像你浏览的网页,或者玩的游戏,都是程序员用编程语言创造出来的。

6. **学习新事物**:编程能帮你通过类比学习新概念,比如你可以把编程比作是搭建一个游乐场,每条代码就像是你用的积木,一块一块搭建成一个完整的游乐场。

7. **分享故事**:如果你喜欢听故事,编程也可以帮你把故事变成互动的形式,让故事更加生动有趣。

编程就像是一种魔法,能把你脑海中的想象变成现实。怎么样,是不是很酷? 
Python代码
"""创建Agent实例"""
import Agently
agent = (
    Agently.create_agent()
        .set_settings("current_model", "ERNIE") #文心一言
        .set_settings("model.ERNIE.auth", { "aistudio": "******" }
)
"""设定Agent实例可调用的工具"""
( agent
    .use_public_tools(["search"]
    # 设定Proxy(如果有需要)
    .set_tool_proxy("http://127.0.0.1:7890")
)
"""发起请求"""
print(agent.input("什么是Agently框架?").start())  
运行结果
Agently是一个帮助大语言模型(LLM)应用开发者快速构建AI agent原生应用的开发框架。

它允许插件开发者将插件打包在框架主包之外,并单独分享他们的插件包给其他开发者。

开发者只需要下载插件包,将文件解压到他们的工作文件夹中,然后轻松安装插件。

Agently还提供了创建和管理基于大语言模型的Agent实例的功能,并能管理他们的人设和记忆,适用于客服机器人、角色扮演机器人等应用。

此外,Agently还不断更新版本,为开发者提供更多便利的功能和工具。

更多信息可以参考Agently的GitHub官方仓库:[Agently](https://github.com/Maplemx/Agently) 
Python代码
"""创建Agent实例"""
import Agently
agent = (
    Agently.create_agent()
        .set_settings("current_model", "Claude")
        .set_settings("model.Claude.auth", { "api_key": "******" }
)
"""定义并注册自定义工具"""
# 自定义工具函数及依赖
from datetime import datetime
import pytz
def get_current_datetime(timezone):
    tz = pytz.timezone(timezone)
    return datetime.now().astimezone(tz)
# 自定义工具信息字典
tool_info = {
    "tool_name": "get_now",
    "desc": "get current data and time",
    "args": {
        "timezone": (
            "str",
            "[*Required] Timezone string used in pytz.timezone() in Python"
        )
    },
    "func": get_current_datetime
}
# 向Agent实例注册自定义工具
agent.register_tool(
    tool_name = tool_info["tool_name"],
    desc = tool_info["desc"],
    args = tool_info["args"],
    func = tool_info["func"],
)
"""发起请求"""
print(agent.input("我在北京,现在几点了?").start())  
运行结果
根据您提供的信息,在北京时间 2024年4月6日 21点43分22秒。如需了解更多相关信息,您可以查阅 [北京时间](https://time.is/Beijing) 网站。
Python代码
"""创建Agent实例"""
import Agently
agent = (
    Agently.create_agent()
        .set_settings("current_model", "Google")
        .set_settings("model.Google.auth", { "api_key": "******" }
)
"""声明流式输出结果的处理方法"""
@agent.on_event("delta")
def delta_event_handler(data):
    print(">", data, end="")
"""发起请求"""
agent.input("请输出一段话。").start()  
运行结果
> 在广袤无垠的宇宙中,一颗蔚蓝色的星球默默旋转
> 着,那是我们的家园——地球。它是一个充满生机与奇迹的世界,从 towering mountaintops 到 deepest oceans,无处不展现着大
> 自然的鬼斧神工。地球是我们赖以生存的家园,是我们生命和梦想的摇篮,值得我们珍惜和保护。
Python代码
"""创建Agent实例和Workflow实例"""
import Agently
agent = (
    Agently.create_agent()
        .set_settings("current_model", "OAIClient")
        .set_settings("model.OAIClient.url", "https://api.moonshot.cn/v1")
        .set_settings("model.OAIClient.options", { "model": "moonshot-v1-8k" })
        .set_settings("model.OAIClient.auth", { "api_key": "******" })
)
workflow = Agently.Workflow()
"""创建执行块(Chunk)"""
# 启动块
@workflow.chunk(
    chunk_id = "Start",
    type = "Start"
)

# 用户输入块
@workflow.chunk(
    chunk_id = "User Input",
    handles = {
        "outputs": [{ "handle": "user_input" }],
    }
)
def user_input_executor(inputs, storage):
    return { "user_input": input("[User]: ") }

# Agent回复块
@workflow.chunk(
    chunk_id = "Assistant Reply",
    handles = {
        "inputs": [{ "handle": "user_input" }],
        "outputs": [{ "handle": "assistant_reply" }],
    }
)
def assistant_reply_executor(inputs, storage):
    chat_history = storage.get("chat_history") or []
    reply = (
        agent
            .chat_history(chat_history)
            .input(inputs["user_input"])
            .start()
    )
    print("[Assistant]: ", reply)
    return { "assistant_reply": reply }

# 对话记录更新块
@workflow.chunk(
    chunk_id = "Update Chat History",
    handles = {
        "inputs": [
            { "handle": "user_input" },
            { "handle": "assistant_reply" },
        ],
    },
)
def update_chat_history_executor(inputs, storage):
    chat_history = storage.get("chat_history") or []
    chat_history.append({ "role": "user", "content": inputs["user_input"] })
    chat_history.append({ "role": "assistant", "content": inputs["assistant_reply"] })
    storage.set("chat_history", chat_history)
    return

# 退出块
@workflow.chunk(
    chunk_id = "Goodbye",
)
def goodbye_executor(inputs, storage):
    print("Bye~👋")
    return

"""连接执行块"""
workflow.chunks["Start"].connect_to(workflow.chunks["User Input"])
(
    workflow.chunks["User Input"].handle("user_input")
        .if_condition(lambda data: data == "#exit").connect_to(workflow.chunks["Goodbye"])
        .else_condition().connect_to(workflow.chunks["Assistant Reply"].handle("user_input"))
)
workflow.chunks["User Input"].handle("user_input").connect_to(workflow.chunks["Update Chat History"].handle("user_input"))
workflow.chunks["Assistant Reply"].handle("assistant_reply").connect_to(workflow.chunks["Update Chat History"].handle("assistant_reply"))
workflow.chunks["Update Chat History"].connect_to(workflow.chunks["User Input"])

"""获取工作流Mermaid代码(可绘图)"""
print(workflow.draw())

"""启动工作流"""
workflow.start()
%%{ init: { 'flowchart': { 'curve': 'linear' }, 'theme': 'neutral' } }%%
%% Rendered By Agently %%
flowchart LR
    f9024ca5-18d9-44a8-9377-11f0e23c097a("Start") -.-> |"output -->-- input"| a5971148-6f84-488f-821a-89653b5a6941("User Input")
    a5971148-6f84-488f-821a-89653b5a6941("User Input") -.-> |"user_input -- ◇ -- input"| faf731fe-50f8-4074-adbf-7f3900812a68("Goodbye")
    a5971148-6f84-488f-821a-89653b5a6941("User Input") -.-> |"user_input -- ◇ -- user_input"| f3540386-0f51-47da-8fde-5ec8d6b21bc7("Assistant Reply")
    a5971148-6f84-488f-821a-89653b5a6941("User Input") -.-> |"user_input -->-- user_input"| 45500531-d427-4227-9cdd-e7b3f7f1aaaf("Update Chat History")
    f3540386-0f51-47da-8fde-5ec8d6b21bc7("Assistant Reply") -.-> |"assistant_reply -->-- assistant_reply"| 45500531-d427-4227-9cdd-e7b3f7f1aaaf("Update Chat History")
    45500531-d427-4227-9cdd-e7b3f7f1aaaf("Update Chat History") -.-> |"output -->-- input"| a5971148-6f84-488f-821a-89653b5a6941("User Input")

实战案例

去案例广场查看更多案例

加入讨论群

  • 加入微信讨论群


    点击这里或扫描下方二维码申请入群

  • 加入Discord讨论群


    点击这里或扫描下方二维码直接加入