智能體開發(fā)SDK:構(gòu)建高效智能體的利器


在數(shù)字化轉(zhuǎn)型的浪潮中,智能體開發(fā)SDK成為了推動(dòng)各行各業(yè)智能化升級(jí)的關(guān)鍵力量。無論是自動(dòng)化辦公、數(shù)據(jù)分析還是代碼生成,智能體都展現(xiàn)出了前所未有的潛力和價(jià)值。本文將深入探討如何利用火貓網(wǎng)絡(luò)提供的智能體開發(fā)SDK,構(gòu)建高效且強(qiáng)大的智能體。
智能體入門
智能體是一種具備感知、決策和執(zhí)行能力的自主系統(tǒng)。它能夠從環(huán)境中獲取信息,結(jié)合自身的知識(shí)或模型進(jìn)行推理和判斷,并通過調(diào)用工具或執(zhí)行操作來完成任務(wù)。與傳統(tǒng)程序不同,智能體不僅僅是被動(dòng)執(zhí)行預(yù)設(shè)指令,而是具備一定程度的自主性和適應(yīng)性,能夠在復(fù)雜、多變的環(huán)境中不斷優(yōu)化行為。
使用現(xiàn)成的智能體:
import asyncio
from metagpt.context import Context
from metagpt.roles.product_manager import ProductManager
from metagpt.logs import logger
async def main():
msg = "Write a PRD for a snake game"
context = Context()
role = ProductManager(context=context)
while msg:
msg = await role.run(msg)
logger.info(str(msg))
if __name__ == '__main__':
asyncio.run(main())
開發(fā)你的第一個(gè)智能體:
從實(shí)際使用的角度考慮,一個(gè)智能體要對(duì)我們有用,它必須具備哪些基本要素呢?從 MetaGPT 的觀點(diǎn)來看,如果一個(gè)智能體能夠執(zhí)行某些動(dòng)作(無論是由 LLM 驅(qū)動(dòng)還是其他方式),它就具有一定的用途。簡(jiǎn)單來說,我們定義智能體應(yīng)該具備哪些行為,為智能體配備這些能力,我們就擁有了一個(gè)簡(jiǎn)單可用的智能體!MetaGPT 提供高度靈活性,以定義您自己所需的行為和智能體。我們將在本節(jié)的其余部分指導(dǎo)您完成這一過程。
智能體運(yùn)行周期的流程圖
一個(gè)智能體的運(yùn)行周期可以分為以下幾個(gè)步驟:
- 初始化智能體并設(shè)置上下文
- 接收用戶輸入或指令
- 解析輸入并調(diào)用相應(yīng)的動(dòng)作
- 執(zhí)行動(dòng)作并返回結(jié)果
- 更新狀態(tài)并繼續(xù)循環(huán)
具有單一動(dòng)作的智能體
假設(shè)我們想用自然語(yǔ)言編寫代碼,并想讓一個(gè)智能體為我們做這件事。讓我們稱這個(gè)智能體為 SimpleCoder,我們需要兩個(gè)步驟來讓它工作:
- 定義一個(gè)編寫代碼的動(dòng)作
- 為智能體配備這個(gè)動(dòng)作
定義動(dòng)作:
from metagpt.actions import Action
class SimpleWriteCode(Action):
PROMPT_TEMPLATE: str = """
Write a python function that can {instruction} and provide two runnnable test cases.
Return ```python your_code_here ``` with NO other texts,
your code:
"""
name: str = "SimpleWriteCode"
async def run(self, instruction: str):
prompt = self.PROMPT_TEMPLATE.format(instruction=instruction)
rsp = await self._aask(prompt)
code_text = SimpleWriteCode.parse_code(rsp)
return code_text
@staticmethod
def parse_code(rsp):
pattern = r"```python(.*)```"
match = re.search(pattern, rsp, re.DOTALL)
code_text = match.group(1) if match else rsp
return code_text
定義角色:
from metagpt.roles import Role
class SimpleCoder(Role):
name: str = "Alice"
profile: str = "SimpleCoder"
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.set_actions([SimpleWriteCode])
async def _act(self) -> Message:
logger.info(f"{self._setting}: to do {self.rc.todo}({self.rc.todo.name})")
todo = self.rc.todo # todo will be SimpleWriteCode()
msg = self.get_memories(k=1)[0] # find the most recent messages
code_text = await todo.run(msg.content)
msg = Message(content=code_text, role=self.profile, cause_by=type(todo))
return msg
運(yùn)行你的角色:
import asyncio
from metagpt.context import Context
async def main():
msg = "write a function that calculates the sum of a list"
context = Context()
role = SimpleCoder(context=context)
logger.info(msg)
result = await role.run(msg)
logger.info(result)
asyncio.run(main)
具有多個(gè)動(dòng)作的智能體
我們注意到一個(gè)智能體能夠執(zhí)行一個(gè)動(dòng)作,但如果只有這些,實(shí)際上我們并不需要一個(gè)智能體。通過直接運(yùn)行動(dòng)作本身,我們可以得到相同的結(jié)果。智能體的力量,或者說Role抽象的驚人之處,在于動(dòng)作的組合(以及其他組件,比如記憶,但我們將把它們留到后面的部分)。通過連接動(dòng)作,我們可以構(gòu)建一個(gè)工作流程,使智能體能夠完成更復(fù)雜的任務(wù)。
假設(shè)現(xiàn)在我們不僅希望用自然語(yǔ)言編寫代碼,而且還希望生成的代碼立即執(zhí)行。一個(gè)擁有多個(gè)動(dòng)作的智能體可以滿足我們的需求。讓我們稱之為RunnableCoder,一個(gè)既寫代碼又立即運(yùn)行的Role。我們需要兩個(gè)Action:SimpleWriteCode 和 SimpleRunCode。
定義動(dòng)作:
class SimpleRunCode(Action):
name: str = "SimpleRunCode"
async def run(self, code_text: str):
result = subprocess.run(["python3", "-c", code_text], capture_output=True, text=True)
code_result = result.stdout
logger.info(f"{code_result=}")
return code_result
定義角色:
class RunnableCoder(Role):
name: str = "Alice"
profile: str = "RunnableCoder"
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.set_actions([SimpleWriteCode, SimpleRunCode])
self._set_react_mode(react_mode="by_order")
async def _act(self) -> Message:
logger.info(f"{self._setting}: to do {self.rc.todo}({self.rc.todo.name})")
# By choosing the Action by order under the hood
# todo will be first SimpleWriteCode() then SimpleRunCode()
todo = self.rc.todo
msg = self.get_memories(k=1)[0] # find the most k recent messages
result = await todo.run(msg.content)
msg = Message(content=result, role=self.profile, cause_by=type(todo))
self.rc.memory.add(msg)
return msg
運(yùn)行你的角色:
import asyncio
from metagpt.context import Context
async def main():
msg = "write a function that calculates the sum of a list"
context = Context()
role = RunnableCoder(context=context)
logger.info(msg)
result = await role.run(msg)
logger.info(result)
asyncio.run(main)
總結(jié)
通過上述示例,我們展示了如何使用火貓網(wǎng)絡(luò)提供的智能體開發(fā)SDK來構(gòu)建高效的智能體。無論是在簡(jiǎn)單的代碼生成任務(wù),還是在復(fù)雜的多步驟任務(wù)中,智能體都能展現(xiàn)出其獨(dú)特的優(yōu)勢(shì)?;鹭埦W(wǎng)絡(luò)致力于提供一站式的智能體開發(fā)解決方案,幫助企業(yè)和開發(fā)者快速實(shí)現(xiàn)智能化升級(jí)。
業(yè)務(wù)包括網(wǎng)站開發(fā),小程序開發(fā),智能體工作流開發(fā)。聯(lián)系方式為:18665003093(徐) 微信號(hào)同手機(jī)號(hào)。
