該庫為您提供了一種創建和運行 Hive 代理的簡單方法。
加入我們的 Discord 社群以獲得支持和討論。
您可以直接從 pip 安裝:
pip install git+https://github.com/hivenetwork-ai/hive-agent-py.git@main
或將其新增至您的requirements.txt檔案:
hive-agent @ git+https://github.com/hivenetwork-ai/hive-agent-py@main
若要安裝可選的 web3 依賴項,您可以如下指定它們:
pip install git+https://github.com/hivenetwork-ai/hive-agent-py.git@main#egg=hive-agent[web3]
或將其新增至您的requirements.txt檔案:
hive-agent[web3] @ git+https://github.com/hivenetwork-ai/hive-agent-py@main
您需要在此目錄中的.env檔中指定OPENAI_API_KEY
。
複製 .env.example 檔案並將其重命名為.env 。
若要將設定檔與HiveAgent
一起使用,請依照下列步驟操作:
建立設定檔:
hive_config.toml
)。 (請參閱 hive_config_example.toml)。建立 SDK 上下文:
from hive_agent . sdk_context import SDKContext
sdk_context = SDKContext ( config_path = "./hive_config.toml" )
指定配置路徑:
HiveAgent
實例時,提供設定檔的相對或絕對路徑。 from hive_agent import HiveAgent
import os
def get_config_path ( filename ):
return os . path . abspath ( os . path . join ( os . path . dirname ( __file__ ), filename ))
simple_agent = HiveAgent (
name = "Simple Agent" ,
functions = [],
instruction = "your instructions for this agent's goal" ,
sdk_context = sdk_context
#config_path=get_config_path("hive_config.toml") # ./hive_config.toml works too
)
首先導入HiveAgent
類別:
from hive_agent import HiveAgent
載入您的環境變數:
from dotenv import load_dotenv
load_dotenv ()
然後建立一個HiveAgent實例:
my_agent = HiveAgent (
name = "my_agent" ,
functions = [],
instruction = "your instructions for this agent's goal" ,
)
然後,運行您的代理:
my_agent . run ()
最後,呼叫 API 端點/api/v1/chat
來查看結果:
curl --request POST
--url http://localhost:8000/api/v1/chat
--header ' Content-Type: multipart/form-data '
--form ' user_id="test" '
--form ' session_id="test" '
--form ' chat_data={ "messages": [ { "role": "user", "content": "Who is Satoshi Nakamoto?" } ] } '
您可以建立工具來幫助您的代理處理更複雜的任務。這是一個例子:
import os
from typing import Optional , Dict
from web3 import Web3
from hive_agent import HiveAgent
from dotenv import load_dotenv
load_dotenv ()
rpc_url = os . getenv ( "RPC_URL" ) # add an ETH Mainnet HTTP RPC URL to your `.env` file
def get_transaction_receipt ( transaction_hash : str ) -> Optional [ Dict ]:
"""
Fetches the receipt of a specified transaction on the Ethereum blockchain and returns it as a dictionary.
:param transaction_hash: The hash of the transaction to fetch the receipt for.
:return: A dictionary containing the transaction receipt details, or None if the transaction cannot be found.
"""
web3 = Web3 ( Web3 . HTTPProvider ( rpc_url ))
if not web3 . is_connected ():
print ( "unable to connect to Ethereum" )
return None
try :
transaction_receipt = web3 . eth . get_transaction_receipt ( transaction_hash )
return dict ( transaction_receipt )
except Exception as e :
print ( f"an error occurred: { e } " )
return None
if __name__ == "__main__" :
my_agent = HiveAgent (
name = "my_agent" ,
functions = [ get_transaction_receipt ]
)
my_agent . run ()
"""
[1] send a request:
```
curl --request POST
--url http://localhost:8000/api/v1/chat
--header 'Content-Type: multipart/form-data'
--form 'user_id="test"'
--form 'session_id="test"'
--form 'chat_data={ "messages": [ { "role": "user", "content": "Who is the sender of this transaction - 0x5c504ed432cb51138bcf09aa5e8a410dd4a1e204ef84bfed1be16dfba1b22060" } ] }'
```
[2] result:
The address that initiated the transaction with hash 0x5c504ed432cb51138bcf09aa5e8a410dd4a1e204ef84bfed1be16dfba1b22060 is 0xA1E4380A3B1f749673E270229993eE55F35663b4.
"""
您可以建立一群代理來協作完成複雜的任務。以下是如何設定和使用 swarm 的範例:
from hive_agent . swarm import HiveSwarm
from hive_agent . agent import HiveAgent
from hive_agent . sdk_context import SDKContext
from hive_agent . llms . utils import llm_from_config
from hive_agent . utils import tools_from_funcs
from hive_agent . llms . claude import ClaudeLLM
import asyncio
# Create SDK Context
sdk_context = SDKContext ( config_path = "./hive_config_example.toml" )
def save_report ():
return "save_item_to_csv"
def search_on_web ():
return "search_on_web"
#You can use the default config using default_config or the config of a specific agent by using the get_config method.
llm = llm_from_config ( sdk_context . get_config ( "target_agent_id" ))
tools = tools_from_funcs ([ search_on_web ])
claude = ClaudeLLM ( llm = llm , tools = tools )
# Create individual agents
agent1 = HiveAgent ( name = "Research Agent" , instruction = "Conduct research on given topics" , sdk_context = sdk_context , functions = [ search_on_web ], llm = claude )
agent2 = HiveAgent ( name = "Analysis Agent" , instruction = "Analyze data and provide insights" , sdk_context = sdk_context , functions = [ save_report ])
agent3 = HiveAgent ( name = "Report Agent" , instruction = "Compile findings into a report" , sdk_context = sdk_context , functions = [])
# Create swarm
swarm = HiveSwarm ( name = "Research Team" , description = "A swarm of agents that collaborate on research tasks" ,
instruction = "Be helpful and collaborative" , functions = [], agents = [ agent1 , agent2 , agent3 ], sdk_context = sdk_context )
async def chat_with_swarm ():
return await swarm . chat ( "Can you analyze the following data: [1, 2, 3, 4, 5]" )
if __name__ == "__main__" :
asyncio . run ( chat_with_swarm ())
您可以新增檢索器工具來建立向量嵌入並檢索語義資訊。它將為「hive-agent-data/files/user」資料夾下的每個 pdf 文件建立向量索引,並可使用 required_exts 參數過濾檔案。
import os
from typing import Optional , Dict
from web3 import Web3
from hive_agent import HiveAgent
from dotenv import load_dotenv
load_dotenv ()
if __name__ == "__main__" :
my_agent = HiveAgent (
name = "retrieve-test" ,
functions = [],
retrieve = True ,
required_exts = [ '.md' ],
retrieval_tool = 'chroma'
)
my_agent . run ()
"""
[1] send a request:
```
curl --request POST
--url http://localhost:8000/api/v1/chat
--header 'Content-Type: multipart/form-data'
--form 'user_id="test"'
--form 'session_id="test"'
--form 'chat_data={ "messages": [ { "role": "user", "content": "Can you summarise the documents?" } ] }'
```
"""
您的代理商/群組的用戶可能並不總是熟悉其功能。提供範例提示可以讓他們探索您所建立的內容。以下是如何添加範例提示,他們可以在承諾使用您的代理/群組之前使用這些提示。
在 hive_config.toml 檔案中,建立一個名為[sample_prompts]
的頂層條目,並將一個新數組加入到按鍵prompts
中,如下所示:
[ sample_prompts ]
prompts = [
" What can you help me do? " ,
" Which tools do you have access to? " ,
" What are your capabilities? "
]
[ target_agent_id ]
model = " gpt-3.5-turbo "
timeout = 15
environment = " dev "
enable_multi_modal = true
ollama_server_url = ' http://123.456.78.90:11434 '
sample_prompts = [
" What can you help me do? " ,
" Which tools do you have access to? " ,
" What are your capabilities? "
]
有關範例設定文件,請參閱 ./hive_config_example.toml。
完整的教學可以在./tutorial.md 中找到。
如果您想為程式碼庫做出貢獻,您需要設定您的開發環境。請依照下列步驟操作:
OPENAI_API_KEY
curl -sSL https://install.python-poetry.org | python3 -
export PATH= " $HOME /.local/bin: $PATH "
poetry shell
poetry install --no-root
tests/
目錄中: cd tests/
pytest
pytest tests/path/to/test_module.py
pytest -v
pytest -s
pip install coverage pytest-cov
pytest --cov --cov-report=html
報告文件tests/htmlcov/index.html
使用瀏覽器開啟 http://localhost:8000/docs 以查看 API 的 Swagger UI。
https://swarmzero.ai