### Install AVCTL CLI on macOS/Linux and Windows Source: https://docs.agentverse.ai/docs/avctl/avctl Instructions for installing the AVCTL Command Line Interface tool on different operating systems. Ensure that Go is installed on your system as a prerequisite. ```Shell # For Mac/Linux users brew tap fetchai/avctl brew install avctl ``` ```Shell # For Windows user (Using Chocolatey) choco install avctl ``` -------------------------------- ### Local Agent Log Output Source: https://docs.agentverse.ai/docs/uAgents/mailbox This snippet shows the log output from a locally running agent, detailing its address, inspector URL, server startup, mailbox client initialization, and successful registration with the Almanac API. It also includes examples of receiving messages from other agents. ```Log Your agent's address is: agent1qfa53drat8rzau90u4494gx5mhj3v87tm4t5cuzkd7gkegxcm5vx5pku7kf INFO: [alice]: Starting agent with address: agent1qfa53drat8rzau90u4494gx5mhj3v87tm4t5cuzkd7gkegxcm5vx5pku7kf INFO: [alice]: Agent inspector available at https://agentverse.ai/inspect/?uri=http%3A//127.0.0.1%3A8000&address=agent1g43cfmrqk5fcyhzvyw6s24tu0acnly3y7mntmnqdvf9zdm23p74xvmh7xm INFO: [alice]: Starting server on http://0.0.0.0:8000 (Press CTRL+C to quit) INFO: [alice]: Starting mailbox client for https://agentverse.ai INFO: [alice]: Registration on Almanac API successful INFO: [alice]: Registering on almanac contract... INFO: [alice]: Registering on almanac contract...complete INFO: [alice]: Mailbox access token acquired INFO: [alice]: Received message from agent1qvzc3svtjv6dt9pql8ec7sfeuwfjmdg6ptafs9zc55ppvdwl5fe82j5m70v: hello there alice INFO: [alice]: Received message from agent1qvzc3svtjv6dt9pql8ec7sfeuwfjmdg6ptafs9zc55ppvdwl5fe82j5m70v: hello there alice INFO: [alice]: Received message from agent1qvzc3svtjv6dt9pql8ec7sfeuwfjmdg6ptafs9zc55ppvdwl5fe82j5m70v: hello there alice INFO: [alice]: Received message from agent1qvzc3svtjv6dt9pql8ec7sfeuwfjmdg6ptafs9zc55ppvdwl5fe82j5m70v: hello there alice ``` -------------------------------- ### Perform HTTP GET Request with Python Requests Library Source: https://docs.agentverse.ai/docs/allowed-imports This example illustrates how to use the `requests` library to make an HTTP GET request to a specified URL. It includes error handling for common HTTP status codes (200 and 404) and demonstrates how to access response headers. ```Python 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) ``` -------------------------------- ### Authenticate with Agentverse CLI Source: https://docs.agentverse.ai/docs/avctl/avctl-ci-github Logs into the Agentverse platform using the `avctl` command-line interface. This command establishes an authenticated session required for subsequent operations like deploying agents. ```bash avctl auth login ``` -------------------------------- ### Set Execute Permissions for Deployment Script Source: https://docs.agentverse.ai/docs/avctl/avctl-ci-github Grants execute permissions to the `deploy-agent.sh` script, which is necessary for running it. This step typically only needs to be performed once after cloning the repository. ```bash chmod +x scripts/deploy-agent.sh ``` -------------------------------- ### Example Mailroom API Agent Object Source: https://docs.agentverse.ai/docs/api/objects A sample JSON representation of an Agent object as it would appear in the Mailroom API, illustrating typical values for its properties. ```json { "name": "Example Name", "address": "agent1qtw0hy4kj65fv6j7qyv5mgdecq7c4qyqfqnjgc25wz4vf5h47l9l6m7qqtg", "Pending_messages": 1, "Bytes_transferred": 1, "Previous_Bytes_transferred": 1 } ``` -------------------------------- ### Run Agent Locally with avctl hosting run Source: https://docs.agentverse.ai/docs/avctl/avctl-hosting Starts a deployed agent locally. An optional `-l` flag enables real-time log streaming. If no agent address is provided, it runs the most recently pulled agent. ```APIDOC avctl hosting run [-l] [-a ] ``` ```Shell abc@xyz-MacBook-Pro myagents % avctl hosting run -l Agent is now running! TIMESTAMP LOG ENTRY 2024-01-23T16:08:31.468000 [INFO]: Successfully published protocol manifest: CurrencyConvertor v0.1.0 2024-01-23T16:10:51.459000 [INFO]: Received message from , session: ``` -------------------------------- ### Initialize uAgents Agent with Proxy for Agentverse Connection Source: https://docs.agentverse.ai/docs/uAgents/proxy This Python code demonstrates how to initialize a `uagents` Agent with proxy capabilities, allowing it to connect to the Agentverse as an intermediary. It sets up a basic agent named 'alice' with a specified seed and enables the proxy feature, then prints the agent's address. ```Python from uagents import Agent, Context, Model class Message(Model): message: str # Now your agent is ready to join the agentverse! agent = Agent( name="alice", seed="your_agent_seed_phrase", proxy=True, ) # Copy the address shown below print(f"Your agent's address is: {agent.address}") if __name__ == "__main__": agent.run() ``` -------------------------------- ### Manage Agent Lifecycle: Start and Stop Agents Source: https://docs.agentverse.ai/docs/api/hosting API endpoints for starting and stopping agents by their unique address. These operations allow control over an agent's running state, transitioning it between active and inactive states. ```Curl curl -X POST \ -H "Authorization: bearer " -H "Content-Type: application/json" \ "https://agentverse.ai/v1/hosting/agents/{address}/start" ``` ```Curl curl -X POST \ -H "Authorization: bearer " -H "Content-Type: application/json" \ "https://agentverse.ai/v1/hosting/agents/{address}/stop" ``` ```APIDOC POST /v1/hosting/agents/{address}/start - Description: Starts an Agent identified by its address. - Parameters: - address: string (path, required) - The unique address of the agent. - Responses: - HTTP 200: Array of JSON objects with agent properties. Example: [ { "name": "InitialTest", "address": "agent1qvnppqyhk4hu0q64tnfkspux8hpd9zayyclhafvkz5340uqx3ax02txfll7", "domain": "None", "running": "True", "compiled": "False", "revision": "4", "code_digest": "66089877730d0501a4ff1efedf545279d5db120d0960f1ea6a1c00f834ff9530", "wallet_address": "None" } ] POST /v1/hosting/agents/{address}/stop - Description: Stops a specific Agent identified by address. - Parameters: - address: string (path, required) - The address of the agent. This is also the current public key of the agent. - Responses: - HTTP 200: Array of JSON objects with agent properties. Example: [ { "name": "InitialTest", "address": "agent1qvnppqyhk4hu0q64tnfkspux8hpd9zayyclhafvkz5340uqx3ax02txfll7", "domain": "None", "running": "False", "compiled": "False", "revision": "4", "code_digest": "66089877730d0501a4ff1efedf545279d5db120d0960f1ea6a1c00f834ff9530", "wallet_address": "None" } ] ``` -------------------------------- ### Deploy Agent to Agentverse Source: https://docs.agentverse.ai/docs/avctl/avctl-ci-github Executes the `deploy-agent.sh` script to deploy or update an agent on the Agentverse platform. This script handles pushing the latest code and managing the agent's running state. ```bash ./scripts/deploy-agent.sh ``` -------------------------------- ### Implement a Basic ASI:One Compatible Chat Agent in Python Source: https://docs.agentverse.ai/docs/uAgents/asimini-agent This Python code snippet provides a foundational example for building a simple chat agent designed to be compatible with ASI:One. It leverages the `uagents` library for agent functionality and the `openai` library for LLM interactions, demonstrating how to set up a basic chat protocol for communication within the Agentverse environment. ```python from datetime import datetime from uuid import uuid4 from openai import OpenAI from uagents import Context, Protocol, Agent from uagents_core.contrib.protocols.chat import ( ChatAcknowledgement, ChatMessage, EndSessionContent, TextContent, chat_protocol_spec, ) ### Example Expert Assistant ## This chat example is a barebones example of how you can create a simple chat agent ``` -------------------------------- ### Agentverse Agent Log Output Source: https://docs.agentverse.ai/docs/uAgents/mailbox This snippet displays the typical log output from an Agentverse Agent, showing its lifecycle from starting up, registering with the Almanac API, sending envelopes, and messaging other agents. It includes debug and info level messages with timestamps. ```Log 2024-12-18 16:41:52 Debug System Starting agent... 2024-12-18 16:41:53 Info Agent Creating wrapper for preloaded 'agent' instance (Ignoring kwargs={'name': 'bob', 'seed': 'put_your_seed_phrase_here', 'endpoint': 'http://127.0.0.1:8001/submit'}) 2024-12-18 16:41:54 Debug System Registered to Almanac api fast track 2024-12-18 16:41:55 Debug System Successfully started agent 2024-12-18 16:41:56 Info System Interval 0 period set to 5 2024-12-18 16:41:57 Debug System Registered to Almanac api fast track 2024-12-18 16:41:58 Debug System Successfully registered agent on Almanac contract 2024-12-18 16:41:59 Debug System Envelope sent to agent1qfa53drat8rzau90u4494gx5mhj3v87tm4t5cuzkd7gkegxcm5vx5pku7kf 2024-12-18 16:42:00 Info Agent Sending message to alice 2024-12-18 16:42:01 Debug System Envelope sent to agent1qfa53drat8rzau90u4494gx5mhj3v87tm4t5cuzkd7gkegxcm5vx5pku7kf 2024-12-18 16:42:02 Info Agent Sending message to alice 2024-12-18 16:42:03 Debug System Envelope sent to agent1qfa53drat8rzau90u4494gx5mhj3v87tm4t5cuzkd7gkegxcm5vx5pku7kf ``` -------------------------------- ### Connect and Query MySQL Databases with MySQLdb Source: https://docs.agentverse.ai/docs/allowed-imports This example shows how to establish a connection to a MySQL database using the MySQLdb library in Python. It demonstrates creating a cursor, executing a SELECT query, fetching results, and properly closing the connection. This is fundamental for interacting with relational databases from Python applications. ```python 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() ``` -------------------------------- ### Setting up a Local uAgents Agent (Alice) Source: https://docs.agentverse.ai/docs/uAgents/mailbox This Python snippet demonstrates how to create a local uAgents agent named 'alice'. It defines a `Message` model for inter-agent communication and sets up an asynchronous message handler using `@agent.on_message`. The agent is configured with a seed phrase and Mailbox support, allowing it to connect to the Agentverse for persistent message handling. ```python from uagents import Agent, Context, Model class Message(Model): message: str # First generate a secure seed phrase (e.g. https://pypi.org/project/mnemonic/) SEED_PHRASE = "put_your_seed_phrase_here" # Now your agent is ready to join the agentverse! agent = Agent( name="alice", seed=SEED_PHRASE, mailbox=True ) # Copy the address shown below print(f"Your agent's address is: {agent.address}") @agent.on_message(model=Message, replies={Message}) async def handle_message(ctx: Context, sender: str, msg: Message): ctx.logger.info(f"Received message from {sender}: {msg.message}") if __name__ == "__main__": agent.run() ``` -------------------------------- ### Retrieve Agent Information with avctl hosting get Source: https://docs.agentverse.ai/docs/avctl/avctl-hosting Retrieves details about deployed agents. `avctl hosting get agents` lists all agents associated with the user, providing their names, addresses, compilation status, and other metadata. `avctl hosting get agent` displays information for a specific deployed agent using its address. ```APIDOC avctl hosting get agents - Returns a list of all agents for the user. - Output fields: NAME, ADDRESS, COMPILED, DOMAIN, REVISION, RUNNING, WALLET ADDRESS avctl hosting get agent -a '' - Prints details for a selected deployed agent. - Parameters: - -a, --agent: The address of the agent to retrieve. ``` ```Shell abc@xyz-MacBook-Pro myagents % avctl hosting get agents NAME ADDRESS COMPILED DOMAIN REVISION RUNNING WALLET ADDRESS name true/false 5 true/false ``` ```Shell abc@xyz-MacBook-Pro myagents % avctl hosting get agent -a '' ``` -------------------------------- ### Sample Almanac API Agent Object Source: https://docs.agentverse.ai/docs/api/objects A sample JSON representation of an Agent object as it would appear in the Almanac API, providing an example of its structure and data types. ```json { "status": "Active", "address": "agent1qwckmey38jd6xl6al9k5qcelr9faqfgpxh73tev6fa3ruqnzajp6yneg3qw", "endpoints": [{"url": "https://agentverse.ai/v1/hosting/submit", "weight": 1}], "protocol": "a98290009c0891bc431c5159357074527d10eff6b2e86a61fcf7721b472f1125", "expiry": "2023-08-26T03:30:05.568195+00:00" } ``` -------------------------------- ### Connect to Ethereum Network and Check Connection with Web3.py Source: https://docs.agentverse.ai/docs/allowed-imports This example demonstrates how to establish a connection to the Ethereum blockchain using the `web3.py` library. It initializes a `Web3` instance with an HTTP provider (e.g., Infura) and then checks if the connection to the network is successful. This is the initial step for any interaction with the Ethereum blockchain, such as sending transactions or querying contract data. ```Python 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 ``` -------------------------------- ### Setting up an Agentverse Hosted uAgents Agent (Bob) Source: https://docs.agentverse.ai/docs/uAgents/mailbox This Python snippet illustrates how to create an Agentverse-hosted uAgents agent named 'bob'. It defines the same `Message` model and includes an `@agent.on_interval` decorator to periodically send messages to 'alice'. An `@agent.on_message` handler is also included to process incoming messages. This agent requires Alice's address and its own seed phrase. ```python from uagents import Agent, Context, Model class Message(Model): message: str # Copy ALICE_ADDRESS generated in mailbox_agent.py ALICE_ADDRESS = "agent1qfa53drat8rzau90u4494gx5mhj3v87tm4t5cuzkd7gkegxcm5vx5pku7kf" # Generate a second seed phrase (e.g. https://pypi.org/project/mnemonic/) SEED_PHRASE = "put_your_seed_phrase_here" # Now let's create the Agentverse agent agent = Agent( name="bob", seed=SEED_PHRASE, endpoint="http://127.0.0.1:8001/submit", ) @agent.on_interval(period=2.0) async def send_message(ctx: Context): ctx.logger.info("Sending message to alice") await ctx.send(ALICE_ADDRESS, Message(message="hello there alice")) @agent.on_message(model=Message, replies=set()) async def on_message(ctx: Context, sender: str, msg: Message): ctx.logger.info(f"Received message from {sender}: {msg.message}") if __name__ == "__main__": agent.run() ``` -------------------------------- ### Pushing Agent Changes to GitHub Repository Source: https://docs.agentverse.ai/docs/avctl/avctl-ci-github These standard Git commands are used to stage, commit, and push local changes to the remote GitHub repository. This action typically triggers the CI/CD workflow for agent deployment configured in GitHub Actions, initiating the automated build and deployment process. ```Git git add . git commit -m "updating agent" git push ``` -------------------------------- ### Successful Response for Agent Search Source: https://docs.agentverse.ai/docs/api/search Example JSON response body for a successful search query to the Agentverse AI platform, showing the structure of an array of AgentSearch objects. ```JSON [ { "address": "agent1qfuexnwkscrhfhx7tdchlz486mtzsl53grlnr3zpntxsyu6zhp2ckpemfdz", "name": "OpenAI Translator Agent", "readme": "# OpenAI Translator Agent\n\n![domain:integration]...", "status": "active", "total_interactions": 10848, "recent_interactions": 10838, "rating": null, "type": "hosted", "category": "fetch-ai", "featured": true, "geo_location": null, "last_updated": "2025-01-06T12:46:03Z", "created_at": "2024-10-03T14:40:39Z" } ] ``` -------------------------------- ### Search Agents using Curl Source: https://docs.agentverse.ai/docs/api/search Example Curl command to perform a general search for agents on the Agentverse AI platform, including filters, sorting, and pagination parameters. ```Curl curl -X POST \ -H "Authorization: bearer " -H "Content-Type: application/json" \ "https://agentverse.ai/v1/search/agents" \ -d '{ "filters": { "state": [], "category": [], "agent_type": [], "protocol_digest": [] }, "sort": "relevancy", "direction": "asc", "search_text": "", "offset": 0, "limit": 30, "search_id": "", "source": "" }' ``` -------------------------------- ### Agentverse Hosting API Endpoints and Operations Source: https://docs.agentverse.ai/docs/api/hosting Comprehensive documentation for managing agents on Agentverse, including listing, creating, retrieving, updating code, starting, stopping, and monitoring agent usage. This section details the request and response formats for key API interactions. ```APIDOC # Endpoints Overview GET /v1/hosting/agents POST /v1/hosting/agents GET /v1/hosting/agents/:agentAddress DELETE /v1/hosting/agents/:agentAddress GET /v1/hosting/agents/:agentAddress/code PUT /v1/hosting/agents/:agentAddress/code POST /v1/hosting/agents/:agentAddress/start POST /v1/hosting/agents/:agentAddress/stop GET /v1/hosting/agents/:agentAddress/logs/latest DELETE /v1/hosting/agents/:agentAddress/logs GET /v1/hosting/usage/current GET /v1/hosting/usage/:year/:month GET /v1/hosting/usage/agents/:address/current GET /v1/hosting/usage/agents/:address/:year/:month # Getting a list of your Agents GET /v1/hosting/agents - Request: Request a list of all your Agents. - Responses: An array of your Agents, each represented as an Agent Object. - Curl Example: curl -X GET \ -H "Authorization: bearer " -H "Content-Type: application/json" \ "https://agentverse.ai/v1/hosting/agents" - HTTP 200 Response Example: [ { "name": "My first agent", "address": "agent1q2dfhywtt8xazrdyzgap6gzdd7uhk4e0wmc3gjqt42esauaegcm8cuvclpj", "running": false, "compiled": true, "revision": 7, "code_digest": "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef", "wallet_address": "fetch1dtwgzm6km4394erexa8ka05wva306wt9cc3mwk" } ] # Creating a new Agent POST /v1/hosting/agents - Request: Request for creating a new Agent. - Parameters: - name: - Type: string - Required: required - Description: The given name of the agent. This is only a label that is used internally so users can keep track of their agents. - Responses: An array containing the properties of a newly created Agent represented as an Agent Object. - Curl Example: curl -X POST \ -H "Authorization: bearer " -H "Content-Type: application/json" \ "https://agentverse.ai/v1/hosting/agents" \ -d '{ "name": "My newest agent" }' - HTTP 200 Response Example: { "name": "My newest agent", "address": "agent1q2dfhywtt8xazrdyzgap6gzdd7uhk4e0wmc3gjqt42esauaegcm8cuvclpj", "running": false, "compiled": true, "revision": 1, "code_digest": "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef", "wallet_address": "fetch1dtwgzm6km4394erexa8ka05wva306wt9cc3mwk" } # Look up specific Agent GET /v1/hosting/agents/{agentAddress} - Description: Retrieve details for a specific agent by its address. ``` -------------------------------- ### Retrieve Agent Code using Curl Source: https://docs.agentverse.ai/docs/api/hosting Example `curl` command to fetch the code details for a specific agent from the Agentverse AI hosting platform. This operation requires an authorization token and the agent's address. ```Curl curl -X GET \ -H "Authorization: bearer " -H "Content-Type: application/json" \ "https://agentverse.ai/v1/hosting/agents/{agentAddress}/code" ``` -------------------------------- ### Integrate Google Cloud Generative Models with LangChain VertexAI Source: https://docs.agentverse.ai/docs/allowed-imports This example shows how to use `langchain-google-vertexai` to interact with Google Cloud's generative models. It constructs a multimodal `HumanMessage` with text and an image URL, then invokes a `ChatVertexAI` model for image analysis. ```python 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]) ``` -------------------------------- ### Automated Agent Deployment Script for Agentverse AI Source: https://docs.agentverse.ai/docs/avctl/avctl-ci-github This comprehensive shell script automates the deployment of an Agentverse AI agent. It defines a function `get_agent_address` to extract an existing agent's address from `.avctl/config.toml`. The script then changes to the agent's directory, initializes `avctl` hosting, retrieves the agent's name, and conditionally stops/syncs an existing agent or deploys a new one using `avctl` CLI commands based on its registration status. ```Shell # Define the function get_agent_address() { local file=".avctl/config.toml " # Check if the file exists if [ -f "$file" ]; then # Extract the address value agent_address=$(grep 'address =' "$file" | sed -E 's/.*= "(.*)"/\1/') # Check if the address is not empty if [ -n "$agent_address" ]; then echo $agent_address else echo "" fi else echo "" fi } # Define the specific directory to work on defined_directory="agent/" # Change to the specified agent directory cd "$defined_directory" # Create a .staging.avctl folder for new agents if it doesn't exist avctl hosting init # get the agent address if it exists agent_address=$(get_agent_address) # Get the agent's name from the README.md top line header agent_name=$(head -n 1 README.md | sed -e 's/#//g' | xargs) # If the address exists... if [ -n "$agent_address" ]; then avctl hosting get agent -a "$agent_address" response=$(avctl hosting get agent -a "$agent_address")\ # Check if the agent is already in existence, if it isn't, deploy as new, else sync. if [ $? -eq 0 ]; then avctl hosting stop -a "$agent_address" avctl hosting sync -a "$agent_address" else avctl hosting deploy -n "$agent_name" --no-dependency-check || true fi # Agent doesn't exist, so let's deploy else avctl hosting deploy -n "$agent_name" --no-dependency-check || true fi ``` -------------------------------- ### Retrieve Agent Details using Curl Source: https://docs.agentverse.ai/docs/api/hosting Example `curl` command to fetch the details of a specific agent from the Agentverse AI hosting platform using its address. This operation requires an authorization token. ```Curl curl -X GET \ -H "Authorization: bearer " -H "Content-Type: application/json" \ "https://agentverse.ai/v1/hosting/agents/{agentAddress}" ``` -------------------------------- ### Curl Example: Search Agents by Name Source: https://docs.agentverse.ai/docs/api/almanac This Curl command illustrates how to perform a POST request to the Almanac API's `/v1/almanac/search` endpoint. It demonstrates searching for agents by providing a 'text' parameter in the JSON request body, requiring authentication with a bearer token. ```Curl curl -X POST \ -H "Authorization: bearer " -H "Content-Type: application/json" \ "https://agentverse.ai/v1/almanac/search" \ -d '{ "text": "TestingAgent" }' ``` -------------------------------- ### Send Multimodal Messages with LangChain Core and Google Generative AI Source: https://docs.agentverse.ai/docs/allowed-imports This example illustrates how to construct a multimodal `HumanMessage` using `langchain-core` and invoke a Google Generative AI model (`gemini-pro-vision`) with both text and image URL content. It showcases the core message abstraction for multimodal interactions. ```python 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]) ``` -------------------------------- ### Integrate Anthropic Chat Models with LangChain Source: https://docs.agentverse.ai/docs/allowed-imports This example shows how to use `langchain-anthropic` to interact with Anthropic’s generative models, specifically 'claude-3-opus-20240229'. It initializes a `ChatAnthropic` model and invokes it with a human message. ```python 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]) ``` -------------------------------- ### Build Retrieval Augmented Generation (RAG) Chain with LangChain Source: https://docs.agentverse.ai/docs/allowed-imports This example illustrates building a RAG chain using LangChain to retrieve relevant information from a web page and generate responses with an LLM. It involves loading documents, splitting them, creating a vector store with embeddings, and then setting up a runnable chain for question answering. This pattern is fundamental for grounding LLM responses in specific knowledge bases. ```Python 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?") ``` -------------------------------- ### Send and Receive Messages with Fetch.ai Babble Source: https://docs.agentverse.ai/docs/allowed-imports This example demonstrates how to use fetchai-babble to interact with the Fetch.ai messaging service (Memorandum). It shows how to create two Client instances with random identities, send a message from one client to another, and then receive and print the message from the recipient. This facilitates inter-agent communication within the Fetch.ai ecosystem. ```python 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) ``` -------------------------------- ### Interact with Cosmos-based Blockchains using CosmPy Source: https://docs.agentverse.ai/docs/allowed-imports This example demonstrates how to use CosmPy to interact with Cosmos-based blockchains, specifically Fetch.ai's stable testnet. It shows how to configure the network, query an agent's balance, and use a faucet to provide tokens if the balance falls below a minimum threshold. This is useful for managing agent finances on-chain. ```python 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) ``` -------------------------------- ### Manage AVCTL CLI Authentication Commands Source: https://docs.agentverse.ai/docs/avctl/avctl Details the `avctl auth` commands used for managing user authentication with the Agentverse CLI, including login, logout, and status checks. This section provides the command signatures and a practical usage example. ```APIDOC avctl auth login - Log in to the CLI. avctl auth logout - Log the current user out from the CLI. avctl auth status - Print out the current status of the authorization. ``` ```Shell abc@zyx-Pro myagent % avctl auth login abc@xyz-Pro myagent % avctl auth status Status: logged-in abc@xyz-Pro myagent % avctl auth logout abc@xyz-Pro myagent % avctl auth status Status: logged-out ``` -------------------------------- ### Granting Execute Permissions to Deployment Script Source: https://docs.agentverse.ai/docs/avctl/avctl-ci-github This shell command, typically executed locally, updates the executable permission for the `deploy-agent.sh` script within the Git repository's index. It ensures the script has the necessary permissions to run on the CI/CD runner, resolving potential execution errors during automated deployments. ```Shell sudo git update-index --chmod=+x scripts/deploy-agent.sh ``` -------------------------------- ### Parse HTML and Extract Data with BeautifulSoup Source: https://docs.agentverse.ai/docs/allowed-imports This example illustrates web scraping using BeautifulSoup (bs4) and requests. It fetches the HTML content of a webpage, parses it, and then extracts and prints the page title. This is a common pattern for parsing and navigating HTML/XML documents for data extraction. ```python 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) ``` -------------------------------- ### API Key and Usage Management Endpoints Source: https://docs.agentverse.ai/docs/api/mailroom Comprehensive API documentation for managing API keys and retrieving their usage statistics. This includes operations to list all existing API keys, delete a specific API key by its UUID, and get detailed profile usage for a given API key. ```APIDOC GET /v1/api-keys - Description: List all existing API keys. - Parameters: None. - Responses: - HTTP 200: An array of JSON objects containing the details of existing API keys. Example: [ { "items": [ { "uuid": "uuid-example", "key": "API-key example", "name": "Test", "expires_at": "2023-11-26T06:09:05.511108+00:00" } ], "total": 1, "page": 1, "size": 50 } ] DELETE /v1/api-keys/{uuid} - Description: Delete an existing API key. - Parameters: - uuid (string, required): The unique identifier (UUID) of the API key that is to be deleted. - Responses: - HTTP 200: An empty JSON object if the deletion is successful. Example: {} GET /v1/api-keys/{uuid} (Get profile usage) - Description: Retrieve profile usage statistics for a specific API key. - Parameters: - uuid (string, required): The unique identifier (UUID) of the API key for which details are being requested. - Responses: - HTTP 200: An array of JSON objects containing information about the Agentverse profile usage. Example: [ { "bytes_transferred": 0, "bytes_transferred_limit": 200000000, "num_messages": 0, "num_messages_limit": 10000, "bytes_stored": 0, "bytes_stored_limit": 50000000, "num_agents": 1, "num_agents_limit": 4 } ] ``` ```curl curl -X GET \ -H "Authorization: bearer " -H "Content-Type: application/json" \ "https://agentverse.ai/v1/api-keys" ``` ```json [ { "items": [ { "uuid": "uuid-example", "key": "API-key example", "name": "Test", "expires_at": "2023-11-26T06:09:05.511108+00:00" } ], "total": 1, "page": 1, "size": 50 } ] ``` ```curl curl -X DELETE \ -H "Authorization: bearer " -H "Content-Type: application/json" \ "https://agentverse.ai/v1/api-keys/{uuid}" ``` ```json {} ``` ```curl curl -X GET \ -H "Authorization: bearer " -H "Content-Type: application/json" \ "https://agentverse.ai/v1/api-keys/{uuid}" ``` ```json [ { "bytes_transferred": 0, "bytes_transferred_limit": 200000000, "num_messages": 0, "num_messages_limit": 10000, "bytes_stored": 0, "bytes_stored_limit": 50000000, "num_agents": 1, "num_agents_limit": 4 } ] ``` -------------------------------- ### Manage Agent Secrets with avctl hosting secrets Source: https://docs.agentverse.ai/docs/avctl/avctl-hosting Provides commands to manage secrets associated with an agent. `add secrets` creates a new secret, `delete secrets` removes an existing one, and `get secrets` lists the names of all secrets for the agent. ```APIDOC avctl hosting add secrets - Adds a new secret for the agent. - Parameters: - secret_name: The name of the secret to add. The value will be prompted interactively. avctl hosting delete secrets - Deletes an existing secret from the agent. - Parameters: - secret_name: The name of the secret to delete. avctl hosting get secrets - Retrieves the names of all secrets associated with the agent. ``` ```Shell abc@xyz-MacBook-Pro myagents % avctl hosting secrets add secret Enter secret value for 'secret': Secret 'secret' added successfully to agent abc@xyz-MacBook-Pro myagents % avctl hosting secrets get Secrets for agent: * secret abc@xyz-MacBook-Pro myagents % avctl hosting secrets delete secret Secret 'secret' deleted successfully from agent abc@xyz-MacBook-Pro myagents % ``` -------------------------------- ### Define a uAgents Local Agent in Python Source: https://docs.agentverse.ai/docs/uAgents/inspector This Python snippet defines a simple local agent using the uAgents framework. It includes a 'Message' model, initializes an 'Agent' named 'Bob' with a specific port and endpoint, and sets up an asynchronous message handler to process incoming messages and send a reply. This demonstrates basic agent setup and communication. ```Python from uagents import Agent, Context, Model class Message(Model): message: str bob = Agent( name="Bob", port=8001, seed="BobSecretPhrase", endpoint=["http://127.0.0.1:8001/submit"] ) print(f"Your agent's address is: {bob.address}") @bob.on_message(model=Message) async def message_handler(ctx: Context, sender: str, msg: Message): ctx.logger.info(f'Received message from {sender}: {msg.message}') await ctx.send(sender, Message(message="Hello There!")) if __name__ == "__main__": bob.run() ``` -------------------------------- ### Example JSON Response for Top Search Terms API Source: https://docs.agentverse.ai/docs/api/search This JSON object represents a successful (HTTP 200) response from the Agentverse AI API for retrieving top search terms. It includes the agent's address and an array of 'term_percentages', each detailing a term and its percentage usage over different timeframes (last 24h, 7d, 30d). ```JSON { "address": "agent1qwnjmzwwdq9rjs30y3qw988htrvte6lk2xaak9xg4kz0fsdz0t9ws4mwsgs", "term_percentages": [ { "term": "agent", "last_24h_percentage": 26, "last_7d_percentage": 30, "last_30d_percentage": 52.1 }, { "term": "hello", "last_24h_percentage": 14.3, "last_7d_percentage": 12.2, "last_30d_percentage": 3.9 } ] } ``` -------------------------------- ### Curl Example: Get Recently Registered Agents Source: https://docs.agentverse.ai/docs/api/almanac This Curl command demonstrates how to make a GET request to the Almanac API's `/v1/almanac/recent` endpoint to retrieve a list of recently registered agents. Authentication is required using a bearer token in the Authorization header. ```Curl curl -X GET \ -H "Authorization: bearer " -H "Content-Type: application/json" \ "https://agentverse.ai/v1/almanac/recent" ``` -------------------------------- ### Initialize Agent Template with avctl hosting init Source: https://docs.agentverse.ai/docs/avctl/avctl-hosting Initializes a new agent project by creating template files and setting up a Git repository and Poetry environment. This command prepares the local directory for agent development. ```APIDOC avctl hosting init ``` ```Shell abc@xyz-MacBook-Pro myagents % avctl hosting init Template agent files created successfully! Initialized empty Git repository in the current directory Poetry setup created successfully ``` -------------------------------- ### Get Agent Interaction Counts using Curl Source: https://docs.agentverse.ai/docs/api/search Example Curl command to retrieve historical and all-time interaction counts for a specific agent using its unique address. ```Curl curl -X GET \ -H "Authorization: bearer " -H "Content-Type: application/json" \ "https://agentverse.ai/v1/search/agents/interactions/{address}" ``` -------------------------------- ### List Supported Packages by Agentverse with avctl hosting packages Source: https://docs.agentverse.ai/docs/avctl/avctl-hosting Displays a list of all programming language packages and their versions that are officially supported by the Agentverse platform for agent development. ```APIDOC avctl hosting packages ``` ```Shell abc@xyz-MacBook-Pro myagents % avctl hosting packages Supported Packages: - python: >=3.11,<3.12 - requests: ^2.28.2 - cosmpy: ^0.9.2 - uagents: ^0.15.2 - pydantic: ^1.10.5 - uagents-ai-engine: ^0.5.0 - mysqlclient: ^2.2.0 - pymongo: ^4.6.0 abc@xyz-MacBook-Pro myagents % ``` -------------------------------- ### Configure Agent with Local README Path in Python Source: https://docs.agentverse.ai/docs/readme This Python code snippet demonstrates how to initialize an `Agent` object, specifying a local `README.md` file path using the `readme_path` parameter. This configuration allows the Agentverse UI to display and enable editing of the README directly from the Agent's page once connected. ```Python agent = Agent( name="Alice", seed=SEED_PHRASE, port=8000, mailbox=True, readme_path="README.md", publish_agent_details=True ) ``` -------------------------------- ### Search Geolocation Agents using Curl Source: https://docs.agentverse.ai/docs/api/search Example Curl command to search for agents within a specified geographical area, including latitude, longitude, and radius filters. ```Curl curl -X POST \ -H "Authorization: bearer " -H "Content-Type: application/json" \ "https://agentverse.ai/v1/search/agents/geo" \ -d '{ "geo_filter": { "latitude": "", "longitude": "", "radius": "" }, "filters": { "state": [], "category": [], "agent_type": [], "protocol_digest": [] }, "sort": "relevancy", "direction": "asc", "search_text": "", "offset": 0, "limit": 30, "search_id": "", "source": "" }' ``` -------------------------------- ### Attach Protocol to Agent in Agentverse (Python) Source: https://docs.agentverse.ai/docs/uAgents/asimini-agent This snippet demonstrates how to include a protocol with an agent instance in the Agentverse framework. It publishes the agent's manifest, making it discoverable within the network. This is a foundational step for agent registration and interaction. ```Python agent.include(protocol, publish_manifest=True) ``` -------------------------------- ### ASI-1 (OpenAI Compatible) Chat Completions API Source: https://docs.agentverse.ai/docs/uAgents/asimini-agent Details the parameters and structure for making chat completion requests to the ASI-1 LLM via its OpenAI-compatible endpoint. This includes defining system and user messages, specifying the model, and controlling response length. ```APIDOC client.chat.completions.create( model: "string", messages: [ {"role": "string", "content": "string"}, ... ], max_tokens: "integer" ) - Description: Creates a chat completion for the given messages. - Parameters: - model (string): The ID of the model to use (e.g., "asi1-mini"). - messages (array of objects): A list of messages comprising the conversation so far. - role (string): The role of the author of this message (e.g., "system", "user", "assistant"). - content (string): The content of the message. - max_tokens (integer, optional): The maximum number of tokens to generate in the chat completion. - Returns: A ChatCompletion object. - choices[0].message.content (string): The generated text content. - Example Usage: r = client.chat.completions.create( model="asi1-mini", messages=[ {"role": "system", "content": "You are a helpful assistant..."}, {"role": "user", "content": "What is the sun?"}, ], max_tokens=2048, ) ``` -------------------------------- ### Delete Agent using Curl Source: https://docs.agentverse.ai/docs/api/hosting Example `curl` command to delete a specific agent from the Agentverse AI hosting platform. This operation requires an authorization token and the agent's address. ```Curl curl -X DELETE \ -H "Authorization: bearer " -H "Content-Type: application/json" \ "https://agentverse.ai/v1/hosting/agents/{agentAddress}" ``` -------------------------------- ### Successful Response for Agent Interaction Counts Source: https://docs.agentverse.ai/docs/api/search Example JSON response body for a successful request to retrieve agent interaction data, detailing interval, message, total counts, and all-time interactions. ```JSON { "address": "agent1q0kn4wmp4866c7kqnql8fnxflvjtx78zga5nr6qg3vvpvjwtlp3pc9umtlu", "interval": [ 0 ], "message": [ 0 ], "total": [ 0 ], "num_all_time_interactions": { "interval": 38379, "message": 0, "total": 38379 } } ``` -------------------------------- ### Successful Response for Geolocation Agent Search Source: https://docs.agentverse.ai/docs/api/search Example JSON response body for a successful geolocation search query, showing the structure of the search results including agents array and pagination details. ```JSON { "agents": [], "offset": 0, "limit": 30, "num_hits": 0, "total": 0, "search_id": "" } ```