在數字化轉型的浪潮中,智能體開發SDK成為了推動各行各業智能化升級的關鍵力量。無論是自動化辦公、數據分析還是代碼生成,智能體都展現出了前所未有的潛力和價值。本文將深入探討如何利用火貓網絡提供的智能體開發SDK,構建高效且強大的智能體。
智能體是一種具備感知、決策和執行能力的自主系統。它能夠從環境中獲取信息,結合自身的知識或模型進行推理和判斷,并通過調用工具或執行操作來完成任務。與傳統程序不同,智能體不僅僅是被動執行預設指令,而是具備一定程度的自主性和適應性,能夠在復雜、多變的環境中不斷優化行為。
使用現成的智能體:
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())
開發你的第一個智能體:
從實際使用的角度考慮,一個智能體要對我們有用,它必須具備哪些基本要素呢?從 MetaGPT 的觀點來看,如果一個智能體能夠執行某些動作(無論是由 LLM 驅動還是其他方式),它就具有一定的用途。簡單來說,我們定義智能體應該具備哪些行為,為智能體配備這些能力,我們就擁有了一個簡單可用的智能體!MetaGPT 提供高度靈活性,以定義您自己所需的行為和智能體。我們將在本節的其余部分指導您完成這一過程。
一個智能體的運行周期可以分為以下幾個步驟:
假設我們想用自然語言編寫代碼,并想讓一個智能體為我們做這件事。讓我們稱這個智能體為 SimpleCoder,我們需要兩個步驟來讓它工作:
定義動作:
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
運行你的角色:
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)
我們注意到一個智能體能夠執行一個動作,但如果只有這些,實際上我們并不需要一個智能體。通過直接運行動作本身,我們可以得到相同的結果。智能體的力量,或者說Role抽象的驚人之處,在于動作的組合(以及其他組件,比如記憶,但我們將把它們留到后面的部分)。通過連接動作,我們可以構建一個工作流程,使智能體能夠完成更復雜的任務。
假設現在我們不僅希望用自然語言編寫代碼,而且還希望生成的代碼立即執行。一個擁有多個動作的智能體可以滿足我們的需求。讓我們稱之為RunnableCoder,一個既寫代碼又立即運行的Role。我們需要兩個Action:SimpleWriteCode 和 SimpleRunCode。
定義動作:
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
運行你的角色:
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)
通過上述示例,我們展示了如何使用火貓網絡提供的智能體開發SDK來構建高效的智能體。無論是在簡單的代碼生成任務,還是在復雜的多步驟任務中,智能體都能展現出其獨特的優勢。火貓網絡致力于提供一站式的智能體開發解決方案,幫助企業和開發者快速實現智能化升級。
業務包括網站開發,小程序開發,智能體工作流開發。聯系方式為:18665003093(徐) 微信號同手機號。