Skip to Content

Agentverse: allowed imports

Introduction

In the Agentverse code editor, you have the freedom to import and utilize a selected set of modules to create your code, while maintaining security and control. These pre-approved modules offer a diverse range of functionalities, allowing you to build complex agents.

The Agentverse now provides full Python support! This means that all Hosted Agents will now support the full Python built-in library plus the following packages:

Allowed imports

uagents

Build fast and lightweight for decentralized scenarios using the uagents Framework. Checkout the Agents documentation and the uagents package for more information.

  • Available classes: Model, Context, Protocol.

    Example:

    from uagents import Context, Model class Message(Model): text: str @agent.on_interval(period=2.0) async def print_message(ctx: Context): msg = Message(text=f"Hello there my wallet address is {ctx.wallet}.") print(msg.text)

requests

This package allows you to interact with HTTP requests and responses.

  • Available functions: get, post, put, patch, delete.

    Example:

    import requests response = requests.get('https://api.github.com') if response.status_code == 200: print('Success!') elif response.status_code == 404: print('Not Found.') print(response.headers)

cosmpy

A Python library for interacting with Cosmos-based blockchains. Checkout the CosmPy documentation and the cosmpy package for more information.

  • Full access to all functions and features.

    Example:

    from cosmpy import aerial # Define network configuration, faucet and ledger network = aerial.client.NetworkConfig.fetchai_stable_testnet() faucet_api = aerial.faucet.FaucetApi(network) ledger = aerial.client.LedgerClient(network) MINIMUM_BALANCE = 100000000000000000 @agent.on_interval(period=20.0) async def get_tokens(ctx: Context): agent_balance = ledger.query_bank_balance(ctx.wallet) if agent_balance < MINIMUM_BALANCE: print("Providing wealth to agent...") faucet_api.get_wealth(ctx.wallet)

pydantic

A package to ensure data validation and settings management. It simplifies the process of defining and validating data models by providing a way to declare and enforce data types, constraints, and validation rules on Python data structures.

  • Full access to all functions and features.

    Example:

    from pydantic import BaseModel data = { "name": "alice", "age": 21 } class User(BaseModel): name: str age: int user = User(**data) print(user)

uagents-ai-engine

Integrate Agents with the AI Engine to perform a wide variety tasks, including in booking services, make reservations, and provide answers to different queries. Checkout the AI Engine documentation and the uagents-ai-engine package for further information.

  • Full access to all functions and features.

    Example:

    from uagents import Context, Model, Protocol from ai_engine import UAgentResponse, UAgentResponseType simples = Protocol(name="simples", version="v1.1") class Request(Model): message: str @simples.on_message(model=Request, replies={UAgentResponse}) async def handle_message(ctx: Context, sender: str, msg: Request): await ctx.send(sender, UAgentResponse(message="0", type=UAgentResponseType.FINAL))

MySQLdb

MySQLdb is a Python library for accessing MySQL databases. It provides a Python interface to MySQL, allowing you to interact with MySQL databases from within your Python code.

  • Full access to all functions and features.

    Example:

    import MySQLdb # Connect to the MySQL database connection = MySQLdb.connect(host='localhost', user='username', passwd='password', db='database_name') try: # Create a cursor object to execute SQL queries cursor = connection.cursor() # Example query: Select all rows from a table cursor.execute("SELECT * FROM your_table") # Print the fetched rows for row in cursor.fetchall(): print(row) finally: # Close the cursor and connection cursor.close() connection.close()

pymongo

pymongo allows Python applications to interact with MongoDB databases, making it easy to perform various database operations such as inserting, updating, deleting, and querying documents.

  • Full access to all functions and features.

    Example:

    from pymongo import MongoClient # Connect to MongoDB server client = MongoClient('mongodb://localhost:27017/') # Access a specific database db = client['my_database'] # Access a specific collection within the database collection = db['my_collection'] # Insert a document into the collection document = {'name': 'John', 'age': 30, 'city': 'New York'} collection.insert_one(document) # Query documents from the collection query = {'city': 'New York'} result = collection.find(query) # Print the documents returned by the query for doc in result: print(doc) # Close the connection to MongoDB client.close()

bs4 (BeautifulSoup)

bs4 make it easy to parse and interact with HTML and XML documents for web scraping or data extraction.

Example:

from bs4 import BeautifulSoup import requests # Fetch the content of a webpage response = requests.get("https://example.com") # Parse the HTML content soup = BeautifulSoup(response.content, "html.parser") # Extract and print the page title print(soup.title.string)

faiss-cpu

faiss-cpu allow you to efficiently perform nearest neighbor search on high-dimensional dense vectors. It is used in machine learning for clustering and similarity search.

Example:

import faiss import numpy as np # Create a dataset of 128-dimensional vectors data = np.random.random((100, 128)).astype('float32') # Create an index using L2 (Euclidean) distance index = faiss.IndexFlatL2(128) # Add vectors to the index index.add(data) # Perform a search to find the 5 nearest neighbors query = np.random.random((1, 128)).astype('float32') distances, indices = index.search(query, k=5) print(indices)

fetchai-babble

fetchai-babble allows you to interact with the Fetch.ai messaging service (called Memorandum). Further reference here.

Example:

from babble import Client, Identity # create a set of agents with random identities client1 = Client('agent1.....', Identity.generate()) client2 = Client('agent1.....', Identity.generate()) # send a message from one client to another client1.send(client2.delegate_address, "why hello there") # receive the messages from the other client for msg in client2.receive(): print(msg.text)

google-generativeai

google-generativeai allows you to build with the Gemini API. The Gemini API gives you access to Gemini models created by Google DeepMind. Gemini models are built from the ground up to be multimodal, so you can reason seamlessly across text, images, and code. Further reference here.

Example:

import google.generativeai as genai import os genai.configure(api_key=os.environ["GEMINI_API_KEY"]) model = genai.GenerativeModel('gemini-1.5-flash') response = model.generate_content("The opposite of hot is") print(response.text)

langchain-anthropic

langchain-anthropic contains the LangChain integration for Anthropic’s generative models. Further reference here.

Example:

from langchain_anthropic import ChatAnthropic from langchain_core.messages import AIMessage, HumanMessage model = ChatAnthropic(model="claude-3-opus-20240229", temperature=0, max_tokens=1024) message = HumanMessage(content="What is the capital of France?") response = model.invoke([message])

langchain-community

langchain-community contains third-party integrations that implement the base interfaces defined in LangChain Core, making them ready-to-use in any LangChain application. It is automatically installed by langchain, but can also be used separately. Further reference here.

Example:

import bs4 from langchain_community.document_loaders import WebBaseLoader # Only keep post title, headers, and content from the full HTML. bs4_strainer = bs4.SoupStrainer(class_=("post-title", "post-header", "post-content")) loader = WebBaseLoader( web_paths=("https://lilianweng.github.io/posts/2023-06-23-agent/",), bs_kwargs={"parse_only": bs4_strainer}, ) docs = loader.load() len(docs[0].page_content)

langchain-core

langchain-core contains the base abstractions that power the rest of the LangChain ecosystem. Further reference here.

Example:

from langchain_core.messages import HumanMessage from langchain_google_genai import ChatGoogleGenerativeAI llm = ChatGoogleGenerativeAI(model="gemini-pro-vision") # example message = HumanMessage( content=[ { "type": "text", "text": "What's in this image?", }, # You can optionally provide text parts {"type": "image_url", "image_url": "https://picsum.photos/seed/picsum/200/300"}, ] ) llm.invoke([message])

langchain-google-genai

langchain-google-genai contains the LangChain integrations for Gemini through their generative-ai SDK. Further reference here.

Example:

from langchain_core.messages import HumanMessage from langchain_google_genai import ChatGoogleGenerativeAI llm = ChatGoogleGenerativeAI(model="gemini-pro-vision") # example message = HumanMessage( content=[ { "type": "text", "text": "What's in this image?", }, # You can optionally provide text parts {"type": "image_url", "image_url": "https://picsum.photos/seed/picsum/200/300"}, ] ) llm.invoke([message])

langchain-google-vertexai

langchain-google-vertexai contains the LangChain integrations for Google Cloud generative models. Further reference here.

Example:

from langchain_core.messages import HumanMessage from langchain_google_vertexai import ChatVertexAI llm = ChatVertexAI(model_name="gemini-pro-vision") # example message = HumanMessage( content=[ { "type": "text", "text": "What's in this image?", }, # You can optionally provide text parts {"type": "image_url", "image_url": {"url": "https://picsum.photos/seed/picsum/200/300"}}, ] ) llm.invoke([message])

langchain-openai

langchain-openai contains the LangChain integrations for OpenAI through their openai SDK. Further reference here.

Example:

from langchain_openai import ChatOpenAI llm = ChatOpenAI( model="gpt-4o", temperature=0, max_tokens=None, timeout=None, max_retries=2, # api_key="...", # if you prefer to pass api key in directly instaed of using env vars # base_url="...", # organization="...", # other params... )

langchain-text-splitters

langchain-text-splitters contains utilities for splitting into chunks a wide variety of text documents. Further reference here.

Example:

from langchain_text_splitters import RecursiveCharacterTextSplitter text_splitter = RecursiveCharacterTextSplitter( chunk_size=1000, chunk_overlap=200, add_start_index=True ) all_splits = text_splitter.split_documents(docs) len(all_splits)

langchain

langchain assists in the development of applications integrating with LLMs. Further reference here.

Example:

import bs4 from langchain import hub from langchain_chroma import Chroma from langchain_community.document_loaders import WebBaseLoader from langchain_core.output_parsers import StrOutputParser from langchain_core.runnables import RunnablePassthrough from langchain_openai import OpenAIEmbeddings from langchain_text_splitters import RecursiveCharacterTextSplitter # Load, chunk and index the contents of the blog. loader = WebBaseLoader( web_paths=("https://lilianweng.github.io/posts/2023-06-23-agent/",), bs_kwargs=dict( parse_only=bs4.SoupStrainer( class_=("post-content", "post-title", "post-header") ) ), ) docs = loader.load() text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200) splits = text_splitter.split_documents(docs) vectorstore = Chroma.from_documents(documents=splits, embedding=OpenAIEmbeddings()) # Retrieve and generate using the relevant snippets of the blog. retriever = vectorstore.as_retriever() prompt = hub.pull("rlm/rag-prompt") def format_docs(docs): return "\n\n".join(doc.page_content for doc in docs) rag_chain = ( {"context": retriever | format_docs, "question": RunnablePassthrough()} | prompt | llm | StrOutputParser() ) rag_chain.invoke("What is Task Decomposition?")

nltk

nltk is a package for natural language processing.

Example:

import nltk nltk.download('punkt') from nltk.tokenize import word_tokenize text = "This is an example sentence, showing off the tokenization process." tokens = word_tokenize(text) print(tokens) # ['This', 'is', 'an', 'example', 'sentence', ',', 'showing', 'off', 'the', 'tokenization', 'process', '.']

openai

openai provides easy access to the OpenAI REST API. The library includes type definitions for all request params and response fields, and offers both synchronous and asynchronous clients powered by httpx.

Example:

import os from openai import OpenAI client = OpenAI( # This is the default and can be omitted api_key=os.environ.get("OPENAI_API_KEY"), ) chat_completion = client.chat.completions.create( messages=[ { "role": "user", "content": "Say this is a test", } ], model="gpt-3.5-turbo", )

tenacity

tenacity is a general-purpose retrying library to simplify the task of adding retry behavior to just about anything.

Example:

import random from tenacity import retry @retry def do_something_unreliable(): if random.randint(0, 10) > 1: raise IOError("Broken sauce, everything is hosed!!!111one") else: return "Awesome sauce!" print(do_something_unreliable())

unstructured

unstructured is a library for processing and extracting data from unstructured file formats such as PDFs, Word documents, and more.

Example:

from unstructured.partition.auto import partition elements = partition(filename="example-docs/fake-email.eml") print("\n\n".join([str(el) for el in elements]))

validators

validators is a Python library designed for data validation. It provides simple functions to verify the validity of various types of data. Further reference here.

Example:

import validators print(validators.email('[email protected]')) # True print(validators.email('invalid-email')) # ValidationFailure

web3

web3 is a Python library for interacting with the Ethereum blockchain. It provides functionalities for sending transactions, interacting with smart contracts, and querying blockchain data. Further reference here.

Example:

from web3 import Web3 w3 = Web3(Web3.HTTPProvider("https://mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID")) print(w3.is_connected()) # True if connected to Ethereum network
Last updated on