Pustaka ini memberi Anda cara mudah untuk membuat dan menjalankan Agen AI dan Kawanan Agen.
Penyedia LLM yang Didukung:
Anda dapat langsung menginstal dengan pip:
pip install swarmzero
Atau bisa juga langsung install dengan puisi :
poetry add swarmzero
Atau tambahkan ke file persyaratan.txt Anda:
...
swarmzero==x.y.z
...
Anda perlu menentukan OPENAI_API_KEY
dalam file .env di direktori ini.
Buat salinan file .env.example dan ganti namanya menjadi .env .
Untuk menggunakan file konfigurasi dengan Agent
Anda, ikuti langkah-langkah berikut:
Buat File Konfigurasi :
swarmzero_config.toml
) di direktori proyek Anda. (Lihat gerombolanzero_config_example.toml).Buat Konteks SDK :
from swarmzero . sdk_context import SDKContext
sdk_context = SDKContext ( config_path = "./swarmzero_config.toml" )
Tentukan Jalur Konfigurasi :
Agent
, berikan jalur relatif atau absolut ke file konfigurasi Anda. from swarmzero import Agent
simple_agent = Agent (
name = "Simple Agent" ,
functions = [],
instruction = "your instructions for this agent's goal" ,
# sdk_context=sdk_context
config_path = "./swarmzero_config.toml"
)
Contoh lebih detail dapat ditemukan di https://github.com/swarmzero/examples
Pertama impor kelas Agent
:
from swarmzero import Agent
Muat variabel lingkungan Anda:
from dotenv import load_dotenv
load_dotenv ()
Kemudian buat instance Agen:
my_agent = Agent (
name = "my_agent" ,
functions = [],
instruction = "your instructions for this agent's goal" ,
)
Kemudian, jalankan agen Anda:
my_agent . run ()
Terakhir, panggil endpoint API /api/v1/chat
, untuk melihat hasilnya:
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?" } ] } '
Anda dapat membuat alat yang membantu agen Anda menangani tugas yang lebih kompleks. Berikut ini contohnya:
import os
from typing import Optional , Dict
from web3 import Web3
from swarmzero import Agent
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 = Agent (
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.
"""
Anda dapat membuat sekumpulan agen untuk berkolaborasi dalam tugas-tugas kompleks. Berikut ini contoh cara menyiapkan dan menggunakan gerombolan:
from swarmzero . swarm import Swarm
from swarmzero . agent import Agent
from swarmzero . sdk_context import SDKContext
import asyncio
# Create SDK Context
sdk_context = SDKContext ( config_path = "./swarmzero_config_example.toml" )
def save_report ():
return "save_item_to_csv"
def search_on_web ():
return "search_on_web"
# Create individual agents
agent1 = Agent ( name = "Research Agent" , instruction = "Conduct research on given topics" , sdk_context = sdk_context ,
functions = [ search_on_web ])
agent2 = Agent ( name = "Analysis Agent" , instruction = "Analyze data and provide insights" , sdk_context = sdk_context ,
functions = [ save_report ])
agent3 = Agent ( name = "Report Agent" , instruction = "Compile findings into a report" , sdk_context = sdk_context , functions = [])
# Create swarm
swarm = Swarm ( name = "Research Team" , description = "A swarm of agents that collaborate on research tasks" ,
instruction = "Be helpful and collaborative" , functions = [], agents = [ agent1 , agent2 , agent3 ])
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 ())
Anda dapat menambahkan alat retriever untuk membuat penyematan vektor dan mengambil informasi semantik. Ini akan membuat indeks vektor untuk setiap dokumen pdf di bawah folder 'swarmzero-data/files/user' dan dapat memfilter file dengan parameter yang diperlukan_exts.
from swarmzero import Agent
from dotenv import load_dotenv
load_dotenv ()
if __name__ == "__main__" :
my_agent = Agent (
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?" } ] }'
```
"""
Pengguna agen/swarm Anda mungkin tidak selalu terbiasa dengan kemampuannya. Memberikan contoh petunjuk memungkinkan mereka menjelajahi apa yang telah Anda buat. Berikut cara menambahkan contoh perintah yang dapat mereka gunakan sebelum berkomitmen menggunakan agen/swarm Anda.
Di file gerombolanzero_config.toml Anda, buat entri tingkat atas bernama [sample_prompts]
dan tambahkan array baru ke prompts
utama seperti ini:
[ 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? "
]
Lihat ./swarmzero_config_example.toml untuk contoh file konfigurasi.
Jika Anda ingin berkontribusi pada basis kode, Anda perlu menyiapkan lingkungan pengembang Anda. Ikuti langkah-langkah berikut:
OPENAI_API_KEY
dari OpenAIcurl -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
File laporan tests/htmlcov/index.html
Buka http://localhost:8000/docs dengan browser Anda untuk melihat UI Swagger dari API.
https://swarmzero.ai