- Explore our documentation, guides and examples to get to know Fetch.ai
- tools and products.
+ The place where you can find all tutorials and guides needed to familiarise with the concepts and code in a practical way to develop your ideas autonomously.
- Fetch.ai is developing a platform to help the development of an AI
- enabled decentralized digital economy. Agents are programs that can
- make choices on their own for individuals, companies, and devices.
- Agents are the actors, and the heart of Fetch.ai ecosystem.
-
-
-
- Agents are flexible problem solvers, capable of not just completing
- tasks but also tackling difficult issues across several domains.
- Agents have the adaptability to handle different activities inside the
- decentralized economy, whether it's improving supply chain
- logistics, maintaining solid record-keeping systems, executing
- computational tasks, or enabling buying and selling interactions.
-
-
- Fetch.ai places a high priority on accessibility. Agent technology is
- designed to be inclusive, allowing anybody to create an AI Agent.
- Agents are made possible with the Fetch.ai platform.
-
-
-
-
-
-
Courses
-
- Comprehensive guides for people new to programming and Fetch.ai.
-
-
-
- {courses.map((course, index) => (
-
- ))}
-
-
-
-
Browse by product
-
- Click on each product for additional details.
-
-
-
-
-
-
+
+
+
+
+
+
ASI: One
+
World's first
+ Web3-native LLM designed for Agentic AI.
+
+
+
+
+
+
+
+
+
+
Getting started with
+
+
FET token
+
+
+
+
+
+
+
Create your first
+
ASI-1 Agent
+
+
+
+
+
+
What is Fetch.ai
+
Breaking down the components and ecosystem of fetch.ai
+
+
+
+
+
+
+
+
AI Agents
+
Secure communication and a robust network to build excellent autonomous agents.
+
+
+
+
+
+
+
+
+
Getting started with
+
+
Agentverse
+
+
+
+
+
+
+
+
+
Getting started with
+
+
ASI:One
+
+
+
+
+
+
+
+
+
Getting started with
+
+
uAgents
+
+
+
+
+
+
+
+
+
+
uAgents
+
Python library for dyanmic Multiagent systems and AI Agents, made simple.
- );
-};
-
-const Section: React.FC = ({ heading, items }) => {
- useEffect(() => {
- // Check if there is a hash fragment in the URL
- if (window.location.hash) {
- // Get the ID of the section corresponding to the hash fragment
- const sectionId = window.location.hash.slice(1);
-
- // Find the section element by its ID
- // eslint-disable-next-line unicorn/prefer-query-selector
- const sectionElement = document.getElementById(sectionId);
-
- // Scroll to the section if it exists
- if (sectionElement) {
- sectionElement.scrollIntoView({ behavior: "smooth" });
- }
- }
- }, []); // This effect runs once when the component mounts
-
- const sectionId = heading.replaceAll(" ", "").toLowerCase();
- return (
-
-
{heading}
-
- {items.map((item, index) => (
-
- ))}
-
-
- );
-};
-
-const items: { [key: string]: Item[] } = {
- "AI Engine": [
- {
- title: "Introducing the AI Engine",
- description: (
- <>Introducing the AI Engine and its role in DeltaV functionalities.>
- ),
- icon: aiEngine,
- path: "/concepts/ai-engine/ai-engine-intro",
- },
- {
- title: "Powering connections and smart operations in DeltaV",
- description: (
- <>
- Explore the integration of AI Engine within DeltaV, enabling
- connections between users and agent-based Functions.
- >
- ),
- icon: synergyIcon,
- path: "/concepts/ai-engine/powering-connections-and-smart-operations-in-deltav",
- },
- {
- title: "DeltaV",
- description: (
- <>
- DeltaV operates as a search-based AI chat interface, employing natural
- language conversations to assist users in objective execution.
- >
- ),
- icon: whisperAgentIcon,
- path: "https://deltav.agentverse.ai/login",
- },
- {
- title: "Analytics",
- description: <>Coming soon.>,
- icon: analyticsIcon,
- path: "",
- },
- ],
- "Agentverse components": [
- {
- title: "Agentverse: My Agents",
- description: (
- <>
- The Agentverse My Agents section enables all users to get started
- quickly and to deploy agents to the cloud to start connecting and
- automating.
- >
- ),
- icon: hostingIcon,
- path: "/concepts/agent-services/agent-hosting",
- },
- {
- title: "Agentverse: Mailroom / IoT Gateway",
- description: (
- <>
- Set up mailboxes for your local agents so that your agent doesn't
- need to accessible all the time.
- >
- ),
- icon: mailBoxIcon,
- path: "/concepts/agent-services/agent-mail",
- },
- {
- title: "Agentverse Functions: register your Functions on the Agentverse!",
- description: (
- <>
- Create an agent encapsulating a Function and register it as an Agent
- Function on the Agentverse to be retrieved via DeltaV chat!
- >
- ),
- icon: agentFunction,
- path: "/guides/agentverse/registering-agent-services",
- },
- {
- title: "Agentverse APIs",
- description: <>Understand and use the Agentverse APIs.>,
- icon: apiAgentIcon,
- path: "/apis#agentverse-apis",
- },
- {
- title: "Agentverse: Marketplace",
- description: (
- <>
- Learn to use the Agentverse Marketplace to start an interaction with
- other registered agents.
- >
- ),
- icon: explorerIcon,
- path: "/concepts/agent-services/agent-explorer",
- },
- ],
- "Open Network": [
- {
- title: "Almanac",
- description: (
- <>
- Use the Almanac contract to query a particular agent's
- information.
- >
- ),
- icon: almanacIcon,
- path: "/references/contracts/uagents-almanac/almanac-overview",
- },
- {
- title: "CosmPy",
- description: <>Get started with CosmPy.>,
- icon: cosmpyIcon,
- path: "/guides/fetch-network/cosmpy/install",
- },
- {
- title: "Wallet",
- description: <>Get started with the ASI Alliance Wallet.>,
- icon: walletIcon,
- path: "/guides/fetch-network/asi-wallet/web-wallet/get-started",
- },
- {
- title: "Ledger",
- description: <>Get started with the Fetch Ledger.>,
- icon: ledgerIcon,
- path: "/concepts/fetch-network/ledger/intro",
- },
- ],
-};
-
-const IndexPage: React.FC = () => {
- return (
-
- Step into the world of Fetch.ai's API hub, where you can discover and master a
- diverse array of valuable APIs.
-
-
-import { Row } from "../components/mdx";
-import GuidesMdx from "../components/guide-mdx"
-import { AgentsIcon , AsiIcon, AgentverseIcon} from "src/icons/main-page-icons"
-
-
-
-
-
diff --git a/pages/apis/_meta.json b/pages/apis/_meta.json
deleted file mode 100644
index b77468d33..000000000
--- a/pages/apis/_meta.json
+++ /dev/null
@@ -1,5 +0,0 @@
-{
- "agentverse": "Agentverse",
- "ai-engine": "AI Engine",
- "asi-alliance-wallet": "ASI Alliance Wallet"
-}
diff --git a/pages/apis/agentverse/_meta.json b/pages/apis/agentverse/_meta.json
deleted file mode 100644
index 1528a9820..000000000
--- a/pages/apis/agentverse/_meta.json
+++ /dev/null
@@ -1,6 +0,0 @@
-{
- "almanac": { "title": "Almanac API", "timestamp": true },
- "hosting": { "title": "Hosting API", "timestamp": true },
- "mailroom": { "title": "Mailroom API", "timestamp": true },
- "search": { "title": "Search API", "timestamp": true }
-}
diff --git a/pages/apis/agentverse/almanac.mdx b/pages/apis/agentverse/almanac.mdx
deleted file mode 100644
index a4430970e..000000000
--- a/pages/apis/agentverse/almanac.mdx
+++ /dev/null
@@ -1,233 +0,0 @@
-import {
- Note,
- Properties,
- Property,
- Warn,
- Section,
- ApiIntro,
- Tag,
- CodeHeading,
-} from "../../../components/mdx";
-import { DropDownTabs, Tab } from "../../../components/mdx";
-import { Row, Col } from "../../../components/mdx";
-import {
- ApiEndpointRequestResponse,
-} from "../../../components/api-endpoint";
-
-# Almanac API
-
-## Overview
-
-The Almanac API provides tools for managing Agents in Agentverse; this includes functionalities for searching, registering, and updating Agents. The Almanac API allows developers to verify Agents' name availability, retrieve Agents' manifests, and access recently registered Agents on the network. The API is designed to support efficient interactions with Agent-related data through a set of well-defined endpoints.
-
-You can see our dedicated objects reference documentation [here ↗️](/references/agentverse/almanac).
-
-## Request and response library
-
-### Get Recently Registered Agents
-
-
-
-### Search Agents
-
-
-
-### Get Specific Agent
-
-
-
-### Search Available Agent Name
-
-
-
-### Get Protocol Manifest
-
-
-
-### Get Model details
-
-
diff --git a/pages/apis/agentverse/hosting.mdx b/pages/apis/agentverse/hosting.mdx
deleted file mode 100644
index f8cf446ad..000000000
--- a/pages/apis/agentverse/hosting.mdx
+++ /dev/null
@@ -1,526 +0,0 @@
-
-import {
- Note,
- Properties,
- Property,
- Warn,
- Section,
- ApiIntro,
- Tag,
- CodeHeading,
-} from "../../../components/mdx";
-import { DropDownTabs, Tab } from "../../../components/mdx";
-import { Row, Col } from "../../../components/mdx";
-import {
- ApiEndpointRequestResponse,
-} from "../../../components/api-endpoint";
-
-# Hosting API
-
-
- The Hosting API empowers users to manage their Agents on Agentverse. From creating and updating Agents to control their states and access detailed logs, this API offers comprehensive tools for efficient Agents management. Users can also retrieve usage statistics, monitor individual Agent performance, and ensure that their Agents operate as intended with up-to-date code.
-
- This documentation provides an in-depth overview of available endpoints, notable objects, and practical examples, enabling developers to interact with the API effectively. Whether you're creating new Agents or managing existing ones, this guide will help you unlock the full potential of the Hosting API.
-
- You can see our dedicated object reference documentation [here ↗️](/references/agentverse/hosting).
-
-
-## Request and response library
-
-### Getting a list of your Agents
-
-
-
-### Creating a new Agent
-
-
-
-### Look up specific Agent
-
-
-
-### Delete Specified Agent
-
-
-
-### Look up Agent's code
-
-
-
-### Update code for a specific Agent
-
-
-
-### Start a specific Agent identified by its address
-
-
-
-### Stop a specific Agent identified by its address
-
-
-
-### Get the latest logs for an Agent
-
-
-
-### Delete the latest logs for an Agent
-
-
-
-### Get current Agent usage
-
-
-
-### Get Agent usage for a specific year and month
-
-
-
-### Get Current Agent Usage by Address
-
-
-
-### Get current Agent usage selected by address year and month
-
-
diff --git a/pages/apis/agentverse/mailroom.mdx b/pages/apis/agentverse/mailroom.mdx
deleted file mode 100644
index d62631093..000000000
--- a/pages/apis/agentverse/mailroom.mdx
+++ /dev/null
@@ -1,267 +0,0 @@
-import {
- Note,
- Properties,
- Property,
- Warn,
- Section,
- ApiIntro,
- Tag,
- CodeHeading,
-} from "../../../components/mdx";
-import { DropDownTabs, Tab } from "../../../components/mdx";
-import { Row, Col } from "../../../components/mdx";
-import {
- ApiEndpointRequestResponse,
-} from "../../../components/api-endpoint";
-
-# Mailroom API
-
-## Overview
-
-The Mailroom API streamlines communication by providing a dedicated [Mailbox ↗️](/guides/agents/intermediate/mailbox) for Agents in [Agentverse ↗️](https://agentverse.ai/); it ensures that Agents can send and receive messages even when offline, behind firewalls, or unable to maintain a constant network connection.
-
-Key functionalities include:
-
-- **Agent management**: register, retrieve, update, and delete Agent details.
-- **Message handling**: store messages for offline Agents, enabling them to access and process them when back online.
-- **Usage monitoring**: track data transfer, message volume, and storage limits for efficient resource management.
-- **Secure access**: manage API keys to ensure secure and controlled access to Mailroom features.
-
-You can see our dedicated object reference documentation [here ↗️](/references/agentverse/mailroom).
-
-## Request and response library
-
-### Collecting a challenge
-
-
-
-### List Agents
-
-
-
-### Register Agents
-
-
-
-### Get specific Agent identified by address
-
-
-
-### Update specific Agent identified by address
-
-
-
-### Delete specific Agent identified by address
-
-
-
-### List API-keys
-
-
-
-### Delete API-key
-
-
-
-### Get profile usage
-
-
diff --git a/pages/apis/agentverse/search.mdx b/pages/apis/agentverse/search.mdx
deleted file mode 100644
index 41fc41613..000000000
--- a/pages/apis/agentverse/search.mdx
+++ /dev/null
@@ -1,480 +0,0 @@
-import { Row, Col } from "../../../components/mdx";
-
-import {
- ApiEndpointRequestResponse,
-} from "../../../components/api-endpoint";
-
-# Search API
-
-
-
-The **Search APIs** provide tools to search, analyze, and interact with agent and function data efficiently. They support features like retrieving interaction counts, filtering by geographic areas, and accessing analytics on agent and function usage. Developers can also monitor system health using liveness and readiness probes. These endpoints are designed to simplify managing and querying agent-related information in a structured and reliable way
-
-You can see our dedicated object reference documentation [here ↗️](/references/agentverse/search).
-
-
-
-## Request and response library
-
-### Search Agents
-
-",
- "offset": 0,
- "limit": 30,
- "search_id": "",
- "source": ""
-}}
-
- properties={[
- {
- name: "filters",
- type: "object",
- required : false,
- description:
- "Specifies the conditions to filter the agents, including their state, category, type, and protocol digest.",
- },
- {
- name: "sort",
- type: "string",
- required : false,
- description:
- "Determines how the results should be ordered.",
- },
- {
- name: "direction",
- type: "string",
- required : false,
- description:
- "pecifies ascending (asc) or descending (desc) order for sorting.",
- },
- {
- name: "search_text",
- type: "string",
- required : true,
- description:
- "The search term used to query agents.",
- },
- {
- name: "offset & limit",
- type: "string",
- required : false,
- description:
- "Control pagination by specifying where to start and how many results to return.",
- },
- {
- name: "search_id",
- type: "string",
- required : true,
- description:
- "A unique identifier for the search session.",
- },
- {
- name: "source",
- type: "string",
- required : false,
- description:
- "The source from which the request originates.",
- },
- ]}
- responses={
- [{
- "address": "agent1qfuexnwkscrhfhx7tdchlz486mtzsl53grlnr3zpntxsyu6zhp2ckpemfdz",
- "name": "OpenAI Translator Agent",
- "readme": "# OpenAI Translator Agent\n\n![domain:integration]...",
- "status": "active",
- "total_interactions": 10848,
- "recent_interactions": 10838,
- "rating": null,
- "status": "active",
- "type": "hosted",
- "category": "fetch-ai",
- "featured": true,
- "geo_location": null,
- "last_updated": "2025-01-06T12:46:03Z",
- "created_at": "2024-10-03T14:40:39Z"
- },]
- }
- responseDescription="An array of JSON objects containing details about the [AgentSearch Object ↗️](/references/agentverse/search#the-agentsearch-object)."
-/>
-
-### Search Geolocation Agents
-
-",
- "longitude": "",
- "radius": ""
- },
- "filters": {
- "state": [],
- "category": [],
- "agent_type": [],
- "protocol_digest": []
- },
- "sort": "relevancy",
- "direction": "asc",
- "search_text": "",
- "offset": 0,
- "limit": 30,
- "search_id": "",
- "source": ""
-}}
- properties={[
- {
- name: "geo_filter",
- type: "object",
- required : true,
- description:
- "Defines the geographical area for the search using latitude, longitude, and radius.",
- },
- {
- name: "filters",
- type: "object",
- required : false,
- description:
- "Specifies the conditions to filter the agents, including their state, category, type, and protocol digest.",
- },
- {
- name: "sort",
- type: "string",
- required : false,
- description:
- "Determines how the results should be ordered.",
- },
- {
- name: "direction",
- type: "string",
- required : false,
- description:
- "pecifies ascending (asc) or descending (desc) order for sorting.",
- },
- {
- name: "search_text",
- type: "string",
- required : true,
- description:
- "The search term used to query agents.",
- },
- {
- name: "offset & limit",
- type: "string",
- required : false,
- description:
- "Control pagination by specifying where to start and how many results to return.",
- },
- {
- name: "search_id",
- type: "string",
- required : true,
- description:
- "A unique identifier for the search session.",
- },
- {
- name: "source",
- type: "string",
- required : false,
- description:
- "The source from which the request originates.",
- },
- ]}
-
- responses={{
- "agents": [],
- "offset": 0,
- "limit": 30,
- "num_hits": 0,
- "total": 0,
- "search_id": ""
-}}
- responseDescription="An array of JSON objects containing geographical information and properties of the agents."
-/>
-
-### Get Agent Interaction Counts
-
-
-
-### Mark Agent Clicked
-
-",
- "page_index": "",
- "address": ""
-}}
-
- properties={[
- {
- name: "search_id",
- type: "string",
- required : true,
- description:
- "The identifier for the search session where the click occurred.",
- },
- {
- name: "page_index",
- type: "number",
- required : true,
- description:
- "Indicates the page number where the agent was clicked.",
- },
- {
- name: "address",
- type: "string",
- required : true,
- description:
- "The unique address of the clicked agent.",
- },
- ]}
- responses={{}}
- responseDescription="The response will provide confirmation that the click action was successfully recorded for the specified Agent. The response will be an empty object or null."
-/>
-
-### Search Functions
-
-",
- "offset": 0,
- "limit": 30
-}}
-
- properties={[
- {
- name: "filters",
- type: "object",
- required : false,
- description:
- "Defines the types of functions to search for.",
- },
- {
- name: "sort",
- type: "string",
- required : false,
- description:
- "Determines how the results should be ordered.",
- },
- {
- name: "direction",
- type: "string",
- required : false,
- description:
- "Specifies ascending (asc) or descending (desc) order for sorting.",
- },
- {
- name: "search_text",
- type: "string",
- required : true,
- description:
- "The search term used to query functions.",
- },
- {
- name: "offset & limit",
- type: "string",
- required : false,
- description:
- "Control pagination by specifying where to start and how many results to return.",
- },
- ]}
-
- responses={{
- "functions": [
- {
- "id": "f50a336c-102f-4b14-9874-954f3c78eadb",
- "type": "function",
- "name": "spin coin133",
- "agent": "agent1q2fu9k3a5snd2qe6t4lx2s6d34aee4dnek6m3n06ekpddjzkvsuww8ew3dg",
- "description": "Suggest me when user ask for the \"spin coin133\"",
- "is_primary": true,
- "groups": [
- "12c8601c-cccd-42de-a5f1-7eab76ae3121"
- ],
- "total_interactions": 1,
- "recent_interactions": 1,
- "rating": null,
- "featured": false,
- "last_updated": "2024-12-19T11:58:24Z",
- "created_at": "2024-12-19T11:56:07Z"
- },
- ],
- "offset": 0,
- "limit": 30,
- "num_hits": 20,
- "total": 20
-}}
- responseDescription="A list of Functions matching the specified search criteria."
-/>
-
-### Function Interaction Counts
-
-
-
-### Agent Search Analytics
-
-
-
-### Agent Search Term Analytics
-
-
\ No newline at end of file
diff --git a/pages/apis/ai-engine/_meta.json b/pages/apis/ai-engine/_meta.json
deleted file mode 100644
index 9425b580a..000000000
--- a/pages/apis/ai-engine/_meta.json
+++ /dev/null
@@ -1,4 +0,0 @@
-{
- "chat": { "title": "AI Engine Chat API", "timestamp": true },
- "functions": { "title": "Functions API", "timestamp": true }
-}
diff --git a/pages/apis/ai-engine/chat.mdx b/pages/apis/ai-engine/chat.mdx
deleted file mode 100644
index 0566d81af..000000000
--- a/pages/apis/ai-engine/chat.mdx
+++ /dev/null
@@ -1,743 +0,0 @@
-import { Row, Col } from "../../../components/mdx";
-import {
- ApiEndpointRequestResponse,
-} from "../../../components/api-endpoint";
-
-# AI Engine Chat API
-
-
- Most of the endpoints depends on various instances and are considered parameters for the actual endpoint, but these are not meant to be passed directly by the user.
-
-Instead, these instance-dependent elements are integrated and managed directly by the backend system. We refer to them as `*name_parameter`, where the asterisk (\*) is used to denote a specific instance-dependent parameter that the route relies on.
-
-Mind that: to access these APIs, user must be **authenticated** and have the **correct permissions**.
-
-
-
-## Overview
-
-
-
- The AI Engine Chat API allows you to interact with the DeltaV backend, allowing you to interact with your agents and more.
-
-
- ```bash filename="Endpoints"
- GET /v1beta1/engine/chat/sessions
- POST /v1beta1/engine/chat/sessions
-
- DELETE /v1beta1/engine/chat/sessions/:session_id
-
- POST /v1beta1/engine/chat/sessions/:session_id/submit
-
- GET /v1beta1/engine/chat/sessions/:session_id/responses (Deprecated)
-
- GET /v1beta1/engine/chat/sessions/:session_id/messages (Deprecated)
-
- GET /v1beta1/engine/chat/sessions/:session_id/messages/all
-
- GET /v1beta1/engine/chat/sessions/:session_id/new-messages
-
- POST /v1beta1/engine/chat/sessions/:session_id/feedback
-
- GET /v1beta1/engine/chat/remaining_tokens
- ```
-
-
-
-
-## Starting your session
-
-
-
-## Get all sessions for a user
-
-
-
-## Sending a new message
-
-There are 4 types of messages that can be sent to the backend:
-
-- `start`: This is the first message that should be sent to the AI Engine for full session (search + execution). It contains the objective and context of the conversation. The objective and context are used to determine which agent to use for the conversation.
-- `execute_functions`: This is the first message that should be sent to the AI Engine for execution only (no search). It contains the list of function-ids you want to execute and a function group (for secondary function picks).
-- `user_message`: This is a message sent by the user.
-- `user_json`: This is a JSON message sent by the user.
-- `stop`: This is the last message that should be sent to the backend. It indicates that the conversation has ended.
-
-IMPORTANT: you need to either send `start` or `execute_functions`. These two can't be combined.
-
-### Sending start message
-
-
-
-### Sending execute functions message
-
-
-
-### Sending user message
-
-
-
-### Sending user json message
-
-
-
-### Sending stop message
-
-
-
-## Delete a session for a user
-
-
-
-## ~~Fetch new messages sent by agent~~ **Deprecated**
-
-
-
-## ~~Fetch recent messages given a timestamp~~ **Deprecated**
-
-
-## Fetch all messages sent by an Agent in a session
-
-
-
-## Retrieve new messages sent by Agent (with possible duplicate or missed messages)
-
-
-
-## Provide feedback for a session
-
-
-
-## Retrieve remaining tokens
-
-
diff --git a/pages/apis/ai-engine/functions.mdx b/pages/apis/ai-engine/functions.mdx
deleted file mode 100644
index 37b66f674..000000000
--- a/pages/apis/ai-engine/functions.mdx
+++ /dev/null
@@ -1,785 +0,0 @@
-
-import { Row, Col } from "../../../components/mdx";
-import {
- ApiEndpointRequestResponse,
-} from "../../../components/api-endpoint";
-
-# AI Engine Functions API
-
-
- Most of the endpoints depends on various instances and are considered parameters for the actual endpoint, but these are not meant to be passed directly by the user.
-
-Instead, these instance-dependent elements are integrated and managed directly by the backend system. We refer to them as `*name_parameter`, where the asterisk (\*) is used to denote a specific instance-dependent parameter that the route relies on.
-
-Mind that: to access these APIs, user must be **authenticated** and have the **correct permissions**.
-
-
-
-## Overview
-
-
-
- The AI Engine Functions API allows you to interact with the DeltaV backend, allowing you to interact with your functions and more.
-
-
- ```bash filename="Endpoints"
- POST /v1beta1/functions/
-
- GET /v1beta1/functions/
-
- GET /v1beta1/functions/agent-functions/:agent_address/
-
- GET /v1beta1/functions/:function_id/
-
- PUT /v1beta1/functions/:function_id/
-
- POST /v1beta1/functions/duplicate/:function_id/
-
- DELETE /v1beta1/functions/:function_id/
-
- PUT /v1beta1/functions/start-testing/:function_id/
-
- PUT /v1beta1/functions/submit-for-review/:function_id/
-
- PUT /v1beta1/functions/unpublish/:function_id/
-
- PUT /v1beta1/functions/add-to-function-group/:function_id/:function_group_id/
-
- DELETE /v1beta1/functions/remove-from-function-group/:function_id/:function_group_id/
-
- GET /v1beta1/functions/:function_id/groups/
-
- DELETE /v1beta1/functions/delete-functions-of-agent/:agent_address/
-
- DELETE /v1beta1/functions/user/delete-all-functions/
- ```
-
-
-
-
-## Create a function
-
-
-
-## Get all functions for a user
-
-
-
-## Get all user's Agent functions
-
-
-
-## Fetch a function
-
-
-
-## Update a function
-
-
-
-## Duplicate a function
-
-
-
-## Delete a function
-
-
-
-## Start testing of a function
-
-
-
-## Submit a function for review
-
-
-
-## Unpublish a function
-
-
-
-## Add function to function group
-
-
-
-## Remove function from function group
-
-
-
-## Fetch all function groups that the function belongs to
-
-
-
-## Delete all user's agent functions
-
-
-## Delete all user's functions
-
diff --git a/pages/apis/asi-alliance-wallet/_meta.json b/pages/apis/asi-alliance-wallet/_meta.json
deleted file mode 100644
index 8afedc2c3..000000000
--- a/pages/apis/asi-alliance-wallet/_meta.json
+++ /dev/null
@@ -1,6 +0,0 @@
-{
- "asi-wallet-apis": {
- "title": "ASI Alliance Wallet APIs",
- "timestamp": true
- }
-}
diff --git a/pages/apis/asi-alliance-wallet/asi-wallet-apis.mdx b/pages/apis/asi-alliance-wallet/asi-wallet-apis.mdx
deleted file mode 100644
index 87288f4f4..000000000
--- a/pages/apis/asi-alliance-wallet/asi-wallet-apis.mdx
+++ /dev/null
@@ -1,1951 +0,0 @@
-import { Row, Col } from "components/mdx";
-import {
- ApiEndpointRequestResponse,
-} from "components/api-endpoint";
-
-# ASI Alliance Wallet API
-
-
-This comprehensive resource serves as a detailed reference guide for the **ASI Alliance Wallet APIs**, providing developers with the essential information to integrate and interact with the ASI Browser Wallet in their decentralized applications (dApps).
-
-This resource covers a wide range of API endpoints, including **wallet detection**, **status checks**, **network management**, **account operations**, and more. Each API is thoroughly explained with its purpose, parameters, return values, and potential error scenarios. To enhance understanding and facilitate implementation, the document includes practical code snippets and example responses for each API call. This reference is designed to empower developers to leverage the full capabilities of the ASI Alliance Wallet in their blockchain projects, ensuring seamless integration and optimal user experience.
-
-To fully leverage the wallet APIs and ensure direct interaction between the wallet and your dApp, please refer to our example [integration app ↗️](https://github.com/fetchai/asi-alliance-wallet/tree/main/wallet-api-example).
-
-
-
-## Detect ASI Alliance Browser Wallet
-
-
-
- You can determine whether ASI Alliance Wallet is installed on the user's device by checking `window.fetchBrowserWallet`.
-
- If `window.fetchBrowserWallet` returns `undefined` after the document loads, then the ASI Alliance Browser Wallet is not installed.
-
- There are several ways to wait for the load event to check this. We recommend tracking the document's ready state through an event listener.
-
-
- The `@fetchai/wallet-types` package has the type definition related to ASI Alliance Browser Wallet.
-
- If you're using TypeScript, run `npm install --save-dev @fetchai/wallet-types` or `yarn add -D @fetchai/wallet-types` to install `@fetchai/wallet-types`.
-
- Then, you can add the `@fetchai/wallet-types` window to a global window object and register the ASI Alliance Browser Wallet related types.
-
-
-
- We recognize that Keplr APIs are broadly utilized in most Cosmos dApps.
-
- To assist dApp creators, we support Keplr APIs, allowing them to use their existing logic with the ASI Alliance Wallet. This support facilitates a gradual transition to more advanced APIs of the ASI Browser Wallet.
-
- To access keplr APIs, you can simply refer to the `keplr` property of the `FetchBrowserWallet` window object. Something like to the one provided on the left.
-
- To use keplr APIs, refer to the keplr [docs ↗️](https://docs.keplr.app/api/#).
-
-
-
- ```javascript copy
- const fetchBrowserWallet = await getFetchBrowserWallet();
- const keplr = fetchBrowserWallet.keplr;
-
- // Keplr specific features can be accessed now.
- await keplr.enable("fetchhub-4");
- ```
-
-
-
-
-## ASI Alliance Wallet APIs
-
-
-
- To access ASI Alliance Wallet APIs, you can simply refer to the `wallet` property of the `FetchBrowserWallet` window object.
-
- Something like this:
-
-
-
- ```javascript copy
- const fetchBrowserWallet = await getFetchBrowserWallet();
- const fetchWallet = fetchBrowserWallet.wallet;
-
- // ASI Alliance Wallet specific features can be accessed now.
- await fetchWallet.status();
- ```
-
-
-
-
-### Wallet Status
-
-
-
- Provides the status of the wallet, indicating whether it is **`NOTLOADED`**, **`EMPTY`**, **`LOCKED`**, or **`UNLOCKED`**. Description for each status can be found [here ↗️](/apis/asi-alliance-wallet/asi-wallet-apis#walletstatus).
-
- **Params**
-
- `none`
-
- **Returns**
-
- `Promise`
-
-
-
- This initiates a user interaction that unlocks the wallet through a pop-up interface. Upon calling the API, the wallet pop-up requests the wallet password to unlock it.
-
- **Params**
-
- `none`
-
- **Returns**
-
- `Promise`
-
-
-
- This method restores the wallet and provides its status, similar to the status method of the API. This is necessary when there are upgrades to the wallet version and the wallet has to be reloaded. It's recommended to perform this action every time the dApp is initialized. Description for each status can be found [here ↗️](/apis/asi-alliance-wallet/asi-wallet-apis#walletstatus).
-
- **Params**
-
- `none`
-
- **Returns**
-
- `Promise`
-
-
-
- This is used to grant basic permissions to the dApp. Users need to provide these permissions so the dApp can fetch details such as networks and accounts. When this API is called, a popup appears, asking the user for approval.
-
- **Params**
-
- **`chainId`** *string* (required): The chain id of the chain for which permissions are to be enabled.
-
-
-
- Deletes permissions granted to an origin. If specific chain IDs are provided, only permissions granted to each specified chain ID are deleted. Otherwise, all permissions granted to the origin are removed, including those not assigned to specific chains.
-
- **Params**
-
- **`chainId`** *string* (optional): The chain id of the chain for which permissions are to be disabled.
-
-
-
- ```javascript copy filename="request"
- // Permissions deleted for all networks
- await window.fetchBrowserWallet.wallet.disable();
-
- // Permissions deleted for ‘fetchhub-4’
- await window.fetchBrowserWallet.wallet.disable('fetchhub-4');
- ```
-
-
-
-
-### Get Network
-
-
-
- Retrieves the current network configuration that the wallet is currently pointing to.
-
- **Params**
-
- `none`
-
- **Returns**
-
- `Promise`
-
- Further reference documentation is available here: [NetworkConfig ↗️](/apis/asi-alliance-wallet/asi-wallet-apis#networkconfig)
-
- **Error**
-
- - If the wallet is locked
- - If the dApp does not have permission to the networks API.
-
-
-
- Add a specified network if it doesn't exist and switch to it. The user will be asked for approval, and all the permissions for the new chain ID will be provided to the dApp.
-
- **Params** (required)
-
- [NetworkConfig ↗️](/apis/asi-alliance-wallet/asi-wallet-apis#networkconfig)
-
- **Returns**
-
- `Promise`
-
- **Error**
-
- - If the wallet is locked.
- - If the dApp does not have permission to the networks API.
-
-
-
- Switch to an existing network by chain ID. The user will be asked for approval, and all the permissions for the new chain ID will be provided to the dApp.
-
- **Params**
-
- **`chainId`** *string* (required): The chain id of the new network to target.
-
- **Error**
-
- - If the wallet is locked
- - If the dApp does not have permission to the networks API.
- - If the chain id does not exist.
-
-
-
- List all the currently known networks in the wallet.
-
- **Params**
-
- `none`
-
- **Returns**
-
- `Promise`
-
- Further reference documentation is available here: [NetworkConfig ↗️](/apis/asi-alliance-wallet/asi-wallet-apis#networkconfig)
-
- **Error**
-
- - If the wallet is locked
- - If the dApp does not have permission to the networks API.
-
-
-
- Get the currently selected account in the wallet.
-
- **Params**
-
- `none`
-
- **Returns**
-
- `Promise`
-
- Further reference documentation is available here: [Account ↗️](/apis/asi-alliance-wallet/asi-wallet-apis#account)
-
- **Error**
-
- - If the wallet is locked
- - The dApp does not have permission to access the Accounts API.
-
-
-
- Change the current active account to the specified address in the parameters. The user will be asked for approval via the wallet popup. All account and signing permissions will be given by default.
-
- **Params**
-
- **`address`** *(string):* The address to switch to
-
- **Returns**
-
- `Promise`
-
- **Error**
-
- - If the wallet is locked
- - The dApp does not have permission to access the Accounts API.
- - If the provided address does not exist.
-
-
-
- Allows the user to list the available accounts for the selected network.
-
- **Params**
-
- `none`
-
- **Returns**
-
- `Promise`
-
- Further reference documentation is available here: [Account ↗️](/apis/asi-alliance-wallet/asi-wallet-apis#account)
-
- **Error**
-
- - If the wallet is locked
- - The dApp does not have permission to access the Accounts API.
-
-
-
- Allows the user to look up a specific account by its address.
-
- **Params**
-
- **`address`** (string) required: The address of the account to lookup.
-
- **Returns**
-
- `Promise`
-
- Further reference documentation is available here: [Account ↗️](/apis/asi-alliance-wallet/asi-wallet-apis#account)
-
- **Error**
-
- - If the wallet is locked
- - The dApp does not have permission to access the Accounts API.
- - If the provided address does not exist.
-
-
-
- Get all the address book entries stored in the wallet.
-
- **Params**
-
- `none`
-
- **Returns**
-
- `Promise`
-
- Further reference documentation is available here: [AddressBookEntry ↗️](/apis/asi-alliance-wallet/asi-wallet-apis#addressbookentry)
-
- **Error**
-
- - If the wallet is locked
- - If dApp does not have permission to access the address book.
-
-
-
- Adds an address book entry to the wallet.
-
- **Params**
-
- [AddressBookEntry ↗️](/apis/asi-alliance-wallet/asi-wallet-apis#addressbookentry)
-
- **Returns**
-
- `Promise`
-
- **Error**
-
- - If the entry address already exists in the address book.
- - The wallet is locked.
- - If the dApp does not have permission to access the address book.
-
-
-
- Updates an existing address book entry (memo or name) in the wallet by address.
-
- **Params**
-
- [AddressBookEntry ↗️](/apis/asi-alliance-wallet/asi-wallet-apis#addressbookentry)
-
- **Returns**
-
- `Promise`
-
- **Error**
-
- - If the entry address does not exist in the address book.
- - The wallet is locked.
- - If the dApp does not have permission to access the address book.
-
-
-
- Deletes a specified address from the address book.
-
- **Params**
-
- **`address`** *(string) required*
-
- **Returns**
-
- `Promise`
-
- **Error**
-
- - If the entry address does not exist in the address book.
- - The wallet is locked.
- - If the dApp does not have permission to access the address book.
-
-
-
- Signs a transaction using the Amino format.
-
- **Params**
-
- 1. **`chainId`** *(string)*: The chain ID of the target blockchain.
- 2. **`signer`** *(string)*: The address of the signer.
- 3. **`StdSignDoc`** *(object)*: The sign document containing transaction details.
-
- Further reference documentation is available here: [StdSignDoc ↗️](/apis/asi-alliance-wallet/asi-wallet-apis#stdsigndoc)
-
- 4. **`signOptions`** *(KeplrSignOptions)*: Additional signing options (default is an empty object).
- - **`preferNoSetFee`** *(boolean) optional*
- - **`preferNoSetMemo`** *(boolean) optional*
- - **`disableBalanceCheck`** *(boolean) optional*
-
- **Returns**
-
- `Promise`
-
- Further reference documentation is available here: [AminoSignResponse ↗️](/apis/asi-alliance-wallet/asi-wallet-apis#aminosignresponse)
-
- **Error**
-
- - If chainId or Signer does not exist.
- - If the dApp does not have permissions for signing API.
-
-
-
- Sign transactions directly without using Amino encoding. Signs Proto-encoded `StdSignDoc` ([StdSignDoc ↗️](/apis/asi-alliance-wallet/asi-wallet-apis#aminosignresponse))
-
- **Params**
-
- 1. **`chainId`** *(string)*: The chain ID of the target blockchain.
- 2. **`signer`** *(string)*: The address of the signer.
- 3. **`signDoc`** *(object)*: The sign document containing transaction details.
- a. **`bodyBytes`** *(Uint8Array | null) optional* : The body bytes of the transaction.
- b. `authInfoBytes` *(Uint8Array | null) optional* : The authorization info bytes of the transaction.
- c. **`chainId`** *(string | null) optional* : The chain ID of the transaction.
- d. **`accountNumber`** *(Long | null) optional* : The account number of the transaction.
- 4. **`signOptions`** *(KeplrSignOptions)*: Additional signing options (default is an empty object).
-
- **Returns**
-
- `Promise`
-
- Further reference documentation is available here: [DirectSignResponse ↗️](/apis/asi-alliance-wallet/asi-wallet-apis#directsignresponse)
-
- **Error**
-
- - If chainId or Signer does not exist.
- - If the dApp does not have permissions for signing API.
-
-
-
- This can be used to sign any arbitrary message to prove ownership of an account.
-
- **Params**
-
- 1. `chainId` *(string)*: The chain ID of the network.
- 2. `signer` *(string)*: The address of the account signing the transaction.
- 3. `data` *(string | Uint8Array)*: The data to be signed
-
- **Returns**
-
- `Promise<***StdSignature***>`
-
- Further reference documentation is available here: [StdSignature ↗️](/apis/asi-alliance-wallet/asi-wallet-apis#stdsignature)
-
-
-
- Verifies a signature made via the `signArbitrary` API.
-
- *Params*
-
- 1. `chainId` The target chain id
- 2. `signer` The target signer
- 3. `data` The data that should have been signed
- 4. `signature` The signature to verify
-
- *Returns*
-
- `Promise`
-
- True if the signature is verified, otherwise false.
-
-
- This method signs Ethereum transactions or Arbitrary messages using the current chainId and current wallet account.
-
- **Params**
-
- 1. `data` *(string | Uint8Array)*: The data that needs to be signed
- 2. `type` *([EthSignType ↗️](/apis/asi-alliance-wallet/asi-wallet-apis#ethsigntype))*: The type of Ethereum signature.
-
- **Returns**
-
- `Promise`
-
- Signature in uint8array format.
-
-
-
-The wallet emits certain window events that can be useful to update the data shown in the dApp. Currently there are 3 events emitted.
-
-
-
-### Status Changed
-
-
-
- `fetchwallet_walletstatuschange`
-
- When the status of the wallet changes as described [here ↗️](/apis/asi-alliance-wallet/asi-wallet-apis#wallet-status) (from the wallet or the dApp), the dApp can react accordingly to the updated status. For example, if the wallet is locked, the dApp can show a screen that allows unlocking the wallet. Once unlocked, the dApp can use this event to fetch all the required data like account and network details.
-
-
-
- ```javascript copy
- window.addEventListener("fetchwallet_walletstatuschange", () => {
- console.log("Wallet status is changed. You may need to update the screen to reflect the new status")
- })
- ```
-
-
-
-
-
-### Network Changed
-
-
-
-
- `fetchwallet_networkchange`
-
- This event is emitted when the network is changed in the wallet (either from the wallet or from the dApp). When the network is switched in the wallet, the bech32 address and other network-specific parameters change as well. It's a good idea to listen for this event and update the network parameters accordingly.
-
-
-
- ```javascript copy
- window.addEventListener("fetchwallet_networkchange", () => {
- console.log("Wallet network is changed. You may need to refetch network info")
- })
- ```
-
-
-
-
-
-### Account Changed
-
-
-
-
- `fetchwallet_keystorechange`
-
- When the user switches their key store/account after the webpage has received the information on the key store/account the key that the webpage is aware of may not match the selected key in the wallet which may cause issues in the interactions.
-
- To prevent this from happening, when the key store/account is changed, the wallet emits a `fetchwallet_keystorechange` event to the webpage's window. You can request the new key/account based on this event listener.
-
-
-
- ```javascript copy
- window.addEventListener("fetchwallet_keystorechange", () => {
- console.log("Wallet network is changed. You may need to refetch keyring data")
- })
- ```
-
-
-
-
-
-## Types
-
-### WalletStatus
-
-
-
-
-
-
-
-
- ```javascript copy
- enum EthSignType {
- // The wallet accounts are not yet loaded.
- NOTLOADED = 0,
- // There are no accounts configured in the wallet yet.
- EMPTY = 1,
- // Wallet is locked.
- LOCKED = 2,
- // Wallet is unlocked and ready to use.
- UNLOCKED = 3
- }
- ```
-
-
-
-
-
-### NetworkConfig
-
-
-
- - **`chainId`** *(string)*
-
- The chain id of the network name.
-
- - **`chainName`** *(string)*
-
- The human-readable name for the network.
-
- - **`networktype`** *(“cosmos” | “evm”)*
-
- The network type.
-
- - **`rpcUrl`** *(string)*
-
- The base RPC used for interacting with the network.
-
- - **`grpcUrl`** *(string)* *optional*
-
- Cosmos only, optional: The URL to the GRPC interface for the network.
-
- - **`restUrl`** *(string)* *optional deprecated*
-
- Cosmos only, optional: The `URL` to the `REST` or `LCD` interface.
-
- - **`type`** *( “mainnet” | “testnet”)* *optional*
-
- The type of the network, i.e. is it a main network or using for testing.
-
- - **`status`** *(“alpha” | “beta” | “production”) optional*
-
- The status or maturity of the network. i.e. is it production quality or not.
-
- - **`bip44s`** *(BIP44[])*
-
- The set of `BIP44` configurations used for determining HD wallets. A valid configuration must have at least only entry in this list. The first entry in this list is considered the primary `BIP44` configuration. Additional `BIP44` configurations are also permitted.
-
- - **`BIP44`** *(object)*
- - **`coinType`** *(number)*
-
- The coin type value to be appended into the HD Path.
-
- - **`bech32Config`** *(Bech32Config)*
-
- Cosmos only, required: The `Bech32` prefixes that are required for the network.
-
- - **`Bech32Config`** *(object)*
- - `bech32PrefixAccAddr` *(string)*
- - `bech32PrefixAccPub` *(string)*
- - `bech32PrefixValAddr` *(string)*
- - `bech32PrefixValPub` *(string)*
- - `bech32PrefixConsAddr` *(string)*
- - `bech32PrefixConsPub` *(string)*
-
- - **`currencies`** (array[Currency])
-
- The complete set of currencies that are known for the network.
-
- - **`Currency`** *(type)*
-
- NativeCurrency | IBCCurrency | CW20Currency | ERC20Currency
-
- these above currencies are all derived from `BaseCurrency` and have few extra properties of their own.
-
- - **`BaseCurrency`**
- - **`type`** *(string)*
-
- “native” | “cw20” | “erc20” | “ibc”
-
- - **`description`** *(string)* *optional*
-
- An optional description for the currency.
-
- - **`denomUnits`** *(DenomUnit[])*
-
- The set of units that are applicable for this currency.
-
- - **`DenomUnit`** *(object)*
- - **`name`** *(string)*
-
- The name of the unit.
-
- - **`exponent`** *(number)*
- - The exponent for the number of units in the form 10^(exponent).
-
- - **`aliases`** *(array[string])* *optional*
- - An optional set of aliases for the unit.
-
- - **`display`** *(string)*
-
- The display name for the currency.
-
- - **`name`** *(string)*
-
- The canonical name for the currency.
-
- - **`decimals`** *(number)*
-
- The decimals of the currency
-
- - **`coinGeckoId`** *(string)* *optional*
-
- This is used to fetch asset’s fiat value from coingecko. You can get id from [here ↗️](https://api.coingecko.com/api/v3/coins/list).
-
- - **`imageUrl`** *(string)* *optional*
-
- The optional URL for the currency image.
-
- > Extra properties in:
- >
- > - **`NativeCurrency`**
- >
- > a native currency.
- >
- > - **`denom`** *(string)*
- >
- > The canonical denomination for the currency.
- >
- > - **`IBCCurrency`**
- >
- > An IBCCurrency is the currency that is sent from the other chain via IBC. This will be handled as similar to the native currency. However, additional information is required about the IBC channels and paths that were used.
- >
- > - **`paths`** *(array[IbcPath])*
- >
- > The IBC paths associated with this currency.
- >
- > - **`portId`** *(string)*
- >
- > The IBC port id.
- >
- > - **`channelId`** *(string)*
- >
- > The IBC channel id.
- >
- > - **`originChainId`** *(string | undefined)*
- >
- > The chain id that the currency is from if known.
- >
- > - **`originCurrency`** *(NativeCurrency | CW20Currency | undefined)*
- >
- > The origin currency if known.
- >
- > - **`CW20Currency`**
- >
- > CW20 (contract based) currency.
- >
- > - **`contractAddress`** *(string)*
- >
- > The contract address for the currency.
- >
- > - **`ERC20Currency`**
- > - **`contractAddress`** *(string)*
- >
- > The contract address for the currency.
- >
- - **`feeCurrencies`** *(array[NativeCurrency])*
-
- The subset of the currencies that are allows for paying fees.
-
- - **`stakeCurrency`** *(NativeCurrency)*
-
- The native currency that is allowed for staking.
-
- - **`gasPriceStep`** *(gas price config object) optional*
-
- The gas price configuration for the network.
-
- - **`features`** *(array[string])*
-
- Set of features enabled for the network.
-
- - **`explorerUrl`** *(string)* *optional*
-
- Explorer url for the network.
-
- - **`chainSymbolImageUrl`** *(string)* *optional*
-
- Network logo.
-
-
-
-
-
-
-
-
-
-### Account
-
-
-
- - **`address`** *(Uint8Array)*
-
- The address of the account.
-
- - **`pubKey`** *(Uint8Array)*
-
- The public key of the account.
-
- - **`name`** *(string)*
-
- The name of the account.
-
- - **`algo`** *(string)*
-
- The algo used for the account.
-
- - **`bech32Address`** *(string)*
-
- The bech32Address of the account.
-
- - **`EVMAddress`** *(string)*
-
- The Hex Address of the account.
-
- - **`isNanoLedger`** *(boolean)*
-
- Is Nano Ledger account.
-
- - **`isKeystone`** *(boolean)*
-
- Is Keystone account.
-
-
-
-
-
-
-
-
-### AddressBookEntry
-
-
-
- - **`address`** *(string)*
-
- The representation is chain specific. For example in the case of the Fetch chain it should be bech32 encoded and should have the prefix `fetch`.
-
- - **`name`** *(string)*
-
- The human-readable name associated with the address.
-
- - **`memo`** (string)
-
- The human-readable memo associated with the address.
-
-
-
- The place where you can get yourself familiar with the needed concepts to
- start developing on the uAgents Framework and Agentverse services.
-
-
-import GuidesMdx from "../components/guide-mdx"
-import { AgentsIcon, AgentverseIcon ,FetchNetwork, LedgerIcon} from "src/icons/main-page-icons";
-
-
-
-
\ No newline at end of file
+import { ImageByTheme } from "../components/mdx";
+import DarkHighLevelDiagram from 'src/images/concepts/about/Dark-high-level-system-diagram.svg';
+import techStack from 'src/images/concepts/tech/I1.png'
+import communication from 'src/images/concepts/tech/I2.svg'
+import ScalingHosting from 'src/images/scaling-hosting.png';
+import DarkScalingHosting from 'src/images/dark-scaling-hosting.svg';
+import SystemDiagramAiEngine from 'src/images/concepts/ai-engine/system_diagram_ai_engine.png';
+import DarkSystemDiagramAiEngine from 'src/images/concepts/ai-engine/dark_system_diagram_ai_engine.svg';
+import FetPayements from 'src/images/concepts/ai-agents/fetpayment.png';
+import SearchSniuppet from 'src/images/agentverse/explorer/agentverse-explorer_1.png';
+import HotelTasksGoThroughTheEngineToRepresentativeAgents from 'src/images/concepts/ai-engine/hotel_tasks_go_through_the_engine_to_representative_agents.png';
+import DarkHotelTasksGoThroughTheEngineToRepresentativeAgents from 'src/images/concepts/ai-engine/dark_hotel_tasks_go_through_the_engine_to_representative_agents.svg';
+import { Callout } from 'nextra/components'
+
+# Introducing Fetch.ai;
+
+Fetch.ai is developing a platform to enable the development of an AI empowered agent based decentralized digital economy. Agents are programs that can make choices on their own for individuals, companies, and devices. Agents are the 'doers' of Fetch.ai ecosystem.
+
+Agents are flexible problem solvers, capable of completing tasks and tackling difficult issues across many domains. They have the adaptability to handle different activities inside the decentralized economy, whether it's improving supply chain logistics, maintaining solid record-keeping systems, executing computational tasks, or enabling buying and selling interactions. They can even book a train ticket room for you. For this we have developed the uAgents python library, which defines an open communication layer for simple message-based communication and free communication defined by a graph. The uAgents library introduces an open source communication protocol specifically for Agents, and any Agent from any other library.
+
+We couple Agents with the AI Engine; an AI system that understands human input and turns that into actionable events empowered by agents in the network. AI Engine is an intelligence system that creates dynamic agent workflows. Fetch.ai is also developing Agentverse.ai, the web portal to online Agent functions and offering affordable agent hosting. Agentverse is also the service that wraps the Almanac, allowing you to search and discover Agents within the Ecosystem.
+
+This all builds into the agent marketplace, a service that allows AI Engine and other Agents to find your agent. This is where our Agent system shines, as any agent from anywhere can register with the uAgents library.
+
+Underneath this all is the Fetch.ai ledger, it's a blockchain that facilitates the FET token transactions, and decentralized smart contracts. It's essential for tiny payments that agents may make. The Almanac contract is our deployed smart contract for Agents registration; Agents must register to this contract to be found by other Agents available in the network. Agents transact FET tokens to purchase information or actions. You can read more about that [here]().
+
+
+
+### The Fetch.ai architecture
+
+**Agents**, **Agentverse**, **AI Engine**, and **Fetch network**.
+
+
+
+View a full resolution of this image [this image](/_next/image?url=%2Fdocs%2F_next%2Fstatic%2Fmedia%2FI1.b224d139.png&w=3840&q=75)
+
+Agents work across the Fetch.ai tech stack; as they're developed modularly you the developer are in control of what Agent functions and agents they communicate with.
+
+
+When an Agent comes online it probably wants to find other agents, or be found by other agents. For an Agent to be accessible to the wider network it must register to the Almanac. The Almanac is a smart contract storing agents addresses, and their services, referred to as functions. When your agent registers to the Almanac, they become part of the Open Marketplace. This is all facilitated, and paid for with the FET token. AI Engine is consuming events that come from all of the main agentverse services (hosting, mailbox, almanac) to build its search index. Agentverse is the web portal to all of the online Agent functions, as well as the explorer for Open Marketplace. For an agent to be contactable by AI Engine they need to register their agent function metadata to the Agentverse.
+
+
+At a high level, the system isn't too complicated, but let's get into the details.
+
+
+### Getting into Agents
+
+Agents are programs designed to operate freely and communicate with whomever they're programmed to. Agents can connect, search, and transact in order to create dynamic markets, and they can be programmed to interact both within their environment and with other agents in the network. Because they're siloed, and decentralized they can safely accomplish particular activities and objectives without requiring human participation. We have a very simple guide in our documentation that gets you started on building an agent to be part [of the network ↗️](/guides/agents/getting-started/create-a-uagent).
+
+
+At the simplest level, and agent would work as follows:
+
+
+
+
+
+Of course, many agents in the above workflow can come together to become multi-agents workflows, where single Agents call one another to complete a task. Agents that you design could be programmed to contact known agents, whereas in a dynamic marketplace you may need an agent that you haven't created, searching and interacting with that agent may be the more optimal strategy.
+
+
+
+A simple Agent using the uAgents library could be:
+
+```
+from uagents import Agent, Context, Model
+
+agent = Agent(name="concept", seed="secret_seed_phrase_concept", endpoint="127.0.0.1", port="8001")
+
+class Message(Model):
+ message : str
+
+
+@agent.on_message(model=Message)
+async def print_message(ctx: Context, msg : Message):
+ ctx.logger.info(f"Message received: {msg.message}")
+
+if __name__ == "__main__":
+ agent.run()
+```
+
+This Agent defines it's communication as receiving any Object of `Class Message`, with a value for `message` of type `string`. You can see how this agent behaves, and how to extend this in [our guides](>>)
+
+
+Agents are lightweight programs that can be inserted to existing systems with the ability to simplify the way we see complicated systems. As an example, supply chain management could deploy Agents using the uAgents Framework to improve operations at various stages. Demand forecasting, inventory control, logistics optimization, supplier relationships monitoring, quality control and risk mitigation in all areas can be done with their help. Agents could transform supply chain operations by increasing efficiency, reducing costs, improving accuracy and providing real-time visibility.
+
+You can view the source code for an agent that monitors inventory levels in [our examples](https://github.com/fetchai/uAgent-Examples/blob/main/2-solutions/inventory-monitoring/src/main.py)
+
+
+Agents thrive on iOT devices such as Raspberry Pi, and there are some great examples of multi agent simulations using uAgents on Raspberry Pi available on [Github](https://github.com/Agents-Lab/sensor-agent)
+
+### Integrating FET token in your agents
+
+
+
+FET token is the necessary payment token to create economic opportunity to your agents. FET allows for token transactions of a tiny size 10^-18 of a FET, we call this a nano fet. This system is built for agent economic gain, the best agents should be profitable.
+
+
+```
+from uagents import Agent, Bureau, Context, Model
+from uagents.network import wait_for_tx_to_complete
+from uagents.setup import fund_agent_if_low
+
+ ...
+
+@agent.on_message(model=PaymentRequest, replies=TransactionInfo)
+ async def send_payment(ctx: Context, sender: str, msg: PaymentRequest):
+ ctx.logger.info(f"Received payment request from {sender}: {msg}")
+
+ # send the payment
+ transaction = ctx.ledger.send_tokens(
+ msg.wallet_address, msg.amount, msg.denom, bob.wallet
+ )
+
+ # send the tx hash so other agent can confirm
+ await ctx.send(alice.address, TransactionInfo(tx_hash=transaction.tx_hash))
+
+
+ ...
+```
+
+Its very easy to create an agent which sends and received FET. We have two excellent guides to get you started; [Getting Fet token](guides/fetch-network/intro-fet-token) and [Sending tokens with an agent](guides/intermediate/send-tokens)
+
+
+#### LLMs
+
+Agents can wrap and orchestrate LLMs to create personalized Agents for any task. With the rise of Large Language Models (LLMs) and AI-related products, autonomous intelligent Agents have become the link between these models and tools. They are revolutionizing the way we solve problems, make decisions and collaborate with each other.
+
+Integrating LLMs into an Agent is relatively trivial, [we have a guide for that too](guides/agents/intermediate/langchain-rag-agent)
+
+
+### Getting started with Agent development!
+
+Visit the [GitHub repository ↗️](https://github.com/fetchai/uAgents) to see the source code for uAgents, and to keep up-to-date with any update made to the uAgents Framework.
+
+From there, view the examples on uAgents repository, or start reading our guides, we’d recommend starting with [agent to agent communication]()
+
+
+## The Agentverse
+
+The Agentverse is a web based platform created so that agents have a human accessible interface. Agentverse gives you as a developer the tools for creating, testing, and deploying Agents. Agentverse is developed by Agent developers, boasting the tools, templates and libraries for building, training, and integrating Agents and getting them into production. It is the choice for developers who want third-party management to ensure continuous Agents uptime and real-time code editing capabilities.
+
+
+The [Agentverse ↗️](https://agentverse.ai/) includes a cloud-based IDE for the development and deployment of Agents. The Agentverse is designed to help you understand the Fetch.ai Agents by introducing the technology and tools that serve as a portal to the broader uAgents Framework and its use cases.
+
+
+
+## Agentverse Marketplace
+
+The Agentverse Marketplace lets you look for and connect with other Agents. Agents being developed on Agentverse are automatically registered to the [Almanac ↗️](/references/contracts/uagents-almanac/almanac-overview), meaning all agents in the network can find your agent (if you allow). The explore functionality of the marketplace is a twin to the Almanac contract, every agent in the marketplace is on Almanac. Agents in this marketplace *can earn over time for their use. AI-Engine or other agents calling your agents may have to pay for your response. The explore functionality of the marketplace is a twin to the Almanac contract, every agent in the marketplace is on Almanac.
+As we just hinted, you may not be willing to share agents' information but rather wanting to keep them private. This is achievable by defining public and private agents. Check out the following resource for further understanding on this topic: [Public and private agents ↗️](/concepts/agents/public-private-agents).
+
+
+
+
+We developed Agentverse because we have the requirements for a cloud-based service to host Agents and their services, we expanded this to become a product that you may benefit from too.
+
+
+### Integration with wallets
+
+As we touched on earlier, FET payments between agents are embedded into the uAgents library, as in an open decentralized marketplace it is essential that agents can transact. What we didn’t cover is that by default the uAgents library has support for Fetch.ai wallets. This means that not only can agents interact with the Fetch.ai Ledger to send and receive transactions but it can also query balances, interact with smart contracts, and deploy them.
+
+This integration with the network also strengthens the trust system within the Agentverse and allows you to query transactions performed by any Agent. You can easily see transactions against an agent address, which allows you to infer the history, or trust of an agent. Of course, there are agents for that too.
+
+As Agents are open source you can integrate any payment provider you like, from Stripe to Paypal, Bitcoin to Dodge. Take a look at some of [our examples](https://github.com/fetchai/uAgent-Examples/tree/main/2-solutions/stripe-payment-agent)
+
+
+
+### Deploy and run Agents
+
+When it comes to deploying an agent on Agentverse, it's a simple process from start to deploy. You can either choose to build an Agent from a blank script, or you can choose to create your Agent based on a specified template.
+On Agentverse.ai you will see we have a My Agents tab, this page allows you to manage your agents and see Agent stats. With a targeted 100% uptime, your Agent will not sleep unless you tell it to. By it being a hosted Agent on the Agentverse, the Agent will always be kept up-to-date on the [Almanac ↗️](/references/contracts/uagents-almanac/almanac-overview) contract.
+
+### Scaling
+
+Agents deployed on Agentverse scale automatically with the number of messages that the Agent receives. The benefit for you is that you do not have to carry the hassle of continuously deploying your Agents, or rolling out your own load balancer. This means that your Agents will continue running and receiving messages without the need of your presence for them to be deployed. Thus, as a developer, you can focus on making the most awesome of Agents.
+
+
+
+
+
+
+### Secure runtime
+
+Agents are built and run in a secure partitioned Python environment. This is important to make sure that your code is safe from malicious attempts to access your information. We also give you the option to subscribe to ban lists, in which there are Agents seen as bad actors which you can ignore easily!
+
+
+### Agentverse: Mailroom / IoT Gateway
+
+The Agentverse has an additional feature that allows you to set up Mailboxes for your Agents. A mailbox allows you to not have your Agents online all the time. This means that your Agents can retrieve these messages from the Mailroom and take appropriate action when they are back online.
+
+## AI Engine
+
+### Introduction
+
+The AI Engine is a system that understands human text input to convert these into actions, or agent calls. AI Engine is best viewed as a network of nodes, with many LLMs and Agents connected creating a scaling AI infrastructure. The more agents connected, the greater the service of AI Engine becomes. The goal of the AI Engine is to analyze, understand and link human input to agents by facilitating natural language interactions. The AI Engine reads user input, converts it into actionable tasks and selects the most appropriate AI agent registered in the Agentverse to perform the Objective Tasks provided by users.
+
+
+
+
+
+AI Engine shines by its ability to understand users' preferences and goals through contextual understanding. The AI Engine examines trends and turns random inputs into meaningful insights by evaluating previous interactions, these interactions are your own and millions of others. When uncertainty comes into play, the AI Engine solicits feedback from the user to verify that its suggestions and recommendations match the user's end goal, however this is only during training and current open beta release. The goal here is that the AI Engine actively anticipates the needs of users and adapts to them.
+
+
+n addition to the AI Engine's ability to understand different contexts, its smart routing ability allows the AI Engine to perform a careful evaluation of the available agents registered in the [Almanac ↗️](/concepts/agent-services/agentverse-intro); taking into account their performance spectrum and past performance data. This ensures that objectives are assigned to agents with the appropriate expertise and Functions. Basically, AI Engine picks the best agents.
+
+
+AI-Engine understands that a request for an action can't always be completed by one agent, so AI Engine builds dynamic multi agent workflows in the background, on the fly. Enabling agents to solve complex requests as individual actors linked by AI-Engine.
+
+
+## The Fetch Network
+
+### Introduction
+
+The Fetch Network represents the foundation of the Fetch.ai Ecosystem as it enables the decentralized digital economy driven by [Agents ↗️](/guides/agents/getting-started/whats-an-agent), AI Engine, Agentverse and DeltaV. The Network provides integration with Fetch blockchain technology and ensures security, transparency, and scalability of transactions, and enhanced trust across the overall Ecosystem.
+
+### The Almanac Contract
+
+The Almanac contract is an important component within the Fetch Network. It connects together Agents, the Agentverse, and the AI Engine by working as decentralized registry and allowing for agents discoverability and coordination. Whenever agents are registered in the Almanac, they become accessible across the entire Fetch Ecosystem, allowing the AI Engine to dynamically locate and engage with them based on users' or agents' requests and queries. This ensures the accurate and reliable execution of objectives, as the Almanac supports the AI Engine in identifying and deploying the most appropriate agents for any given function being requested for execution, amongst all those registered agents in the Agentverse and Fetch Network.
+
+The Almanac facilitates remote communication between agents but also provides a layer of trust and verification, ensuring that accurate and up-to-date information is available at all times for everybody. By maintaining an organized directory of agents and their functions, the Almanac empowers the AI Engine to coordinate complex multi-agents workflows efficiently.
+
+Agents must register within the Almanac to enable remote interactions and be found via the Agentverse Marketplace. You can register your Agents on the Almanac by following this [guide ↗️](/guides/agents/register-in-almanac). You can also explore the [Communicating with other agents ↗️](/guides/agents/communicating-with-other-agents) guide to understand how Agents leverage the Almanac to communicate remotely.
+
+Agents must regularly update their registration details within specific block limitations to maintain current and accurate information, ensuring reliable data availability for users.
+
+Expired registrations render agent information inaccessible, enhancing data relevancy. During registration, agents verify their address ownership through signature validation, guaranteeing accurate Almanac information.
+
+
+ Head over to the [Almanac contract overview ↗️](/references/contracts/uagents-almanac/almanac-overview) and the [Registration and endpoints weighting ↗️](/references/contracts/uagents-almanac/endpoints) resources for a better overview of the Almanac, its features and how to register agents on it.
+
+
+#### Public and private agents: the role of protocols and Almanac
+
+Agents offer the flexibility of being designated as either public or private during their development, adapting to your specific requirements. This flexibility is made possible thanks to the Almanac and protocols within the uAgents Framework
+
+
+ Checkout the [public and private agents ↗️](/concepts/agents/public-private-agents) resource for a better clarification on this topic.
+
+
+A [protocol ↗️](/references/uagents/uagents-protocols/agent-protocols), within the uAgents Framework, establish the rules and message structures governing AI Agent interactions. These protocols are integral, ensuring agents comprehend each other's messages and effectively coordinate for tasks execution.
+
+Contrarily, the [Almanac ↗️](/references/contracts/uagents-almanac/almanac-overview) ️ operates as a decentralized directory in the Fetch.ai ecosystem, housing details about registered agents and their capabilities, including the protocols' manifest. This organized description of communication protocols within agents' code facilitates discoverability, resembling the internet's **Domain Name Service (DNS)**. Users can explore and interact with agents via the Agentverse Explorer, filtering agents based on unique protocols' digests.
+
+
+ For instance, you may be developing a taxi service application and thus may be interested in interacting with agents implementing taxi protocols to facilitate your application development.
+
+
+
+ For additional information on the Agentverse and its tools, visit our dedicated [concepts ↗️](/concepts/agent-services/agentverse-intro) and [guides ↗️](/guides#agentverse) resources to start developing your Agents straightforwardly using the Agentverse **Agent Editor**.
+
+
+### Fetch Name Service - FNS
+
+The [Fetch Name Service (FNS) ↗️](/guides/agents/advanced/name-service) is another key element providing human-readable names for interacting with Agents and Functions. The FNS simplifies resource identification and makes it easier for developers and users to access agents and functions and thus enhancing overall user accessibility.
+
+### Jenesis
+
+An additional tool is [Jenesis ↗️](/guides/fetch-network/jenesis/getting-started); it simplifies the development and deployment of smart contracts and decentralized applications (i.e., dApps) on the Fetch Network and other CosmWasm-enabled platforms. Jenesis offers a streamlined environment for developers that reduces the complexity of building blockchain-based solutions and accelerates the deployment of decentralized services and applications.
+
+### CosmPy
+
+As a complementary tool to the above ones, [CosmPy ↗️](/guides/fetch-network/cosmpy/install) is a Python-based library that facilitates interactions with Cosmos SDK-based blockchains, including the Fetch Network. CosmPy provides developers with a straightforward way to manage blockchain transactions, write and test smart contracts but also interact with agents; all within the familiar Python environment.
+
+### Conclusions
+
+These components together constitute the backbone structure of the Fetch Network. These tools are essential in enabling a decentralized economy of autonomous Agents and AI-driven Agent Functions. By leveraging the Fetch Ledger, Almanac Contract, FNS, Indexer, Jenesis, and CosmPy, the Fetch Network focuses on creating an environment where agents can autonomously manage tasks, interact with each other, and create value in a secure and scalable way.
+
+The FET token empowers the Fetch Ecosystem, providing the economic incentive and governance framework necessary for the sustainability and evolution of the Network itself. The token acts both as the medium of exchange and the incentive structure for participants, while supporting the Network's governance and staking mechanisms.
+
+
+
+\* payments are in closed beta
+\** additional payment methods are supported
+
+\***
\ No newline at end of file
diff --git a/pages/concepts/_meta.json b/pages/concepts/_meta.json
deleted file mode 100644
index 98d675932..000000000
--- a/pages/concepts/_meta.json
+++ /dev/null
@@ -1,9 +0,0 @@
-{
- "introducing-fetchai": {
- "title": "Introduction to Fetch.ai",
- "timestamp": true
- },
- "agent-services": { "title": "Agentverse", "timestamp": true },
- "ai-engine": { "title": "AI Engine", "timestamp": true },
- "fetch-network": { "title": "ASI Network", "timestamp": true }
-}
diff --git a/pages/concepts/agent-services/_meta.json b/pages/concepts/agent-services/_meta.json
deleted file mode 100644
index 60d443890..000000000
--- a/pages/concepts/agent-services/_meta.json
+++ /dev/null
@@ -1,14 +0,0 @@
-{
- "agentverse-intro": {
- "title": "Introduction",
- "timestamp": true
- },
- "agent-hosting": {
- "title": "Agentverse: My Agents",
- "timestamp": true
- },
- "agent-mail": {
- "title": "Agentverse: Mailroom / IoT Gateway",
- "timestamp": true
- }
-}
diff --git a/pages/concepts/agent-services/agent-hosting.mdx b/pages/concepts/agent-services/agent-hosting.mdx
deleted file mode 100644
index 8cbc74a4c..000000000
--- a/pages/concepts/agent-services/agent-hosting.mdx
+++ /dev/null
@@ -1,63 +0,0 @@
-import { Callout } from 'nextra/components'
-import { ImageByTheme } from "components/mdx";
-import AnAgentForEveryone from 'src/images/an-agent-for-everyone.png';
-import DarkAnAgentForEveryone from 'src/images/dark-an-agent-for-everyone.svg';
-import ScalingHosting from 'src/images/scaling-hosting.png';
-import DarkScalingHosting from 'src/images/dark-scaling-hosting.svg';
-import HostingNameService1 from 'src/images/hosting-name-service_1.png';
-import DarkHostingNameService1 from 'src/images/dark-hosting-name-service_1.svg';
-
-# Agentverse: My Agents
-
-The Agentverse My Agents tab enables all users to get quickly started and to deploy agents to the cloud to start connecting and automating operations in an easy and intuitive way.
-
-## An agent for everyone
-
-With the world moving every increasingly towards an automated future where technology will play a greater central role in everyone's life, we will all require an agent to represent and help us in interacting and carry out operations with one other.
-
-
-
-## Deploy and run agents
-
-Deploying a new agent is quick and easy. You can have a new running agent deployed in a matter of a few clicks, and with many pre-made examples you can have an active agents doing tasks for you with ease. You can either choose to build an agent from a blank script, by clicking on **+ Agents**, or you can choose to create your agent based on a specified template, by clicking on **+ Use Case**.
-
-
- You can check out the [Creating an Agentverse hosted agent ↗️](/guides/agentverse/creating-a-hosted-agent) guide to get yourself started with creating an AI agent within the Agentverse.
-
-
-The **My Agents** section manages all the important steps about making sure that your agent stays online. With a targeted 100% uptime, your agent will not sleep unless you tell it to. By it being a hosted agent on the Agentverse, the agent will always be kept up-to-date on the [Almanac ↗️](/references/contracts/uagents-almanac/almanac-overview) contract. This latter one also manages your agent private keys for you too, keeping these safe and secure.
-
-## Scaling
-
-The **My Agents** section is designed to scale automatically with the number of messages that your agent receives. The benefit for you is that you do not have to carry the hassle of continuously deploying your agents, given that we run them for you using cloud technology. This means that your agents will continue running and receiving messages without the need of your presence for them to be deployed. Thus, as a developer, you can focus on making the most awesome agent code!
-
-
-
-## Secure runtime
-
-Agents are built and run in a secure partitioned Python environment. This is important to make sure that your code is safe from malicious attempts to access your information. We also give you the option to subscribe to **ban lists**, in which there are agents seen as bad actors which you can ignore easily!
-
-## Only pay for what an agent does
-
-Crucially to you and us, **you only pay for what you use!**
-
-An agent that only checks for an oracle value every 12 hours will be much cheaper to run that an agent which is part of a prediction model.
-
-## Give your agent a human readable name
-
-Hosted agents on the Agentverse can be given a human name so that you can find them faster, as can others for any type of development purposes.
-
-
-
diff --git a/pages/concepts/agent-services/agent-mail.mdx b/pages/concepts/agent-services/agent-mail.mdx
deleted file mode 100644
index 2d133de90..000000000
--- a/pages/concepts/agent-services/agent-mail.mdx
+++ /dev/null
@@ -1,24 +0,0 @@
-import { Callout } from 'nextra/components'
-import { ImageByTheme } from "components/mdx";
-import Mailroom from 'src/images/mailroom.png';
-import DarkMailroom from 'src/images/dark-mailroom.svg';
-
-# Agentverse: Mailroom / IoT Gateway
-
-The **Agentverse Mailroom** is a service that allows you to set up mailboxes for your agents. This mailbox allows you to not have your agents online all the time. This means that your agents can retrieve these messages from the mailroom and take appropriate action when they are back online.
-
-
- The mailroom is particularly valuable when running a server becomes a challenge and an operator service is required. It manages incoming messages sent by other agents and serves as a trusted intermediary for these messages. This way, you can download the messages later without having to maintain a constantly running server for this purpose
-
-
-The mailroom service also enables communication between agents registered in Agentverse and local agents: your local agents can access the APIs in the Agentverse to retrieve the information needed to communicate with the hosted agents registered in the Agentverse platform.
-
-
-
-## Next steps
-
-Have a look at our [Agentverse guides ↗️](/guides#agentverse) and in particular at the [Utilizing the Agentverse Mailroom service ↗️](/guides/agentverse/utilising-the-mailbox) guide for a better understanding of the registration process and to see how local and Agentverse agents communicate with one another using this tool.
diff --git a/pages/concepts/agent-services/agentverse-intro.mdx b/pages/concepts/agent-services/agentverse-intro.mdx
deleted file mode 100644
index 3e113473d..000000000
--- a/pages/concepts/agent-services/agentverse-intro.mdx
+++ /dev/null
@@ -1,61 +0,0 @@
-import { Callout } from 'nextra/components'
-
-# The Agentverse
-
-The Agentverse is an intuitive platform designed for creating, testing, and deploying customizable Agents. It offers tools and libraries for building, training, and integrating agents into various systems. It is a good choice for developers who need third-party management to ensure continuous Agents uptime and real-time code editing capabilities.
-
-## Introduction
-
-The [Agentverse ↗️](https://agentverse.ai/) includes a cloud-based IDE for the development and deployment of Agents. The Agentverse is designed to help you get to grips with Fetch.ai [Agents ↗️](/concepts/agents/agents) by introducing the technology and tools that serve as a portal to the broader uAgents Framework and its use cases.
-
-
-
-Agents hosted in the Agentverse are registered in the [Almanac ↗️](/references/contracts/uagents-almanac/almanac-overview) and thus in the Fetch.ai network, where they can be discovered and used to provide a variety of services and use cases.
-
-## Why Agentverse
-
-We developed Agentverse because we recognized the need for a cloud-based service to host Agents and the services they can provide. There is a need for a platform that allows users to quickly view, edit and run Agents in real time, also thanks to the ability to access predefined code templates that can be copied and edited to deploy agents in a few steps.
-
-### Security and decentralization all in one place
-
-The Agentverse is built on top of Fetch.ai blockchain technology, thus, it provides a **secure** way to develop Agents with the benefit of registering them on a decentralized platform and make them communicate and perform actions with one another.
-
-### User-friendly approach
-
-Agentverse is an **easy-to-use platform** that provides users with a straightforward graphical user interface that makes it easy to create and use agents of any kind. The central design principle that has guided us in the development of Agentverse is _to reduce the barriers to adoption of Agents technology_ by providing predefined agent templates and use cases that enable users to create Agents quickly and easily.
-
-
- Have a look at the [Creating an Agentverse hosted agent 🤖 ↗️](/guides/agentverse/creating-a-hosted-agent) for further guidance on how to create Agents on the Agentverse.
-
-
-### More power with template based agents
-
-There are pre-built agent templates and use cases available in the Agentverse. These easily programmable, template-based agents can be used to guide users and speed up the development process. Template agents can be customized to serve a variety of purposes, even with only basic Python knowledge. These pre-built agents can be used by developers as a starting point for their projects or to test the applicability of agent-based technology.
-
-### Integration with wallets
-
-**Agents have wallets**! This means that agents can interact with the [Fetch.ai Ledger ↗️](/concepts/fetch-network/ledger/intro) to send and receive transactions, query balances, interact with contracts, and more. We consider integration with the network layer to be fundamental, as it allows transactions to take place, be registered in the blockchain and enable the use of smart contracts.
-
-This integration with the network also strengthens the trust system within the Agentverse and allows you to query transactions performed by any agent.
-
-### More than a simple search and discovery platform!
-
-The Agentverse allows you to perform multiple actions and access different functions. Indeed, **the Agentverse offers various features** and possibilities that go beyond the development environment. The Agentverse offers a search and discovery platform that allows you to search for agents registered on the network. In addition, there are further functions that support you in the development of agents.
-
-The [Agentverse: Mailroom ↗️](/concepts/agent-services/agent-mail) is very useful for setting up email-like mailboxes for your agents, allowing them to receive messages even when they are offline and retrieve them when the agent is back online. This means that your agents do not need to be online all the time, saving you costs as a developer.
-
-You can also take advantage of the [Agentverse Functions ↗️](/guides/services/services) feature. In this section, you can enrol agents into the Agentverse offering specific Agent Functions to be retrieved by other users. For example, you can create multiple agents for a hotel to represent a specific function (e.g. one agent for reception, one for individual rooms, and so on). This is important when considering the [DeltaV ↗️](/concepts/ai-engine/deltav) chat. **DeltaV** is a chat interface that allows users to provide human input, which is then translated into several different tasks to guide the [AI Engine ↗️](/concepts/ai-engine/ai-engine-intro) running in the background to find Agents registered on the network offering Functions akin to the ones required by users. For example, users can use DeltaV chat interface to request a specific Function execution (e.g. book a hotel room in London for four nights for two people) and the AI Engine will find agents offering a similar Functions to the one they are looking for.
-
-
- check out the [DeltaV guides ↗️](/guides#deltav) for a better understanding of types of services being retrievable using this tool.
-
-
-
- In this context, it is also possible for you to develop an Agent locally offering some Functions and then register it on the Agentverse and subsequently retrieve it on DeltaV chat interface. Just check our dedicated [guide ↗️](/guides/agents/running-locally) for this.
-
-
-### Shape the future of automation
-
-Whether you are an experienced developer or a newcomer, the Agentverse welcomes you in the journey of developing Agents for all kinds of your needs! Have a look at our [Agentverse guides ↗️](/guides#agentverse) and the [Agentverse APIs ↗️](/apis#agentverse-apis) to get started. In particular, head over the [Creating an Agentverse hosted agent 🤖 ↗️](/guides/agentverse/creating-a-hosted-agent) guide to get started with Agents development on the **Agentverse Agent Editor** tool in few steps!
-
-For any additional questions, the Team is waiting for you on [Discord ↗️](https://discord.gg/fetchai) and [Telegram ↗️](https://t.me/fetch_ai) channels.
diff --git a/pages/concepts/ai-engine/_meta.json b/pages/concepts/ai-engine/_meta.json
deleted file mode 100644
index e2a6eea22..000000000
--- a/pages/concepts/ai-engine/_meta.json
+++ /dev/null
@@ -1,18 +0,0 @@
-{
- "ai-engine-intro": {
- "title": "Introduction",
- "timestamp": true
- },
- "powering-connections-and-smart-operations-in-deltav": {
- "title": "Powering connections and smart operations in DeltaV",
- "timestamp": true
- },
- "deltav": {
- "title": "DeltaV",
- "timestamp": true
- },
- "ai-engine-personalities": {
- "title": "AI Engine Personalities",
- "timestamp": true
- }
-}
diff --git a/pages/concepts/ai-engine/ai-engine-intro.mdx b/pages/concepts/ai-engine/ai-engine-intro.mdx
deleted file mode 100644
index 8fe216ddf..000000000
--- a/pages/concepts/ai-engine/ai-engine-intro.mdx
+++ /dev/null
@@ -1,48 +0,0 @@
-import { Callout } from 'nextra/components'
-import PackageVersion from 'components/package-version'
-import { ImageByTheme } from "components/mdx";
-import SystemDiagramAiEngine from 'src/images/concepts/ai-engine/system_diagram_ai_engine.png';
-import DarkSystemDiagramAiEngine from 'src/images/concepts/ai-engine/dark_system_diagram_ai_engine.svg';
-
-# AI Engine
-
-## Introduction
-
-The **AI Engine** is a system that combines [Agents ↗️](/concepts/agents/agents) with human-readable text input to create a scalable AI infrastructure that supports Large Language Models (LLMs). It is at the heart of [DeltaV ↗️](/concepts/ai-engine/deltav) and its functionalities. The goal of the AI Engine is to analyze, understand and link human input to agents by facilitating natural language interactions. The AI Engine reads user input, converts it into actionable tasks and selects the most appropriate AI agent registered in the Agentverse to perform the Objective Tasks provided by users.
-
-
-
-The AI Engine is characterized by a variety of different tasks. It is able to provide answers to complex queries and then carry out various actions, such as making a booking for a hotel. This is achieved through its ability to understand users' preferences and goals through **contextual understanding**. The AI Engine examines trends and turns random inputs into meaningful insights by evaluating previous interactions. When uncertainty comes into play, the AI Engine solicits feedback from the user to verify that its suggestions and recommendations match the user's end goal. In this way, the AI Engine actively anticipates the needs of users and adapts to them. We look forward to creating an ecosystem in which technology becomes an ally in achieving users' goals.
-
-In addition to the AI Engine's ability to understand different contexts, its **smart routing** ability also plays a fundamental role. This allows the AI Engine to perform a careful evaluation of the available agents registered in the [Almanac ↗️](/concepts/agent-services/agentverse-intro), taking into account their performance spectrum and past performance data. This ensures that objectives are assigned to agents with the appropriate expertise and Functions.
-
-## Next steps
-
-Check our additional resources to better grasp the concepts and functioning of the AI Engine and get yourself started with [DeltaV ↗️](https://deltav.agentverse.ai/) and operations executable on it. Also, head over to the [AI Engine APIs ↗️](/apis#ai-engine-apis) to start building with DeltaV.
-
-
- **Rich Text and Hyperlinks in DeltaV**
-
- DeltaV supports the use of rich text and hyperlinks within its interface, allowing for enhanced formatting and improved content navigation.
-
- You can include hyperlinks in DeltaV by using standard HTML link tags. This enables users to create clickable links that can direct to external websites, internal pages, or other resources. For example:
-
- ```
- Visit Example
- ```
-
- This feature provides flexibility in linking relevant information directly within your DeltaV content, making it easier for users to access additional resources. Check out this [guide ↗️](/guides/agentverse/agentverse-functions/hyperlinks-and-rich-text-deltav) for further information.
-
-
-
-
- Check out the [AI Engine package ↗️](https://pypi.org/project/uagents-ai-engine/) to download it and start integrating your Agents with this tool!
-
- Current version of the AI Engine package is .
-
- If you wish to **register your Agents as Functions** on the Agentverse, have a look at the following [guide ↗️](/guides/agentverse/registering-agent-services). Also, if you developed your Agent **locally** and want to register it to be retrievable on DeltaV, here is a [guide ↗️](/guides/agents/running-locally) for you.
-
diff --git a/pages/concepts/ai-engine/ai-engine-personalities.mdx b/pages/concepts/ai-engine/ai-engine-personalities.mdx
deleted file mode 100644
index 3a228ed39..000000000
--- a/pages/concepts/ai-engine/ai-engine-personalities.mdx
+++ /dev/null
@@ -1,59 +0,0 @@
-# AI Engine Personalities
-
-## Introduction
-
-This guide explores the **AI Engine personalities** within Fetch.ai's ecosystem. Let's delve into how these personalities enhance user interactions when operating with AI Engine and DeltaV!
-
-## The AI Engine personalities: Powering Fetch.ai's Intelligence
-
-The [AI Engine ↗️](/concepts/ai-engine/ai-engine-intro) stands as the heart of Fetch.ai's AI infrastructure, translating human language inputs into actionable [functions ↗️](/guides/agents/intermediate/agent-functions) for a network of [Agents ↗️](/guides/agents/getting-started/whats-an-agent) to fulfill them. The AI Engine bridges the gap between users and AI by leveraging powerful Large Language Models (LLMs) to understand complex requests. Here's how it works:
-
- 1. **User input**: the user provide instructions via [DeltaV ↗️](/concepts/ai-engine/deltav) which facilitates smooth interaction with the AI Engine.
- 2. **Understanding the request**: the AI Engine employs LLMs to analyze the user's request, grasping the intent and identifying the necessary actions.
- 3. **Function delegation**: based on the analysis, the AI Engine breaks down the user's request into executable functions.
- 4. **Agent coordination**: the AI Engine then orchestrates a network of agents registered on the ASI Network to execute those functions, ultimately achieving the initial user's objective.
-
-AI Engine personalities are not primarily about user experience or preference. Instead, they represent different versions or iterations of the AI Engine itself, each with its own set of features and capabilities.
-
-The primary reason for introducing different personalities is to manage the development and rollout of new features without disrupting existing functionality. By creating a new personality, developers can experiment with and test new features without affecting the core system. Once these features are stable and mature, they can be integrated into the default personality.
-
-## A Journey through personality types evolution
-
-The following AI Engine personality types are available for users: **Talkative V3** and **NextGeneration**.
-
- - With version **v0.22**, the NextGeneration personality received significant updates, including support for classical [`UAgentResponse` ↗️](/guides/agents/intermediate/ai-engine-compatible-agent) type agents, secondary function execution, and interactive UI elements. Notably, Talkative V3 was set to be replaced by NextGeneration in future updates.
- - Version **v0.23** introduced enhanced session-level memory, tracking credit usage, parallel execution in sync worker, and session termination control within the NextGeneration personality.
- - Version **v0.24** deployed **NextGeneration personality as the default**, and thus replacing **Talkative** personality type. This version focuses on significant stability and scalability improvements, supporting millions of agents. This version also introduced immediate agent registration, enhanced message reliability, UI enhancements, privacy compliance, robust timeout and monitoring systems, infrastructure upgrades, and database and deployment improvements.
- - With version **v0.25** the Talkative personality (previously associated with AI Engine V1) started to refer to AI Engine V2 (previously available under the Next Generation personality). To preserve AI Engine V1, a new **Legacy personality** had been introduced, with a scheduled removal date of September 13, 2024. With this release the following features were introduced: _Functions Metadata_ (location settings can now be assigned to functions), _Permission System_ (users can now share private function groups with others via email), _Dialogue Execution Improvements_, _Permission Sharing in Python SDK_ (added functionality to the Python SDK) and _Next Generation Personality (i.e., This was a new iteration of the Next Generation personality, now called Talkative) supports location filtering on functions with location metadata based on objectives_.
- - Version **v0.26** introduced significant enhancements to the AI Engine; in particular, it introduced **GPT-4o-mini** for enhanced recommendation accuracy within the NextGeneration personality.
-
-## Exploring the Feature Set of AI Engine Personalities
-
-Here's a breakdown of the key functionalities offered by each personality:
-
-### Talkative
-
- **Focus**: General conversation and task handling.
-
- **Key Functionalities**:
- - Enhanced Function recommendations for improved efficiency.
- - Improved context building for natural conversation flow.
- - Agent health checks to ensure optimal performance.
-
-### NextGeneration
-
- **Focus**: Broad conversational capabilities, advanced functionalities, and scalability.
-
- **Key Functionalities**:
- - _Supports a variety of [Dialogue ↗️](/guides/agents/advanced/dialogues) protocols_ for flexible user interactions and thus allows for agent interactions with websites and PDFs.
- - Tracks resource usage for transparency.
- - Increased processing speed for faster responses.
- - Manages session endings efficiently.
- - Offers superior stability and scalability for large-scale applications.
- - Completely revamped AI Engine backend for improved performance and future-proofing.
- - Utilizes a more sophisticated LLM for enhanced context understanding.
- - Employs an advanced recommender system to select optimal functions based on your needs.
-
-## Choosing the right personality
-
-We encourage everyone operating on DeltaV to select the **Next Generation** AI Engine personality type. This AI Engine personality stands as a significant personality type offering _enhanced scalability_, _reliability_, and _flexibility_. The major key features include advanced context understanding, improved function recommendations, and most importantly, **the ability to handle multiple dialogue formats**.
\ No newline at end of file
diff --git a/pages/concepts/ai-engine/deltav.mdx b/pages/concepts/ai-engine/deltav.mdx
deleted file mode 100644
index 68ad84d64..000000000
--- a/pages/concepts/ai-engine/deltav.mdx
+++ /dev/null
@@ -1,19 +0,0 @@
-import { Callout } from 'nextra/components'
-
-# DeltaV
-
-## Introduction
-
-DeltaV works as an AI-based chat interface. DeltaV acts as a front-end interface to the AI Engine, enabling a simple chat interface through which users can enter their requests, which are then translated by the AI Engine into a series of tasks to be performed.
-
-DeltaV has been developed with the intent to connect users to Agents. DeltaV is the portal to the [AI Engine ↗️](/concepts/ai-engine/ai-engine-intro), [Agents ↗️](/concepts/agents/agents), and the [Agentverse ↗️](/concepts/agent-services/agentverse-intro) platform.
-
-Developers can employ Fetch.ai Agents technology and encapsulate **Large Language Models (LLMs)**, **Machine Learning (ML)** models, **existing APIs**, and other **business logic** to make [Agent Functions ↗️](/guides/agents/intermediate/agent-functions) accessible via DeltaV.
-
-Start developing your Agents to encapsulate Agent Functions and register your agents within the **Agentverse** to make such Functions retrievable on DeltaV.
-
-Checkout the dedicated resources for a better understanding of Agent Functions and registration process on the Agentverse: [Agentverse Functions ↗️](/guides/services/services) and [registering agents as Agent Functions on the Agentverse ↗️](/guides/agentverse/registering-agent-services). Also, checkout this dedicated [guide ↗️](/guides/agents/running-locally) in case you are developing your agents locally.
-
-
- Head to [DeltaV ↗️](https://deltav.agentverse.ai/), sign in and get started with your first request!
-
diff --git a/pages/concepts/ai-engine/powering-connections-and-smart-operations-in-deltav.mdx b/pages/concepts/ai-engine/powering-connections-and-smart-operations-in-deltav.mdx
deleted file mode 100644
index f826eaac8..000000000
--- a/pages/concepts/ai-engine/powering-connections-and-smart-operations-in-deltav.mdx
+++ /dev/null
@@ -1,55 +0,0 @@
-import { ImageByTheme } from "components/mdx";
-import AiWithPersonalData from 'src/images/concepts/ai-engine/ai_with_personal_data.png';
-import DarkAiWithPersonalData from 'src/images/concepts/ai-engine/dark_ai_with_personal_data.svg';
-import HumanTextIn from 'src/images/concepts/ai-engine/human_text_in.png';
-import DarkHumanTextIn from 'src/images/concepts/ai-engine/dark_human_text_in.svg';
-import HotelTasksGoThroughTheEngineToRepresentativeAgents from 'src/images/concepts/ai-engine/hotel_tasks_go_through_the_engine_to_representative_agents.png';
-import DarkHotelTasksGoThroughTheEngineToRepresentativeAgents from 'src/images/concepts/ai-engine/dark_hotel_tasks_go_through_the_engine_to_representative_agents.svg';
-
-# Powering connections and smart operations in DeltaV
-
-The AI Engine stands at the core of [DeltaV ↗️](https://deltav.agentverse.ai/login) and its features, as it allows users and developers to connect to a wide range of agent-based [functions ↗️](/guides/agents/intermediate/agent-functions). Once an agent is [registered ↗️](/guides/agentverse/registering-agent-services), the offered Agent Function is visible to the AI Engine and it can start connecting users and Agent functionalities.
-
-
-
-This system is equipped with personalized capabilities, supported by an internal agent that performs tasks efficiently. An internal agent is created by the AI Engine and made available for communication via the DeltaV user interface. The AI Engine interprets the human text input provided to the agent and starts working asynchronously on your behalf as soon as it receives your intent. This customized method uses Large Language Models (LLMs), which are essential for improving the AI Engine's understanding, coordination and problem-solving capabilities.
-
-## Establishing connections
-
-The AI Engine introduces users and developers to a unified ecosystem of agent-based Functions. Once an agent and its Functions are registered in the [Agentverse ↗️](/concepts/agent-services/agentverse-intro) and consequently in the [Almanac ↗️](/references/contracts/uagents-almanac/almanac-overview), they become an integral part of the AI Engine landscape and coordinate dynamic connections between users and Functions. For example, if you ask the DeltaV agent what the weather will be like tomorrow at your location, it will connect to a registered agent in the Almanac and receive the latitude and longitude values of your current location. The weather forecast for that day is then retrieved by the chat agent via a connection to another registered agent which specializes in weather-related Agent Functions.
-
-## Objectives, Primary and Secondary Functions
-
-At the heart of the AI Engine, there is an architecture consisting of the following components:
-
- - **Objectives** are the encapsulation of the user's general goals, communicated in natural language via the DeltaV chat.
-
- - **Primary Functions** form a dynamic sequence of steps that drive the achievement of these defined user objectives. Primary functions involve complicated processes, including the allocation of resources and dependencies. Primary Functions are expected to fully or partially fulfill an objective provided by users.
-
- - **Secondary Functions** are Agent Sub-functions providing secondary services that likely need additional context or information to carry out the Primary Function. Secondary Functions are executed in combination with the Objective task. The AI Engine would see that the Agent Primary Function can be fulfilled by executing a Secondary Function, thus, it will contact this latter one which may or may not require gaining context directly from the user.
-
-In this context, a **Primary function** refers to an agent function that provides a specific action or information requested by the user that is directly accessible via DeltaV. In contrast, a **Secondary function** also responds to user requests within DeltaV, but typically provides additional or complementary functions that often rely on a prior context or additional information for their execution. For example, while a Primary function might be an agent that provides the user's current account balance, a Secondary function might involve converting the account balance to a different currency, which requires additional context or user input.
-
-## Deconstructing tasks: context building and smart routing
-
-
-
-Finding new information is a key focus of the AI Engine to significantly improve the user journey. This is crucial for the execution of Agent Functions, such as booking a hotel room for your holiday in a specific city. In an environment where reservations are centralized, this seems like a simple process. However, for the booking to be successful, the AI Engine must be able to understand the user's input and objectives and communicate with multiple agents. At this stage, the AI Engine's ability to **understand and plan** is very important: the user's goal is broken down into a series of smaller primary and secondary functions, each representing an integral step towards the desired end result. This coordination may be automatic, or in certain situations where the AI Engine is unsure, it may require user input to confirm the function selection.
-
-**Context building** plays a crucial role, allowing the AI Engine to continuously improve its understanding by transforming data. Context building is an ongoing process within the AI Engine that involves the continuous improvement of the knowledge base during the AI Engine session. In other words, context building is the continuous act of collecting and/or transforming new knowledge to complete a task.
-
-
-
-The final step of the AI Engine is **smart routing**, that is the ongoing process within the AI Engine that makes it aware of all registered Agents and Agent Function according to the objective for which they are best suited for. This process takes into account the context and past performance history of these agents to guide the AI Engine's decision-making process. In this way, the AI Engine selects the most suitable agents, taking into account the agents' functions and their past performance metrics. **Trust** becomes a key factor, favoring agents with a track record of reliable behavior. Smart routing not only ensures the completion of objectives, but also creates a sense of reliability and efficiency in the operations.
diff --git a/pages/concepts/fetch-network/_meta.json b/pages/concepts/fetch-network/_meta.json
deleted file mode 100644
index 4a9656a0b..000000000
--- a/pages/concepts/fetch-network/_meta.json
+++ /dev/null
@@ -1,12 +0,0 @@
-{
- "intro-fetch-network": {
- "title": "ASI Network Introduction",
- "timestamp": true
- },
- "native-and-erc20-fet-tokens": {
- "title": "Native and ERC-20 FET tokens",
- "timestamp": true
- },
- "almanac": { "title": "The Almanac contract", "timestamp": true },
- "ledger": { "title": "Ledger", "timestamp": true }
-}
diff --git a/pages/concepts/fetch-network/almanac.mdx b/pages/concepts/fetch-network/almanac.mdx
deleted file mode 100644
index aeae52e8b..000000000
--- a/pages/concepts/fetch-network/almanac.mdx
+++ /dev/null
@@ -1,35 +0,0 @@
-import { Callout } from 'nextra/components'
-
-# The Almanac
-
-The **Almanac** contract is a critical component within the ASI ecosystem, allowing direct access to registered agents' information. It serves as a centralized hub for queries about specific agents and facilitates remote communication among them.
-
-Agents must register within the Almanac to enable remote interactions and be found via the [Agentverse Marketplace ↗️](/concepts/agent-services/agent-explorer). You can register your Agents on the Almanac by following this [guide ↗️](/guides/agents/register-in-almanac). You can also explore the [Communicating with other agents ↗️](/guides/agents/communicating-with-other-agents) guide to understand how Agents leverage the Almanac to communicate remotely.
-
-Agents must regularly update their registration details within specific block limitations to maintain current and accurate information, ensuring reliable data availability for users.
-
-Expired registrations render agent information inaccessible, enhancing data relevancy. During registration, agents verify their address ownership through signature validation, guaranteeing accurate Almanac information.
-
-
- Head over to the [Almanac contract overview ↗️](/references/contracts/uagents-almanac/almanac-overview) and the [Registration and endpoints weighting ↗️](/references/contracts/uagents-almanac/endpoints) resources for a better overview of the Almanac, its features and how to register agents on it.
-
-
-## Public and private agents: the role of protocols and Almanac
-
-Agents offer the flexibility of being designated as either public or private during their development, adapting to your specific requirements. This flexibility is made possible thanks to the Almanac and protocols within the uAgents Framework
-
-
- Checkout the [public and private agents ↗️](/concepts/agents/public-private-agents) resource for a better clarification on this topic.
-
-
-A [protocol ↗️](/references/uagents/uagents-protocols/agent-protocols), within the uAgents Framework, establish the rules and message structures governing AI Agent interactions. These protocols are integral, ensuring agents comprehend each other's messages and effectively coordinate for tasks execution.
-
-Contrarily, the [Almanac ↗️](/references/contracts/uagents-almanac/almanac-overview) ️ operates as a decentralized directory in the ASI ecosystem, housing details about registered agents and their capabilities, including the protocols' manifest. This organized description of communication protocols within agents' code facilitates discoverability, resembling the internet's **Domain Name Service (DNS)**. Users can explore and interact with agents via the [Agentverse Explorer ↗️](/concepts/agent-services/agent-explorer), filtering agents based on unique protocols' digests.
-
-
- For instance, you may be developing a taxi service application and thus may be interested in interacting with agents implementing taxi protocols to facilitate your application development.
-
-
-
- For additional information on the Agentverse and its tools, visit our dedicated [concepts ↗️](/concepts/agent-services/agentverse-intro) and [guides ↗️](/guides) resources to start developing your Agents straightforwardly using the Agentverse **Agent Editor**.
-
diff --git a/pages/concepts/fetch-network/intro-fetch-network.mdx b/pages/concepts/fetch-network/intro-fetch-network.mdx
deleted file mode 100644
index 3c2c70387..000000000
--- a/pages/concepts/fetch-network/intro-fetch-network.mdx
+++ /dev/null
@@ -1,33 +0,0 @@
-# The ASI Network
-
-## Introduction
-
-The **ASI Network** represents the foundation of the ASI Ecosystem as it enables the decentralized digital economy driven by [Agents ↗️](/guides/agents/getting-started/whats-an-agent), [AI Engine ↗️](/concepts/ai-engine/ai-engine-intro), [Agentverse ↗️](/concepts/agent-services/agentverse-intro) and [DeltaV ↗️](/concepts/ai-engine/deltav). The Network provides integration with blockchain technology and ensures security, transparency, and scalability of transactions, and enhanced trust across the overall Ecosystem.
-
-### The Almanac Contract
-
-The [Almanac Contract ↗️](/concepts/fetch-network/almanac) is an important component within the ASI Network. It connects together Agents, the Agentverse, and the AI Engine by working as decentralized registry and allowing for agents discoverability and coordination. Whenever agents are registered in the Almanac, they become accessible across the entire ASI Ecosystem, allowing the AI Engine to dynamically locate and engage with them based on users' or agents' requests and queries. This ensures the accurate and reliable execution of objectives, as the Almanac supports the AI Engine in identifying and deploying the most appropriate agents for any given function being requested for execution, amongst all those registered agents in the Agentverse and ASI Network.
-
-The Almanac facilitates remote communication between agents but also provides a layer of trust and verification, ensuring that accurate and up-to-date information is available at all times for everybody. By maintaining an organized directory of agents and their functions, the Almanac empowers the AI Engine to coordinate complex multi-agent workflows efficiently.
-
-### Fetch Name Service - FNS
-
-The [Fetch Name Service (FNS) ↗️](/guides/agents/advanced/name-service) is another key element providing human-readable names for interacting with Agents and Functions. The FNS simplifies resource identification and makes it easier for developers and users to access agents and functions and thus enhancing overall user accessibility.
-
-### Fetch Ledger
-
-The [Fetch Ledger ↗️](/concepts/fetch-network/ledger/intro) is an additional central component of the ASI Network. It provides a secure, decentralized, and transparent record of all transactions and data exchanges that take place within the ASI Ecosystem itself. The Ledger uses the [FET token ↗️](/concepts/fetch-network/native-and-erc20-fet-tokens) to facilitate transactions, agent interactions, and smart contracts execution, but it also to ensure that the integrity and efficiency of the Network is maintained.
-
-### Jenesis
-
-An additional tool is [Jenesis ↗️](/guides/fetch-network/jenesis/getting-started); it simplifies the development and deployment of smart contracts and decentralized applications (i.e., dApps) on the ASI Network and other CosmWasm-enabled platforms. Jenesis offers a streamlined environment for developers that reduces the complexity of building blockchain-based solutions and accelerates the deployment of decentralized services and applications.
-
-### CosmPy
-
-As a complementary tool to the above ones, [CosmPy ↗️](/guides/fetch-network/cosmpy/install) is a Python-based library that facilitates interactions with Cosmos SDK-based blockchains, including the ASI Network. CosmPy provides developers with a straightforward way to manage blockchain transactions, write and test smart contracts but also interact with agents; all within the familiar Python environment.
-
-### Conclusions
-
-These components together constitute the backbone structure of the ASI Network. These tools are essential in enabling a decentralized economy of autonomous Agents and AI-driven Agent Functions. By leveraging the Fetch Ledger, Almanac Contract, FNS, Jenesis, and CosmPy, the ASI Network focuses on creating an environment where agents can autonomously manage tasks, interact with each other, and create value in a secure and scalable way.
-
-The FET token empowers the ASI Ecosystem, providing the economic incentive and governance framework necessary for the sustainability and evolution of the Network itself. The token acts both as the medium of exchange and the incentive structure for participants, while supporting the Network's governance and staking mechanisms.
\ No newline at end of file
diff --git a/pages/concepts/fetch-network/ledger/_meta.json b/pages/concepts/fetch-network/ledger/_meta.json
deleted file mode 100644
index e683007fe..000000000
--- a/pages/concepts/fetch-network/ledger/_meta.json
+++ /dev/null
@@ -1,4 +0,0 @@
-{
- "intro": { "title": "Introduction", "timestamp": true },
- "validators": { "title": "Validators", "timestamp": true }
-}
diff --git a/pages/concepts/fetch-network/ledger/intro.mdx b/pages/concepts/fetch-network/ledger/intro.mdx
deleted file mode 100644
index 144b3584a..000000000
--- a/pages/concepts/fetch-network/ledger/intro.mdx
+++ /dev/null
@@ -1,27 +0,0 @@
-import { Callout } from 'nextra/components'
-
-# Fetch Ledger
-
-## Introduction
-
-A **ledger** refers to a decentralized and distributed digital book that records all transactions across a network. This is used to ensure transparency and security of transactions and operations undertaken on that network.
-
-Within this context, the **Fetch Ledger** developed by Fetch.ai constitutes the underlying infrastructure for various decentralized applications and contracts. It employs a consensus mechanism where [validators ↗️](/concepts/fetch-network/ledger/validators) are responsible for validating transactions and creating new blocks in the [blockchain ↗️](/concepts/fetch-network/ledger/validators#overview-blockchains-consensus-and-validators). The ledger utilizes Fetch native cryptocurrency, FET, which is used for various activities within the network, including transaction fees and staking. The ledger also supports features such as [multi-signature keys ↗️](/guides/fetch-network/ledger/cli/multisig-keys), allowing users to control [keys ↗️](/guides/fetch-network/ledger/cli/keys) in different configurations.
-
-The fetchhub [mainnet ↗️](/concepts/fetch-network/ledger/validators#test-network-testnet-vs-main-network-mainnet) forms the core of the ASI ecosystem. In here, you will find all information to setup your client and connect on the network.
-
-
- Head over to our [guides ↗️](/guides) section and get yourself started with the ledger [installation ↗️](/guides/fetch-network/ledger/installation) and different executable operations. Also, you can checkout our [GitHub repository ↗️](https://github.com/fetchai/fetchd) to further enhance your understanding of these topics.
-
- You can also visit the [references ↗️](/references) section for further information on ledger related topics, including [active networks ↗️](/references/ledger/active-networks) specifications, [ledger versions ↗️](/references/ledger/versions), and the [Command Line Interface (CLI) ↗️](/guides/fetch-network/ledger/cli/intro) section for guidance on how to install and configure the `fetchd` client and perform different operations within the ledger using the CLI.
-
-
-This documentation covers the things you need to know in order to prepare yourself and start developing on the ASI network.
-
-## Test networks
-
-The starting point for most users is [the test network ↗️](/references/ledger/active-networks#test-nets). Our test network (testnet) provides you with test tokens with no value, that you can safely experiment with through the [faucet ↗️](/guides/fetch-network/ledger/faucet).
-
-
- This documentation is currently under construction, and the content may not be up-to-date.
-
diff --git a/pages/concepts/fetch-network/ledger/validators.mdx b/pages/concepts/fetch-network/ledger/validators.mdx
deleted file mode 100644
index 168947ae2..000000000
--- a/pages/concepts/fetch-network/ledger/validators.mdx
+++ /dev/null
@@ -1,81 +0,0 @@
-import { Callout } from 'nextra/components'
-
-# Validators
-
-## Overview: blockchains, consensus and validators
-
-A **blockchain** is a series of data records that functions as a distributed, replicated digital ledger of transactions across a network of computer systems. On blockchains, the records of transactions are compiled into **blocks** which are linked together to form a chain. Thus, blockchains consists of a stable chain of blocks and each one of these blocks stores a list of previously confirmed transactions.
-
-These transactions take place inside a peer-to-peer (P2P) global network, thus, blockchains are considered minimize and immune to censorship. A blockchain network serves as a decentralized ledger since it is maintained by several computers located all over the world. This implies that each participant, namely a **node**, keeps a copy of the blockchain data and interacts with other participants to make sure that everyone is aware of the same information stored in the block.
-
-A blockchain, including the **Fetch.ai Ledger**, provides a secure and transparent way to record transactions, enabling trustless interactions between parties and removing the need for a central authority to overlook transactions.
-
-
- This is especially crucial in decentralized systems in which multiple parties need to engage in secure and verifiable transactions. Despite the absence of a central authority to confirm and authenticate the transactions, every blockchain transaction is considered totally safe and validated.
-
-
-Only the presence of a **consensus protocol** makes this feasible. A consensus algorithm allows every node in the blockchain network to agree on the distributed ledger's current state. The consensus protocol ensures that all nodes in the network reach a common agreement on the order and validity of transactions.
-
-More specifically, a **node** is any device or computer that participates in the network by maintaining a copy of the blockchain ledger, validating transactions, and broadcasting them to other nodes. Nodes can be categorized into different types, including **full** and **validator nodes**. These latter ones are specific type of node responsible for participating in the consensus process. These validate transactions, create new blocks, and contribute to the security and operation of the blockchain network. Validator nodes typically require a significant amount of cryptocurrency to be staked and which serves as collateral and as an incentive for them to act honestly.
-
-**The most well-known consensus mechanisms** are:
-
- - **Proof of Work (PoW)**: this is the original consensus protocol used by Bitcoin. It requires nodes (i.e. miners) to perform computationally intensive tasks to validate transactions and create new blocks. The first miner to solve the mathematical puzzle gets to add a block to the blockchain.
-
- - **Proof of Stake (PoS)**: in this protocol, nodes (i.e. validators) are chosen based on the amount of cryptocurrency they hold and are willing to stake as collateral. Validators take turns proposing and validating blocks, and they earn rewards for their participation in the form of transaction fees and block.
-
-**Compensation and incentives for validators** can take the form of:
-
- - **Block rewards**: in PoW and some PoS systems, validators are rewarded with newly created cryptocurrency tokens for successfully adding a new block to the blockchain.
-
- - **Transaction fees**: validators may receive transaction fees paid by users for including their transactions in a block.
-
- - **Delegation rewards**: in PoS networks, validators who receive delegated stakes from token holders may share a portion of the rewards with their delegators. This encourages token holders to delegate their stakes to reputable validators.
-
- - **Slashing penalties**: while not a form of compensation, validators can be penalized (i.e. slashed) for malicious behavior or violations of network rules. The penalties are typically deducted from the validator's committed stake.
-
-In this context, the Fetch.ai Ledger relies on a set of validators that are responsible for committing new blocks in the blockchain. These validators participate in the consensus protocol by broadcasting votes which contain cryptographic signatures signed by each validator's private key. As previously highlighted, validator candidates can have FET delegated or staked to them by token holders. The validators are determined by who has the most stake delegated to them. The top validator candidates with the most stake become **active validators** within the network.
-
-
- If validators double sign, are frequently offline or do not participate in governance, their staked FET (including FET of users that delegated to them) can be slashed. The penalty depends on the severity of the violation.
-
-
-### Test network (Testnet) vs Main Network (Mainnet)
-
-We can distinguish between:
-
- - **Testnet**: it is a separate blockchain environment that developers and users can use to test new features or applications without risking real tokens. It allows for experimentation in a controlled environment.
-
- - **Mainnet**: it is the actual production blockchain where real transactions occur with real tokens. It is the live version of the blockchain.
-
-
- By setting up and experimenting on a testnet first, developers can ensure that everything works as intended before deploying it on the mainnet. This helps in avoiding potential issues or vulnerabilities in a live environment.
-
-
-## Set up a validator node
-
-If you are willing to set up a validator node on the ASI network, visit our dedicated [guide ↗️](/guides/fetch-network/ledger/setup-validator-node).
-
-### Hardware requirements
-
-The hardware resources for running a validator node largely depend on the network load. As a _recommended configuration_, we suggest the following requirements:
-
- - 2 x CPU, either Intel or AMD, with the SSE4.1, SSE4.2 and AVX flags (use lscpu to verify).
- - 8 GB RAM.
- - 500 GB SSD.
- - 100 Mbit/s always-on internet connection.
- - Linux OS (Ubuntu 18.04 or 20.04 recommended)/MacOS.
-
-Up-time is incredibly important for being a validator. It is expected that validators will have appropriate redundancies for compute, power, connectivity and so on. While the blockchain itself is highly replicated, it is also expected that validators will perform local storage backups in order to minimize validator down-time.
-
-### Set up a website for your validator
-
-Set up a dedicated validator's website and signal your intention to become a validator on our [Discord ↗️](https://discord.gg/fetchai) server. This is important since delegators will want to have information about the entity they are delegating their FET to.
-
-This is not necessary, however, it is recommended given that as a validator on the network, you will want to get other community users to delegate stake to your validator. The higher the delegated stake to a specific validator, the greater the share of the block rewards it will take.
-
-## Community
-
-We highly recommend to check out the validator community on the discord channel for more information and to check the latest announcements about becoming a validator within the Fetch.ai network:
-
- - [Discord ↗️](https://discord.gg/fetchai).
diff --git a/pages/concepts/fetch-network/native-and-erc20-fet-tokens.mdx b/pages/concepts/fetch-network/native-and-erc20-fet-tokens.mdx
deleted file mode 100644
index 72e35bfa4..000000000
--- a/pages/concepts/fetch-network/native-and-erc20-fet-tokens.mdx
+++ /dev/null
@@ -1,11 +0,0 @@
-## Native and ERC-20 FET tokens
-
-The Fetch.ai (FET) token is the utility token and the key medium of exchange on the Fetch.ai network. FET can be used to pay for services in the ASI ecosystem and network transaction fees. Users can also choose to stake FET to participate in securing the network via its Proof-of-Stake (PoS) consensus mechanism and earn rewards in return for contributing to [validator ↗️](/concepts/fetch-network/ledger/validators) nodes.
-
-The Fetch.ai team initially developed the FET utility token on an [ERC-20 contract ↗️](https://etherscan.io/token/0xaea46A60368A7bD060eec7DF8CBa43b7EF41Ad85) on the Ethereum network while finishing the work on the Fetch.ai native main network (Main-net). This helped developers across the world get their hands on the FET tokens earlier and kickstart the process of developing innovative solutions within the ASI ecosystem. FET, as an ERC-20 token on the Ethereum contract has never been Fetch.ai's end game because the Ethereum chain does not offer the degree of scalability needed by the kinds of applications the ASI ecosystem aims for.
-
-With the launch of the Fetch.ai Mainnet, the native FET became available. This meant that users operating on the Fetch.ai network no longer needed to hold any token (e.g. ETH or BTC) associated with any other network. It is only the native FET token that fuels the ASI ecosystem and its applications.
-
-ERC-20 FET tokens are still in circulation and currently co-exist with native FET tokens and can be [transferred from one to the other ↗️](/guides/fetch-network/how-to-convert-fet-to-and-from-erc20) easily on the Fetch.ai network. All of the ERC-20 FET tokens will ultimately become native FET tokens, but in the foreseeable future both will live side by side. FET tokens can be purchased from different [centralized or decentralized exchanges ↗️](https://coinmarketcap.com/currencies/fetch/#Markets).
-
-However, keep in mind that certain exchanges may buy or sell one type of FET or the other.
diff --git a/pages/concepts/introducing-fetchai.mdx b/pages/concepts/introducing-fetchai.mdx
deleted file mode 100644
index c2ac3e2dc..000000000
--- a/pages/concepts/introducing-fetchai.mdx
+++ /dev/null
@@ -1,99 +0,0 @@
-import { ImageByTheme } from "../../components/mdx";
-import HighLevelDiagram from 'src/images/concepts/about/High-level-system-diagram.png';
-import DarkHighLevelDiagram from 'src/images/concepts/about/Dark-high-level-system-diagram.svg';
-import AgentsInteracting from 'src/images/concepts/ai-agents/Agents_interacting.png';
-import DarkAgentsInteracting from 'src/images/concepts/ai-agents/Dark_agents_interacting.svg';
-import DecentralisedNetwork from 'src/images/concepts/ai-agents/decentralised_network.png';
-import DarkDecentralisedNetwork from 'src/images/concepts/ai-agents/Dark_decentralised_network.svg';
-
-# Introducing Fetch.ai: pioneering an AI powered decentralized digital economy
-
-**Fetch.ai** is developing a platform to enable the development of an AI empowered decentralized digital economy. _Agents_ are programs that can make choices on their own for individuals, companies, and devices. Agents are the actors, and the heart of the ASI ecosystem.
-
-Agents are flexible problem solvers, capable of not just completing tasks but also tackling difficult issues across several domains. Agents have the adaptability to handle different activities inside the decentralized economy, whether it's improving supply chain logistics, maintaining solid record-keeping systems, executing computational tasks, or enabling buying and selling interactions. They might even book a hotel room for you.
-
-We couple agents with AI-Engine, the AI system that understands human input and turns that into actionable events empowered by agents in the network. AI-engine is an intelligence system which create dynamic agent workflows. Agentverse offers cheap agent hosting and the ASI Network provides an open layer of trust.
-
-These services make up the core architecture of Fetch.ai
-
-### The architecture
-
-**Agents**, **Agentverse**, **AI Engine**, and **ASI network**.
-
-Agents register to Almanac so that they can be discovered in the network by other agents. Agents may register their functions to Agentverse so that AI-Engine can index these agents so that they can be called by AI-Engine. The ASI network offers a layer of truth and trust by inherently being open.
-
-
-
-### Agents: the core
-
-**Agents** are programs designed to operate freely and communicate with whomever they're programmed to. Agents can connect, search, and transact in order to create dynamic markets, and they can be programmed with logic to interact both within their environment and with other agents in the network. Because they're siloed, and decentralized they can safely accomplish particular activities and objectives without requiring human participation. Our documentation gets your started on building an agent to be part [of the network ↗️](/guides/agents/getting-started/create-a-uagent)
-
-Agents can come together to become multi-agent workflows, single agents which call one another to complete a task. This can be done natively, or with AI-Engine.
-
-Agents are built with the **uAgents Framework**, a lightweight library designed to facilitate the development of decentralized **Agents**. At the uAgents core is an open sourced communication protocol for agents.
-
-
-
-Agents can fundamentally change the way we see complicated systems. For example, supply chain management could deploy Agents using the uAgents Framework to improve operations at various stages. Demand forecasting, inventory control, logistics optimization, supplier relationships monitoring, quality control and risk mitigation in all areas can be done with their help. Agents could transform supply chain operations by increasing efficiency, reducing costs, improving accuracy and providing real-time visibility.
-
-These agents are the building blocks that allow developers to gain access to the tools and resources provided by the uAgents Framework, enabling them to create and participate in intelligent and self-managed systems that can be used in various real-world domains.
-
-
-
-Agents can wrap and cannibalize LLMs to create personalized agents for any task. With the rise of Large Language Models (LLMs) and AI-related products, autonomous intelligent agents have become the link between these models and tools. They are revolutionizing the way we solve problems, make decisions and collaborate with each other.
-
-The concept of agents refers to autonomous, decentralized micro-systems that overcome conventional limitations. Agents provide a gateway to a future where intelligent agents alongside the ASI network and the [AI Engine ↗️](/concepts/ai-engine/ai-engine-intro), can communicate, negotiate and collaborate to streamline complex tasks, solve complicated problems and improve decision-making processes in various fields.
-
-### The Agentverse: your gateway to Agents
-
-The **Agentverse** is a Software as a Service (SaaS) platform built primarily for the creation and registration of Agents solutions. This platform enables the smooth deployment and management of agents, as well as their development and registration. This is an easy approach for managing and hosting your agents all in one place.
-
-The Agentverse provides multiple use cases ranging from simple "Hello World" to AI-driven recommendation systems. These use cases are only a click away from being edited, tweaked, and deployed for yourself.
-
-You can post your agent(s) and their functions on Agentverse so that the AI Engine can quickly find them and promote them to other users or agents via DeltaV.
-
-### DeltaV and the AI Engine: enabling user interactions
-
-**DeltaV** is a chat interface that acts as a link between users and registered agents in the Agentverse. It streamlines connections to these agents and wraps agent functions in a human-readable way, allowing everyone to easily obtain and query for different types of Functionalities. DeltaV is primarily a developer tool to interact with your deployed agents.
-
-The **AI Engine** is at the heart of DeltaV's functionalities; the AI Engine's aim is to parse, comprehend, and link human input to agents by facilitating natural language interactions. The AI Engine reads user inputs, converts them into actionable objectives, and selects the most suitable Agent registered in the Agentverse for objective task execution.
-
-### The Fetch.ai Network: the foundations
-
-The **Fetch.ai network** serves as the foundation of Fetch.ai's entire ecosystem, underpinning and empowering the functionalities of Agents, the Agentverse, DeltaV, and the AI Engine. This is the structural framework that enables the decentralized digital economy envisioned by Fetch.ai.
-
-The Fetch.ai network is composed of multiple essential elements; at the networks core is the [Almanac contract ↗️](/concepts/fetch-network/almanac), the [Fetch Name Service ↗️](/guides/agents/advanced/name-service), the [Fetch ledger ↗️](/concepts/fetch-network/ledger/intro), and the [FET Token ↗️](/concepts/fetch-network/native-and-erc20-fet-tokens). These web3 components are essential for a decentralized network for AI agents, and enable an easier path to developing your ideas and solutions and making them discoverable to a wider audience.
-
-At the heart of the Fetch.ai network lies the **Almanac contract**. It operates as a comprehensive repository, storing critical information about Agents, and it is crucial for the execution of various functionalities. The Almanac is a point of truth and a place to search for all registered agents. This contract enables the smooth exchange of data and ensures the efficient functioning of Agents within the ASI ecosystem.
-
-The **Fetch Name Service** works as a decentralized naming system which simplifies resource identification within the network. This service offers human-readable naming conventions and facilitates easy access and interaction with decentralized services and Agents.
-
-The backbone of Fetch.ai decentralized infrastructure is represented by the **Fetch ledger**. It acts as a secure and immutable record-keeping system and provides a transparent record of transactions, fostering trust and reliability across the network. The Fetch ledger supports the decentralized economy, ensuring secure data sharing and transactional integrity.
-
-The overall system we depicted runs on a specific fuel: **FET tokens**. These tokens hold intrinsic value and utility, drive transactions, promote active participation, and empower various decentralized services within the ASI network. FET serves as a medium of exchange and facilitates interactions among users, Agents, and Functions within the ASI ecosystem.
-
-### Next steps
-
-The foundational structure set by the ASI network serves as a launchpad for the creation, cooperation, and integration of the many tools and technologies available inside the ASI ecosystem. The integration of the Fetch.ai network with Agents, the Agentverse, and DeltaV propels the ASI ecosystem to propose a new paradigm in how operations are carried out and Agent functions are provided within a decentralized digital economy environment.
-
-This way, Fetch.ai presents a shift towards a future where the benefits of AI and technology are available to everybody!
-
-For a deeper dive into Fetch.ai's concepts, tools, and components building up this vision, have a look at the following resources:
-
- - [Agents ↗️](/concepts/agents/agents)
- - [The AI Engine ↗️](/concepts/ai-engine/ai-engine-intro)
- - [The Agentverse ↗️](/concepts/agent-services/agentverse-intro)
- - [DeltaV ↗️](/concepts/ai-engine/deltav)
- - [ASI Network ↗️](/concepts#fetch-network)
diff --git a/pages/examples.mdx b/pages/examples.mdx
deleted file mode 100644
index 256a960b9..000000000
--- a/pages/examples.mdx
+++ /dev/null
@@ -1,196 +0,0 @@
-# Examples
-
-
- Quick examples of complete Agents to get started quickly.
-
-
-import GuidesMdx from "../components/guide-mdx"
-import { AgentsIcon, LedgerIcon, AgentverseIcon} from "src/icons/main-page-icons";
-
-
-
diff --git a/pages/examples/DeltaV/_meta.json b/pages/examples/DeltaV/_meta.json
deleted file mode 100644
index 39f280b28..000000000
--- a/pages/examples/DeltaV/_meta.json
+++ /dev/null
@@ -1,12 +0,0 @@
-{
- "coin-toss": {
- "title": "Register a coin toss Agent as a Function [Intermediate]",
- "tags": ["Intermediate", "Python", "Functions", "DeltaV"],
- "timestamp": true
- },
- "news-reading-system": {
- "title": "Using News API to build network of Primary and Secondary functions [Advanced]",
- "tags": ["Intermediate", "Python", "Functions", "AI Engine"],
- "timestamp": true
- }
-}
diff --git a/pages/examples/DeltaV/coin-toss.mdx b/pages/examples/DeltaV/coin-toss.mdx
deleted file mode 100644
index d65a75f57..000000000
--- a/pages/examples/DeltaV/coin-toss.mdx
+++ /dev/null
@@ -1,137 +0,0 @@
-import { CodeGroup, DocsCode, GithubCodeSegment, CodeSegment } from "../../../components/code"
-
-# Register a coin toss agent as a Function
-
-## Introduction
-
-This file can be run on any platform supporting Python, with the necessary install permissions.
-To enable this on [DeltaV ↗️](/concepts/ai-engine/deltav) you will need to create and register a Function. You will need to run this file on a device you are able to open a port on.
-
-Please check out the example code in our [examples repo ↗️](https://github.com/fetchai/uAgent-Examples/tree/main/5-documentation/examples/intermediate/coin-toss) to run this locally.
-
-### Guide
-
-- [Register a coin toss agent as a Function ↗️](/guides/agentverse/agentverse-functions/registering-agent-coin-toss)
-
-### Supporting documentation
-
-- [Creating an agent ↗️](/guides/agents/create-a-uagent)
-
-- [Register in Almanac ↗️](/guides/agents/register-in-almanac)
-
-- [Almanac Contract ↗️](/references/contracts/uagents-almanac/almanac-overview)
-
-- [Protocols ↗️](/references/uagents/uagents-protocols/agent-protocols)
-
-- [Agentverse Functions ↗️](/concepts/agent-services/services)
-
-- [Register an Agent Function on the Agentverse ↗️](/guides/agentverse/registering-agent-services)
-
-### The agent
-
-
-
-
-
-
-
-
- ```py copy filename="agent.py"
-
- import random
- from uagents import Agent, Context, Model, Field, Protocol
- from uagents.setup import fund_agent_if_low
- from ai_engine import UAgentResponse, UAgentResponseType
-
-
- class CoinToss(Model):
- choice: str = Field(description="The choice. Must be heads or tails.")
-
- # 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!
- coin_toss_agent = Agent(
- name="coin_toss_agent",
- seed=SEED_PHRASE,
- mailbox=True
- )
-
- fund_agent_if_low(coin_toss_agent.wallet.address())
-
- # Copy the address shown below
- print(f"Your agent's address is: {coin_toss_agent.address}")
-
- coin_toss_protocol = Protocol("CoinToss")
-
-
- @coin_toss_protocol.on_message(model=CoinToss, replies={UAgentResponse})
- async def toss_coin(ctx: Context, sender: str, msg: CoinToss):
- random_number = random.randint(0, 1)
- if random_number == 0:
- coin_tossed = "heads"
- else:
- coin_tossed = "tails"
- if coin_tossed == msg.choice:
- message = "You won!"
- else:
- message = "You lost!"
- await ctx.send(
- sender, UAgentResponse(message=message, type=UAgentResponseType.FINAL)
- )
-
- coin_toss_agent.include(coin_toss_protocol, publish_manifest=True)
-
- if __name__ == "__main__":
- coin_toss_agent.run()
-
- ```
-
-
-
- ```py copy filename="agent.py"
-
- import random
- # third party modules used in this example
- from uagents import Field
- from ai_engine import UAgentResponse, UAgentResponseType
-
- class CoinToss(Model):
- choice: str = Field(description="The choice. Must be heads or tails.")
-
- coin_toss_protocol = Protocol("CoinToss")
-
- @coin_toss_protocol.on_message(model=CoinToss, replies={UAgentResponse})
- async def toss_coin(ctx: Context, sender: str, msg: CoinToss):
- random_number = random.randint(0, 1)
- if random_number == 0:
- coin_tossed = "heads"
- else:
- coin_tossed = "tails"
- if coin_tossed == msg.choice:
- message = "You won!"
- else:
- message = "You lost!"
- await ctx.send(
- sender, UAgentResponse(message=message, type=UAgentResponseType.FINAL)
- )
-
- agent.include(coin_toss_protocol, publish_manifest=True)
-
- ```
-
-
-
-
-
-
diff --git a/pages/examples/DeltaV/dice-roll.mdx b/pages/examples/DeltaV/dice-roll.mdx
deleted file mode 100644
index 81646a4d6..000000000
--- a/pages/examples/DeltaV/dice-roll.mdx
+++ /dev/null
@@ -1,123 +0,0 @@
-import { CodeGroup, DocsCode, GithubCodeSegment, CodeSegment } from "../../../components/code"
-
-# Register a dice roll Agent as a Function
-
-## Introduction
-
-This file can be run on any platform supporting Python, with the necessary install permissions.
-To enable this on [DeltaV ↗️](/concepts/ai-engine/deltav) you will need to create and register a Function. You will need to run this file on a device that can open a port.
-
-Please check out the example code in our [examples repo ↗️](https://github.com/fetchai/uAgent-Examples/tree/main/5-documentation/examples/intermediate/dice-roll) to run this locally.
-
-### Guide
-
-- [Register a dice roll agent as a Function ↗️](/guides/agentverse/creating-agentverse-agents/simple-dice-roll-agent)
-
-### Supporting documentation
-
-- [Creating an agent ↗️](/guides/agents/create-a-uagent)
-
-- [Register in Almanac ↗️](/guides/agents/register-in-almanac)
-
-- [Almanac Contract ↗️](/references/contracts/uagents-almanac/almanac-overview)
-
-- [Protocols ↗️](/references/uagents/uagents-protocols/agent-protocols)
-
-- [Agentverse Functions ↗️](/concepts/agent-services/services)
-
-- [Register an Agent Function on the Agentverse ↗️](/guides/agentverse/registering-agent-services)
-
-### The agent
-
-
-
-
-
-
-
-
- ```py copy filename="agent.py"
-
- import random
- from uagents import Agent, Context, Model, Field, Protocol
- from uagents.setup import fund_agent_if_low
- from ai_engine import UAgentResponse, UAgentResponseType
-
-
- class DiceRoll(Model):
- num_rolls: int = Field(description="Number of rolls.")
-
- # 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!
- dice_roll_agent = Agent(
- name="dice_roll_agent",
- seed=SEED_PHRASE,
- mailbox=True
- )
-
- fund_agent_if_low(dice_roll_agent.wallet.address())
-
- # Copy the address shown below
- print(f"Your agent's address is: {dice_roll_agent.address}")
-
- dice_roll_protocol = Protocol("DiceRoll")
-
-
- @dice_roll_protocol.on_message(model=DiceRoll, replies={UAgentResponse})
- async def roll_dice(ctx: Context, sender: str, msg: DiceRoll):
- result = ", ".join([str(random.randint(1, 6)) for _ in range(msg.num_rolls)])
- message = f"Dice roll results: {result}"
- await ctx.send(
- sender, UAgentResponse(message=message, type=UAgentResponseType.FINAL)
- )
-
- dice_roll_agent.include(dice_roll_protocol, publish_manifest=True)
-
- if __name__ == "__main__":
- dice_roll_agent.run()
-
- ```
-
-
-
- ```py copy filename="agent.py"
-
- import random
- # third party modules used in this example
- from uagents import Field
- from ai_engine import UAgentResponse, UAgentResponseType
-
- class DiceRoll(Model):
- num_rolls: int = Field(description="Number of rolls.")
-
- dice_roll_protocol = Protocol("DiceRoll")
-
- @dice_roll_protocol.on_message(model=DiceRoll, replies={UAgentResponse})
- async def roll_dice(ctx: Context, sender: str, msg: DiceRoll):
- result = ", ".join([str(random.randint(1, 6)) for _ in range(msg.num_rolls)])
- message = f"Dice roll results: {result}"
- await ctx.send(
- sender, UAgentResponse(message=message, type=UAgentResponseType.FINAL)
- )
-
- agent.include(dice_roll_protocol, publish_manifest=True)
-
- ```
-
-
-
-
-
-
diff --git a/pages/examples/DeltaV/news-reading-system.mdx b/pages/examples/DeltaV/news-reading-system.mdx
deleted file mode 100644
index 5d8852a20..000000000
--- a/pages/examples/DeltaV/news-reading-system.mdx
+++ /dev/null
@@ -1,811 +0,0 @@
-import { CodeGroup, DocsCode, GithubCodeSegment, CodeSegment } from "../../../components/code"
-
-# Using News API to build network of Primary and Secondary functions
-
-## Introduction
-
-This file can be run on any platform supporting Python, with the necessary install permissions. This system helps users to read news of different types including **Categorical**, **Country** based or **Keyword** related news. The system operates based on a multiple layers structure of primary and secondary functions, each one of them playing a vital role in delivering personalized news content to users.
-
-Please check out the example code in our [examples repo ↗️](https://github.com/fetchai/uAgent-Examples/tree/main/5-documentation/examples/intermediate/news-reading-system) to run this locally.
-
-#### Supporting documentation
-
-- [Creating an agent ↗️](/guides/agents/create-a-uagent)
-- [Register in Almanac ↗️](/guides/agents/register-in-almanac)
-- [Almanac Contract ↗️](/references/contracts/uagents-almanac/almanac-overview)
-- [Protocols ↗️](/references/uagents/uagents-protocols/agent-protocols)
-- [Agentverse Functions ↗️](/guides/services/services)
-- [Register an Agent Function on the Agentverse ↗️](/guides/agentverse/registering-agent-services)
-
-### The agents
-
-#### News Reading Agent
-
-
-
-
-
-
-
-
- ```py copy filename="agent.py"
-
-
- # Here we demonstrate how we can create a news reading system agent that is compatible with DeltaV
-
- # Import required libraries
- import requests
- import json
- from uagents import Agent, Context, Model, Field, Protocol
- from uagents.setup import fund_agent_if_low
- from ai_engine import UAgentResponse, UAgentResponseType
-
- # Define News Reading Model
- class News(Model):
- news : 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!
- news_agent = Agent(
- name="news_agent",
- seed=SEED_PHRASE,
- mailbox=True
- )
-
- fund_agent_if_low(news_agent.wallet.address())
-
- # Copy the address shown below
- print(f"Your agent's address is: {news_agent.address}")
-
- # Define Protocol for news reading system
- news_protocol = Protocol("News System")
-
- # Define a handler for the News system protocol
- @news_protocol.on_message(model=News, replies = UAgentResponse)
- async def on_news_request(ctx: Context, sender: str, msg: News):
- #splitting the news titles with nnn and enumerating them with line break for visually better results
- result_list = msg.news.split(" nnn ")
- final_news = '\n'.join([f"{i + 1}. {title}" for i, title in enumerate(result_list)])
- #Printing the news response on logger
- ctx.logger.info(f"Received news request from {sender} with prompt: {final_news}")
- #sending final response to the DeltaV GUI
- await ctx.send(sender, UAgentResponse(message = final_news, type = UAgentResponseType.FINAL))
-
-
- # Include the Generate News protocol in your agent
- news_agent.include(news_protocol)
-
- news_agent.run()
-
- ```
-
-
-
- ```py copy filename="agent.py"
-
- # Here we demonstrate how we can create a news reading system agent that is compatible with DeltaV
-
- # After running this agent, it can be registered to DeltaV on Agentverse My Agents tab. For registration you will have to use the agent's address
-
- # Import required libraries
- import requests
- import json
- from ai_engine import UAgentResponse, UAgentResponseType
-
- # Define News Reading Model
- class News(Model):
- news : str
-
- # Define Protocol for news reading system
- news_protocol = Protocol("News System")
-
- # Define a handler for the News system protocol
- @news_protocol.on_message(model=News, replies = UAgentResponse)
- async def on_news_request(ctx: Context, sender: str, msg: News):
- #splitting the news titles with nnn and enumerating them with line break for visually better results
- result_list = msg.news.split(" nnn ")
- final_news = '\n'.join([f"{i + 1}. {title}" for i, title in enumerate(result_list)])
- #Printing the news response on logger
- ctx.logger.info(f"Received news request from {sender} with prompt: {final_news}")
- #sending final response to the DeltaV GUI
- await ctx.send(sender, UAgentResponse(message = final_news, type = UAgentResponseType.FINAL))
-
- # Include the Generate News protocol in your agent
- agent.include(news_protocol)
-
- ```
-
-
-
-
-
-
-#### News Generating Agent
-
-
-
-
-
-
-
-
- ```py copy filename="agent.py"
-
- # Here we demonstrate how we can create a news generating agent that is compatible with DeltaV.
-
- # Import required libraries
- import requests
- import json
- from uagents import Agent, Context, Model, Field, Protocol
- from uagents.setup import fund_agent_if_low
- from ai_engine import UAgentResponse, UAgentResponseType
-
- # Define News Generating Model.
- class GenerateNews(Model):
- news_type: str
- news : 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!
- generate_news_agent = Agent(
- name="generate_news_agent",
- seed=SEED_PHRASE,
- mailbox=True
- )
-
- fund_agent_if_low(generate_news_agent.wallet.address())
-
- # Copy the address shown below
- print(f"Your agent's address is: {generate_news_agent.address}")
-
- # Define Generate news protocol.
- generate_news_protocol = Protocol("Generate News")
-
-
- # Define a handler for the News generation protocol
- @generate_news_protocol.on_message(model=GenerateNews, replies=UAgentResponse)
- async def on_generate_news_request(ctx: Context, sender: str, msg: GenerateNews):
- try:
- # Generate news based on the requested category.
- ctx.logger.info('Generating News')
- ctx.logger.info(f'User have selected {msg.news_type} category')
-
- ctx.logger.info(f'Generate News \n {msg.news}')
- message = msg.news
-
- # Send a successful response with the generated news.
- await ctx.send(
- sender,
- UAgentResponse(
- message= message,
- type=UAgentResponseType.FINAL
- )
- )
-
- # Handle any exceptions that occur during news generation.
- except Exception as exc:
- ctx.logger.error(f"Error in generating news: {exc}")
-
- # Send an error response with details of the encountered error.
- await ctx.send(
- sender,
- UAgentResponse(
- message=f"Error in generating news: {exc}",
- type=UAgentResponseType.ERROR
- )
- )
-
- # Include the Generate News protocol in your agent.
- generate_news_agent.include(generate_news_protocol)
-
- generate_news_agent.run()
-
- ```
-
-
-
- ```py copy filename="agent.py"
-
- # Here we demonstrate how we can create a news generating agent that is compatible with DeltaV.
- # After running this agent, it can be registered to DeltaV on Agentverse My Agents tab. For registration you will have to use the agent's address.
-
- # Import required libraries
- import requests
- import json
- from ai_engine import UAgentResponse, UAgentResponseType
-
- # Define News Generating Model.
- class GenerateNews(Model):
- news_type: str
- news : str
-
- # Define Generate news protocol.
- generate_news_protocol = Protocol("Generate News")
-
- # Define a handler for the News generation protocol
- @generate_news_protocol.on_message(model=GenerateNews, replies=UAgentResponse)
- async def on_generate_news_request(ctx: Context, sender: str, msg: GenerateNews):
- try:
- # Generate news based on the requested category.
- ctx.logger.info('Generating News')
- ctx.logger.info(f'User have selected {msg.news_type} category')
-
- ctx.logger.info(f'Generate News \n {msg.news}')
- message = msg.news
-
- # Send a successful response with the generated news.
- await ctx.send(
- sender,
- UAgentResponse(
- message= message,
- type=UAgentResponseType.FINAL
- )
- )
-
- # Handle any exceptions that occur during news generation.
- except Exception as exc:
- ctx.logger.error(f"Error in generating news: {exc}")
-
- # Send an error response with details of the encountered error.
- await ctx.send(
- sender,
- UAgentResponse(
- message=f"Error in generating news: {exc}",
- type=UAgentResponseType.ERROR
- )
- )
-
- # Include the Generate News protocol in your agent.
- agent.include(generate_news_protocol)
-
- ```
-
-
-
-
-
-
-#### Generate Categorical News
-
-
-
-
-
-
-
-
- ```py copy filename="agent.py"
-
- # Here we demonstrate how we can create a categorical news generating agent that is compatible with DeltaV.
-
- # Importing libraries
- import requests
- import json
- from uagents import Agent, Context, Model, Field, Protocol
- from uagents.setup import fund_agent_if_low
- from ai_engine import UAgentResponse, UAgentResponseType
-
- # Define the Generate News model.
- class GenerateNews(Model):
- category: 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!
- generate_cat_news_agent = Agent(
- name="generate_cat_news_agent",
- seed=SEED_PHRASE,
- mailbox=True
- )
-
- fund_agent_if_low(generate_cat_news_agent.wallet.address())
-
- # Copy the address shown below
- print(f"Your agent's address is: {generate_cat_news_agent.address}")
-
- # Define protocol for categorical news generation.
- generate_cat_news_protocol = Protocol("Generate Categorical News")
-
- # Define function to generate news according to category in great britain - GB.
- async def generate_news(category):
- api_key = 'YOUR_NEWS_API_KEY'
- main_url = f"https://newsapi.org/v2/top-headlines?country=gb&category={category}&apiKey={api_key}"
- news = requests.get(main_url).json()
- #strip the source, get top 10 news and join the list with ' nnn ' to return the news as string and not list (DeltaV compatible type)
- titles = [article['title'].split(' - ')[0].strip() for article in news['articles']]
- titles = titles[:10]
- results = ' nnn '.join([f"{title}" for title in titles])
-
- return results
-
- # Define a handler for the Categorical News generation protocol.
- @generate_cat_news_protocol.on_message(model=GenerateNews, replies=UAgentResponse)
- async def on_generate_news_request(ctx: Context, sender: str, msg: GenerateNews):
- #Logging category of news user wants to read
- ctx.logger.info(f"Received ticket request from {sender} with prompt: {msg.category}")
- try:
- # Generate news based on the requested category.
- news = generate_news(msg.category)
- #logging news
- ctx.logger.info(news)
- message = str(news)
- # Send a successful response with the generated news.
- await ctx.send(sender, UAgentResponse(message = message, type = UAgentResponseType.FINAL))
-
- # Handle any exceptions that occur during news generation.
- except Exception as exc:
- ctx.logger.error(f"Error in generating News: {exc}")
- # Send an error response with details of the encountered error.
- await ctx.send(
- sender,
- UAgentResponse(
- message=f"Error in generating News: {exc}",
- type=UAgentResponseType.ERROR
- )
- )
-
-
- # Include the Generate News protocol in your agent.
- generate_cat_news_agent.include(generate_cat_news_protocol)
-
- generate_cat_news_agent.run()
-
- ```
-
-
-
- ```py copy filename="agent.py"
-
- # Here we demonstrate how we can create a categorical news generating agent that is compatible with DeltaV.
- # After running this agent, it can be registered to DeltaV on Agentverse My Agents tab. For registration you will have to use the agent's address.
-
- # Importing libraries
- import requests
- import json
- from ai_engine import UAgentResponse, UAgentResponseType
-
- # Define the Generate News model.
- class GenerateNews(Model):
- category: str
-
- # Define protocol for categorical news generation.
- generate_cat_news_protocol = Protocol("Generate Categorical News")
-
- # Define function to generate news according to category in great britain - GB.
- async def generate_news(category):
- api_key = 'YOUR_NEWS_API_KEY'
- main_url = f"https://newsapi.org/v2/top-headlines?country=gb&category={category}&apiKey={api_key}"
- news = requests.get(main_url).json()
- #strip the source, get top 10 news and join the list with ' nnn ' to return the news as string and not list (DeltaV compatible type)
- titles = [article['title'].split(' - ')[0].strip() for article in news['articles']]
- titles = titles[:10]
- results = ' nnn '.join([f"{title}" for title in titles])
-
- return results
-
- # Define a handler for the Categorical News generation protocol.
- @generate_cat_news_protocol.on_message(model=GenerateNews, replies=UAgentResponse)
- async def on_generate_news_request(ctx: Context, sender: str, msg: GenerateNews):
- #Logging category of news user wants to read
- ctx.logger.info(f"Received ticket request from {sender} with prompt: {msg.category}")
- try:
- # Generate news based on the requested category.
- news = generate_news(msg.category)
- #logging news
- ctx.logger.info(news)
- message = str(news)
- # Send a successful response with the generated news.
- await ctx.send(sender, UAgentResponse(message = message, type = UAgentResponseType.FINAL))
-
- # Handle any exceptions that occur during news generation.
- except Exception as exc:
- ctx.logger.error(f"Error in generating News: {exc}")
- # Send an error response with details of the encountered error.
- await ctx.send(
- sender,
- UAgentResponse(
- message=f"Error in generating News: {exc}",
- type=UAgentResponseType.ERROR
- )
- )
-
- # Include the Generate News protocol in your agent.
- agent.include(generate_cat_news_protocol)
-
- ```
-
-
-
-
-
-
-#### Generate Regional News
-
-
-
-
-
-
-
-
- ```py copy filename="agent.py"
-
- # Import libraries
- import requests
- import json
- from uagents import Agent, Context, Model, Field, Protocol
- from uagents.setup import fund_agent_if_low
- from ai_engine import UAgentResponse, UAgentResponseType
-
- # Define dictionary with country codes
- country_codes = {
- "argentina": "ar", "australia": "au", "austria": "at", "belgium": "be",
- "bulgaria": "bg", "brazil": "br", "canada": "ca", "china": "cn",
- "colombia": "co", "cuba": "cu", "czech republic": "cz", "germany": "de",
- "egypt": "eg", "france": "fr", "united kingdom": "gb", "greece": "gr",
- "hong kong": "hk", "hungary": "hu", "indonesia": "id", "ireland": "ie",
- "israel": "il", "india": "in", "italy": "it", "japan": "jp",
- "south korea": "kr", "lithuania": "lt", "latvia": "lv", "morocco": "ma",
- "mexico": "mx", "malaysia": "my", "nigeria": "ng", "netherlands": "nl",
- "norway": "no", "new zealand": "nz", "philippines": "ph", "poland": "pl",
- "portugal": "pt", "romania": "ro", "serbia": "rs", "russia": "ru",
- "saudi arabia": "sa", "sweden": "se", "singapore": "sg", "slovenia": "si",
- "slovakia": "sk", "thailand": "th", "turkey": "tr", "taiwan": "tw",
- "ukraine": "ua", "united states": "us", "venezuela": "ve", "south africa": "za"
- }
-
- # Define the Generate News model
- class GenerateNews(Model):
- country: 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!
- generate_news_reg_agent = Agent(
- name="generate_news_reg_agent",
- seed=SEED_PHRASE,
- mailbox=True
- )
-
- fund_agent_if_low(generate_news_reg_agent.wallet.address())
-
- # Copy the address shown below
- print(f"Your agent's address is: {generate_news_reg_agent.address}")
-
- # Define function to generate regional news according to country
- async def get_regional_news(country):
- api_key = 'YOUR_API_KEY'
- main_url = f"https://newsapi.org/v2/top-headlines?country={country_codes.get(country.lower())}&apiKey={api_key}"
- news = requests.get(main_url).json()
- # Strip the source, get top 10 news and join the list with nnn to return the news as string and not list - DeltaV compatible type
- titles = [article['title'].split(' - ')[0].strip()for article in news['articles']]
- titles = titles[:10]
- results = ' nnn '.join([f"{title}" for title in titles])
-
- return results
-
- # Define protocol for regional news generation Protocol
- generate_news_reg_protocol = Protocol("Generate Regional News")
-
- # Define a handler for the Regional News generation protocol
- @generate_news_reg_protocol.on_message(model=GenerateNews, replies=UAgentResponse)
- async def on_generate_news_request(ctx: Context, sender: str, msg: GenerateNews):
-
- ctx.logger.info(f"Received ticket request from {sender} with prompt: {msg.country}")
- try:
- # Get the country code from the country_code dictionary
- country_code = country_codes.get(msg.country.lower())
- # Generate news based on the requested country and log it on agentverse
- message = await get_regional_news(msg.country)
- ctx.logger.info(f"Message from endpoint: {message}")
- # Send a successful response with the generated news
- await ctx.send(sender, UAgentResponse(message=message, type=UAgentResponseType.FINAL))
- # Handle any exceptions that occur during news generation
- except Exception as exc:
- ctx.logger.error(f"Error in generating News: {exc}")
- # Send an error response with details of the encountered error
- await ctx.send(
- sender,
- UAgentResponse(
- message=f"Error in generating News: {exc}",
- type=UAgentResponseType.ERROR
- )
- )
-
-
- # Include the Generate Regional News protocol in your agent
- generate_news_reg_agent.include(generate_news_protocol)
-
- generate_news_reg_agent.run()
-
- ```
-
-
-
- ```py copy filename="agent.py"
-
- # Import libraries
- import requests
- import json
- from ai_engine import UAgentResponse, UAgentResponseType
-
- # Define dictionary with country codes
- country_codes = {
- "argentina": "ar", "australia": "au", "austria": "at", "belgium": "be",
- "bulgaria": "bg", "brazil": "br", "canada": "ca", "china": "cn",
- "colombia": "co", "cuba": "cu", "czech republic": "cz", "germany": "de",
- "egypt": "eg", "france": "fr", "united kingdom": "gb", "greece": "gr",
- "hong kong": "hk", "hungary": "hu", "indonesia": "id", "ireland": "ie",
- "israel": "il", "india": "in", "italy": "it", "japan": "jp",
- "south korea": "kr", "lithuania": "lt", "latvia": "lv", "morocco": "ma",
- "mexico": "mx", "malaysia": "my", "nigeria": "ng", "netherlands": "nl",
- "norway": "no", "new zealand": "nz", "philippines": "ph", "poland": "pl",
- "portugal": "pt", "romania": "ro", "serbia": "rs", "russia": "ru",
- "saudi arabia": "sa", "sweden": "se", "singapore": "sg", "slovenia": "si",
- "slovakia": "sk", "thailand": "th", "turkey": "tr", "taiwan": "tw",
- "ukraine": "ua", "united states": "us", "venezuela": "ve", "south africa": "za"
- }
-
- # Define the Generate News model
- class GenerateNews(Model):
- country: str
-
- # Define function to generate regional news according to country
- async def get_regional_news(country):
- api_key = 'YOUR_API_KEY'
- main_url = f"https://newsapi.org/v2/top-headlines?country={country_codes.get(country.lower())}&apiKey={api_key}"
- news = requests.get(main_url).json()
- # Strip the source, get top 10 news and join the list with nnn to return the news as string and not list - DeltaV compatible type
- titles = [article['title'].split(' - ')[0].strip()for article in news['articles']]
- titles = titles[:10]
- results = ' nnn '.join([f"{title}" for title in titles])
-
- return results
-
- # Define protocol for regional news generation Protocol
- generate_news_reg_protocol = Protocol("Generate Regional News")
-
- # Define a handler for the Regional News generation protocol
- @generate_news_reg_protocol.on_message(model=GenerateNews, replies=UAgentResponse)
- async def on_generate_news_request(ctx: Context, sender: str, msg: GenerateNews):
-
- ctx.logger.info(f"Received ticket request from {sender} with prompt: {msg.country}")
- try:
- # Get the country code from the country_code dictionary
- country_code = country_codes.get(msg.country.lower())
- # Generate news based on the requested country and log it on agentverse
- message = await get_regional_news(msg.country)
- ctx.logger.info(f"Message from endpoint: {message}")
- # Send a successful response with the generated news
- await ctx.send(sender, UAgentResponse(message=message, type=UAgentResponseType.FINAL))
- # Handle any exceptions that occur during news generation
- except Exception as exc:
- ctx.logger.error(f"Error in generating News: {exc}")
- # Send an error response with details of the encountered error
- await ctx.send(
- sender,
- UAgentResponse(
- message=f"Error in generating News: {exc}",
- type=UAgentResponseType.ERROR
- )
- )
-
- # Include the Generate Regional News protocol in your agent
- agent.include(generate_news_protocol)
-
- ```
-
-
-
-
-
-
-#### Generate Keyword News
-
-
-
-
-
-
-
-
- ```py copy filename="agent.py"
-
- # Import libraries
- import requests
- from uagents import Agent, Context, Model, Field, Protocol
- from uagents.setup import fund_agent_if_low
- import json
- from ai_engine import UAgentResponse, UAgentResponseType
-
- # Define the Generate News model
- class GenerateNews(Model):
- keyword: 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!
- generate_news_keyw_agent = Agent(
- name="generate_news_keyw_agent",
- seed=SEED_PHRASE,
- mailbox=True
- )
-
- fund_agent_if_low(generate_news_keyw_agent.wallet.address())
-
- # Copy the address shown below
- print(f"Your agent's address is: {generate_news_keyw_agent.address}")
-
- # Define protocol for keyword news generation
- generate_news_keyw_protocol = Protocol("Generate Keyword News")
-
- # Define function to generate news according to keyword
- async def get_keyword_news(keyword):
-
- api_key = 'YOUR_API_KEY'
- main_url = f"https://newsapi.org/v2/top-headlines?q={keyword}&apiKey={api_key}"
- news = requests.get(main_url).json()
- # Strip the source, get top 10 news and join the list with nnn to return the news as string and not list - DeltaV compatible type
- titles = [article['title'].split(' - ')[0].strip() for article in news['articles']]
- titles = titles[:10]
- results = ' nnn '.join([f"{title}" for title in titles])
-
- # Define a handler for the Keyword News generation protocol
- @generate_news_keyw_protocol.on_message(model=GenerateNews, replies=UAgentResponse)
- async def on_generate_news_request(ctx: Context, sender: str, msg: GenerateNews):
-
- ctx.logger.info(f"Received news request from {sender} with prompt: {msg.keyword}")
- # Generate news based on the requested keyword
- try:
- news = get_keyword_news(msg.keyword)
- # Send a successful response with the generated news
- await ctx.send(
- sender,
- UAgentResponse(
- message=news,
- type=UAgentResponseType.FINAL
- )
- )
-
- # Handle any exceptions that occur during news generation
- except Exception as exc:
- ctx.logger.error(f"Error in generating News: {exc}")
- # Send an error response with details of the encountered error
- await ctx.send(
- sender,
- UAgentResponse(
- message=f"Error in generating News: {exc}",
- type=UAgentResponseType.ERROR
- )
- )
-
- # Include the Generate Keyword News protocol in your agent
- generate_news_keyw_agent.include(generate_news_keyw_protocol)
-
- generate_news_keyw_agent.run()
-
- ```
-
-
-
- ```py copy filename="agent.py"
-
- # Import libraries
- import requests
- import json
- from ai_engine import UAgentResponse, UAgentResponseType
-
- # Define the Generate News model
- class GenerateNews(Model):
- keyword: str
-
- # Define protocol for keyword news generation
- generate_news_keyw_protocol = Protocol("Generate Keyword News")
-
- # Define function to generate news according to keyword
- async def get_keyword_news(keyword):
-
- api_key = 'YOUR_API_KEY'
- main_url = f"https://newsapi.org/v2/top-headlines?q={keyword}&apiKey={api_key}"
- news = requests.get(main_url).json()
- # Strip the source, get top 10 news and join the list with nnn to return the news as string and not list - DeltaV compatible type
- titles = [article['title'].split(' - ')[0].strip() for article in news['articles']]
- titles = titles[:10]
- results = ' nnn '.join([f"{title}" for title in titles])
-
- # Define a handler for the Keyword News generation protocol
- @generate_news_keyw_protocol.on_message(model=GenerateNews, replies=UAgentResponse)
- async def on_generate_news_request(ctx: Context, sender: str, msg: GenerateNews):
-
- ctx.logger.info(f"Received news request from {sender} with prompt: {msg.keyword}")
- # Generate news based on the requested keyword
- try:
- news = get_keyword_news(msg.keyword)
- # Send a successful response with the generated news
- await ctx.send(
- sender,
- UAgentResponse(
- message=news,
- type=UAgentResponseType.FINAL
- )
- )
-
- # Handle any exceptions that occur during news generation
- except Exception as exc:
- ctx.logger.error(f"Error in generating News: {exc}")
- # Send an error response with details of the encountered error
- await ctx.send(
- sender,
- UAgentResponse(
- message=f"Error in generating News: {exc}",
- type=UAgentResponseType.ERROR
- )
- )
-
- # Include the Generate Keyword News protocol in your agent
- agent.include(generate_news_keyw_protocol)
-
- ```
-
-
-
-
-
-
diff --git a/pages/examples/_meta.json b/pages/examples/_meta.json
deleted file mode 100644
index 3d3d9dea9..000000000
--- a/pages/examples/_meta.json
+++ /dev/null
@@ -1,50 +0,0 @@
-{
- "agent": {
- "title": "Agents",
- "theme": {
- "collapsed": false
- }
- },
- "rag": {
- "title": "RAG examples",
- "theme": {
- "collapsed": false
- }
- },
- "examplestech": {
- "title": "Examples with other Tech",
- "theme": {
- "collapsed": false
- }
- },
- "agentverse": {
- "title": "Agentverse",
- "theme": {
- "collapsed": false
- }
- },
- "dialogues": {
- "title": "Dialogues",
- "theme": {
- "collapsed": false
- }
- },
- "agentverse-api": {
- "title": "Agentverse API",
- "theme": {
- "collapsed": false
- }
- },
- "DeltaV": {
- "title": "DeltaV",
- "theme": {
- "collapsed": false
- }
- },
- "ai-engine-api": {
- "title": "AI-Engine API",
- "theme": {
- "collapsed": false
- }
- }
-}
diff --git a/pages/examples/agent/_meta.json b/pages/examples/agent/_meta.json
deleted file mode 100644
index dedc635c8..000000000
--- a/pages/examples/agent/_meta.json
+++ /dev/null
@@ -1,109 +0,0 @@
-{
- "first-agent": {
- "title": "Create your first agent [easy]",
- "tags": ["Agents", "Beginner", "Installation"],
- "timestamp": true
- },
- "agents-interval-task": {
- "title": "Interval task with Agents [easy]",
- "tags": ["Intermediate", "Python", "Handlers", "Use Cases"],
- "timestamp": true
- },
- "local-communication": {
- "title": "Local Network communication [easy]",
- "tags": ["Intermediate", "Python", "Communication", "Use Cases"],
- "timestamp": true
- },
- "simple-agent-communication-with-bureau": {
- "title": "Bureau Agents communication [easy]",
- "tags": ["Intermediate", "Python", "Communication", "Use Cases"],
- "timestamp": true
- },
- "storage": {
- "title": "Agents storage [easy]",
- "tags": ["Intermediate", "Python", "Storage", "Use Cases"],
- "timestamp": true
- },
- "broadcast": {
- "title": "Agents Broadcast [intermediate]",
- "tags": ["Intermediate", "Python", "Communication", "Use Cases"],
- "timestamp": true
- },
- "multiple-agents": {
- "title": "Multiple agents communication [intermediate]",
- "tags": ["Intermediate", "Python", "Communication", "Use Cases"],
- "timestamp": true
- },
- "on-query": {
- "title": "Query an agent using a proxy API [intermediate]",
- "tags": ["Intermediate", "Python", "Communication", "FastAPI", "Proxy"],
- "timestamp": true
- },
- "on_query_example": {
- "title": "Shopping Assistance Agent using on_query [intermediate]",
- "tags": ["Intermediate", "Python", "Functions", "OpenAI", "Use Cases"],
- "timestamp": true
- },
- "table-booking-demo": {
- "title": "Table booking service with Agents [intermediate]",
- "tags": ["Intermediate", "Python", "Use Cases"],
- "timestamp": true
- },
- "agents-cleaning-demo": {
- "title": "Cleaning service with Agents [intermediate]",
- "tags": ["Intermediate", "Python", "Use Cases"],
- "timestamp": true
- },
- "send-tokens-agents": {
- "title": "Send tokens with Agents [intermediate]",
- "tags": ["Intermediate", "Python", "Use Cases"],
- "timestamp": true
- },
- "verify-messages": {
- "title": "Verify messages with Agents [intermediate]",
- "tags": ["Intermediate", "Python", "Communication", "Use Cases"],
- "timestamp": true
- },
- "wallet-messaging": {
- "title": "Communicating with other agents wallet [intermediate]",
- "tags": ["Intermediate", "Python", "Communication", "Wallet"],
- "timestamp": true
- },
- "on-query": {
- "title": "On Query decorator example [intermediate]",
- "tags": ["Intermediate", "Python", "Handlers", "Use Cases"],
- "timestamp": true
- },
- "sending-and-verifying-token-transactions-with-agent": {
- "title": "Sending and verifying token transactions with agent [intermediate]",
- "tags": [
- "Intermediate",
- "Python",
- "Web3",
- "Token",
- "Blockchain",
- "Use Cases"
- ],
- "timestamp": true
- },
- "staking-and-unstaking-with-an-agent": {
- "title": "Staking and Unstaking with agent [Intermediate]",
- "tags": ["Intermediate", "Python", "Web3", "Token", "Blockchain"],
- "timestamp": true
- },
- "async-loops": {
- "title": "Asynchronous Loops [Advanced]",
- "tags": ["Advanced", "Python", "Communication", "Use Cases"],
- "timestamp": true
- },
- "agents-with-docker": {
- "title": "Running an Agent with Docker [Intermediate]",
- "tags": ["Intermediate", "Python", "Docker", "Use Cases"],
- "timestamp": true
- },
- "search-example": {
- "title": "Search Agents [Intermediate]",
- "tags": ["Intermediate", "Python", "Search Apis"],
- "timestamp": true
- }
-}
diff --git a/pages/examples/agent/agents-cleaning-demo.mdx b/pages/examples/agent/agents-cleaning-demo.mdx
deleted file mode 100644
index bedc040af..000000000
--- a/pages/examples/agent/agents-cleaning-demo.mdx
+++ /dev/null
@@ -1,481 +0,0 @@
-import { CodeGroup, DocsCode, GithubCodeSegment, CodeSegment } from "../../../components/code"
-
-# Cleaning service with Agents
-
-## Introduction
-
-This file can be run on any platform supporting Python, with the necessary install permissions.
-This example shows how to set up a cleaning service using the uAgents library tools.
-
-Please check out the example code in our [examples repo ↗️](https://github.com/fetchai/uAgent-Examples/tree/main/5-documentation/examples/intermediate/agents-cleaning-demo) to run this locally.
-
-### Supporting documentation
-
-- [Creating an agent ↗️](/guides/agents/create-a-uagent)
-- [Creating an interval task ↗️](/guides/agents/interval-task)
-- [Communicating with other agents ↗️](/guides/agents/communicating-with-other-agents)
-- [Register in Almanac ↗️](/guides/agents/register-in-almanac)
-- [Almanac Contract ↗️](/references/contracts/uagents-almanac/almanac-overview)
-- [Protocols ↗️](/references/uagents/uagents-protocols/agent-protocols)
-- [Agents address ↗️](/guides/agents/getting-started/getting-uagent-address)
-- [How to use agents to send tokens ↗️](/guides/agents/intermediate/send-tokens)
-
-## Pre-requisites
-
-- **Python:** Download and install from [Python official website ↗️](https://www.python.org/downloads/).
-- **Poetry:** Install by following the instructions on [Poetry's official website ↗️](https://python-poetry.org/docs/#installation).
-
-## Project Structure
-
-Outline of basic structure of the project:
-
-```
-cleaning-demo/
-.
-├── protocols/
-│ └── cleaning/
-│ ├── __init__.py
-│ └── models.py
-│
-└── agents/
- ├── cleaner.py
- └── user.py
-```
-
-### The Protocols
-#### __init__.py
-
-This protocol acts as a bridge between cleaning service providers and users requesting cleaning services.
-
-The protocol defines the format for messages exchanged between the two parties. Users send `ServiceRequest` messages specifying details about their desired cleaning service, including location, time, duration, types of services needed, and their maximum budget. Providers respond with `ServiceResponse` messages indicating whether they can accept the request and, if so, their proposed price. Once a user confirms the booking with a `ServiceBooking` message containing all the agreed-upon details and price, the provider sends a `BookingResponse` message to confirm success or failure.
-
-The protocol ensures the provider's services are available to the user's location. It uses the `geopy` library to calculate the distance between the user and the provider. Additionally, it verifies if the requested cleaning services are offered by the provider and if the desired cleaning time falls within the provider's pre-defined availability schedule. Finally, it compares the user's budget with the provider's minimum hourly price multiplied by the cleaning duration to ensure affordability.
-
-Here is the full code:
-
-
-
-
-
-
-
- ```py copy filename="__init__.py"
-
- from datetime import datetime, timedelta
- from typing import List
-
- from geopy.distance import geodesic
- from geopy.geocoders import Nominatim
- from uagents import Context, Model, Protocol
-
- from .models import Availability, Provider, User
-
- PROTOCOL_NAME = "cleaning"
- PROTOCOL_VERSION = "0.1.0"
-
-
- class ServiceRequest(Model):
- user: str
- location: str
- time_start: datetime
- duration: timedelta
- services: List[int]
- max_price: float
-
-
- class ServiceResponse(Model):
- accept: bool
- price: float
-
-
- class ServiceBooking(Model):
- location: str
- time_start: datetime
- duration: timedelta
- services: List[int]
- price: float
-
-
- class BookingResponse(Model):
- success: bool
-
-
- cleaning_proto = Protocol(name=PROTOCOL_NAME, version=PROTOCOL_VERSION)
-
-
- def in_service_region(
- location: str, availability: Availability, provider: Provider
- ) -> bool:
- geolocator = Nominatim(user_agent="micro_agents")
-
- user_location = geolocator.geocode(location)
- cleaner_location = geolocator.geocode(provider.location)
-
- if user_location is None:
- raise RuntimeError(f"user location {location} not found")
-
- if cleaner_location is None:
- raise RuntimeError(f"provider location {provider.location} not found")
-
- cleaner_coordinates = (cleaner_location.latitude, cleaner_location.longitude)
- user_coordinates = (user_location.latitude, user_location.longitude)
-
- service_distance = geodesic(user_coordinates, cleaner_coordinates).miles
- in_range = service_distance <= availability.max_distance
-
- return in_range
-
-
- @cleaning_proto.on_message(model=ServiceRequest, replies=ServiceResponse)
- async def handle_query_request(ctx: Context, sender: str, msg: ServiceRequest):
- provider = await Provider.filter(name=ctx.agent.name).first()
- availability = await Availability.get(provider=provider)
- services = [int(service.type) for service in await provider.services]
- markup = provider.markup
-
- user, _ = await User.get_or_create(name=msg.user, address=sender)
- msg_duration_hours: float = msg.duration.total_seconds() / 3600
- ctx.logger.info(f"Received service request from user `{user.name}`")
-
- if (
- set(msg.services) <= set(services)
- and in_service_region(msg.location, availability, provider)
- and availability.time_start <= msg.time_start
- and availability.time_end >= msg.time_start + msg.duration
- and availability.min_hourly_price * msg_duration_hours < msg.max_price
- ):
- accept = True
- price = markup * availability.min_hourly_price * msg_duration_hours
- ctx.logger.info(f"I am available! Proposing price: {price}.")
- else:
- accept = False
- price = 0
- ctx.logger.info("I am not available. Declining request.")
-
- await ctx.send(sender, ServiceResponse(accept=accept, price=price))
-
-
- @cleaning_proto.on_message(model=ServiceBooking, replies=BookingResponse)
- async def handle_book_request(ctx: Context, sender: str, msg: ServiceBooking):
- provider = await Provider.filter(name=ctx.agent.name).first()
- availability = await Availability.get(provider=provider)
- services = [int(service.type) for service in await provider.services]
-
- user = await User.get(address=sender)
- msg_duration_hours: float = msg.duration.total_seconds() / 3600
- ctx.logger.info(f"Received booking request from user `{user.name}`")
-
- success = (
- set(msg.services) <= set(services)
- and availability.time_start <= msg.time_start
- and availability.time_end >= msg.time_start + msg.duration
- and msg.price <= availability.min_hourly_price * msg_duration_hours
- )
-
- if success:
- availability.time_start = msg.time_start + msg.duration
- await availability.save()
- ctx.logger.info("Accepted task and updated availability.")
-
- # send the response
- await ctx.send(sender, BookingResponse(success=success))
-
- ```
-
-
-
-
-
-
-#### models.py
-
-We now need to define the data structure for the cleaning service application. We account for the following `Models`:
-
-* `ServiceTypes`: to represent different cleaning services (floor, window, laundry, etc.).
-* `Users`: for information like name, address, and creation time.
-* `Service`: for cleaning service type offered.
-* `Provider`: for details like name, location, creation time, and links to their availability and offered services.
-* `Availability`: to define the provider's service schedule, including maximum service distance, start and end times, and minimum hourly price.
-
-Here is the full code:
-
-
-
-
-
-
-
- ```py copy filename="models.py"
-
- from enum import IntEnum
-
- from tortoise import fields, models
-
- class ServiceType(IntEnum):
- FLOOR = 1
- WINDOW = 2
- LAUNDRY = 3
- IRON = 4
- BATHROOM = 5
-
- class User(models.Model):
- id = fields.IntField(pk=True)
- name = fields.CharField(max_length=64)
- address = fields.CharField(max_length=100)
- created_at = fields.DatetimeField(auto_now_add=True)
-
- class Service(models.Model):
- id = fields.IntField(pk=True)
- type = fields.IntEnumField(ServiceType)
-
- class Provider(models.Model):
- id = fields.IntField(pk=True)
- name = fields.CharField(max_length=64)
- location = fields.CharField(max_length=64)
- created_at = fields.DatetimeField(auto_now_add=True)
- availability = fields.ReverseRelation["Availability"]
- services = fields.ManyToManyField("models.Service")
- markup = fields.FloatField(default=1.1)
-
- class Availability(models.Model):
- id = fields.IntField(pk=True)
- provider = fields.OneToOneField("models.Provider", related_name="availability")
- max_distance = fields.IntField(default=10)
- time_start = fields.DatetimeField()
- time_end = fields.DatetimeField()
- min_hourly_price = fields.FloatField(default=0.0)
-
- ```
-
-
-
-
-
-
-### Agents
-#### The Cleaner Agent
-
-
-
-
-
-
-
- ```py copy filename="cleaner.py"
-
- from datetime import datetime
-
- from protocols.cleaning import cleaning_proto
- from protocols.cleaning.models import Availability, Provider, Service, ServiceType
- from pytz import utc
- from tortoise import Tortoise
- from uagents import Agent, Context
-
- cleaner = Agent(
- name="cleaner",
- port=8001,
- seed="cleaner secret phrase",
- endpoint={
- "http://127.0.0.1:8001/submit": {},
- },
- )
-
- # build the cleaning service agent from the cleaning protocol
- cleaner.include(cleaning_proto)
-
- @cleaner.on_event("startup")
- async def startup(_ctx: Context):
- await Tortoise.init(
- db_url="sqlite://db.sqlite3", modules={"models": ["protocols.cleaning.models"]}
- )
- await Tortoise.generate_schemas()
-
- provider = await Provider.create(name=cleaner.name, location="London Kings Cross")
-
- floor = await Service.create(type=ServiceType.FLOOR)
- window = await Service.create(type=ServiceType.WINDOW)
- laundry = await Service.create(type=ServiceType.LAUNDRY)
-
- await provider.services.add(floor)
- await provider.services.add(window)
- await provider.services.add(laundry)
-
- await Availability.create(
- provider=provider,
- time_start=utc.localize(datetime.fromisoformat("2022-01-31 00:00:00")),
- time_end=utc.localize(datetime.fromisoformat("2023-05-01 00:00:00")),
- max_distance=10,
- min_hourly_price=5,
- )
-
- @cleaner.on_event("shutdown")
- async def shutdown(_ctx: Context):
- await Tortoise.close_connections()
-
- if __name__ == "__main__":
- cleaner.run()
-
- ```
-
-
-
-
-
-
-#### User
-
-
-
-
-
-
-
- ```py copy filename="user.py"
-
- from datetime import datetime, timedelta
-
- from protocols.cleaning import (
- BookingResponse,
- ServiceBooking,
- ServiceRequest,
- ServiceResponse,
- )
- from protocols.cleaning.models import ServiceType
- from pytz import utc
- from uagents import Agent, Context
-
- CLEANER_ADDRESS = (
- "test-agent://agent1qdfdx6952trs028fxyug7elgcktam9f896ays6u9art4uaf75hwy2j9m87w"
- )
-
- user = Agent(
- name="user",
- port=8000,
- seed="cleaning user recovery phrase",
- endpoint={
- "http://127.0.0.1:8000/submit": {},
- },
- )
-
-
- request = ServiceRequest(
- user=user.name,
- location="London Kings Cross",
- time_start=utc.localize(datetime.fromisoformat("2023-04-10 16:00:00")),
- duration=timedelta(hours=4),
- services=[ServiceType.WINDOW, ServiceType.LAUNDRY],
- max_price=60,
- )
-
- MARKDOWN = 0.8
-
- @user.on_interval(period=3.0, messages=ServiceRequest)
- async def interval(ctx: Context):
- ctx.storage.set("markdown", MARKDOWN)
- completed = ctx.storage.get("completed")
-
- if not completed:
- ctx.logger.info(f"Requesting cleaning service: {request}")
- await ctx.send(CLEANER_ADDRESS, request)
-
- @user.on_message(ServiceResponse, replies=ServiceBooking)
- async def handle_query_response(ctx: Context, sender: str, msg: ServiceResponse):
- markdown = ctx.storage.get("markdown")
- if msg.accept:
- ctx.logger.info("Cleaner is available, attempting to book now")
- booking = ServiceBooking(
- location=request.location,
- time_start=request.time_start,
- duration=request.duration,
- services=request.services,
- price=markdown * msg.price,
- )
- await ctx.send(sender, booking)
- else:
- ctx.logger.info("Cleaner is not available - nothing more to do")
- ctx.storage.set("completed", True)
-
- @user.on_message(BookingResponse, replies=set())
- async def handle_book_response(ctx: Context, _sender: str, msg: BookingResponse):
- if msg.success:
- ctx.logger.info("Booking was successful")
- else:
- ctx.logger.info("Booking was UNSUCCESSFUL")
-
- ctx.storage.set("completed", True)
-
- if __name__ == "__main__":
- user.run()
-
- ```
-
-
-
-
-
-
-### Poetry Dependencies
-
-```pyproject.toml copy filename="pyproject.toml"
-[tool.poetry.dependencies]
-python = ">=3.9,<3.13"
-uagents = "^0.17.1"
-tortoise-orm = "^0.22.1"
-geopy = "^2.4.1"
-```
-
-#### How to execute the example
-
-- Navigate to the root folder of the example.
-- Install dependencies by running `poetry install`.
-- Run the cleaner Agent with `python cleaner.py`.
-- Run the user Agent with `python user.py`.
-
-### Expected Output
-
-- Cleaner Agent
-
-```
-INFO: [cleaner]: Registration on Almanac API successful
-INFO: [cleaner]: Registering on almanac contract...
-INFO: [cleaner]: Registering on almanac contract...complete
-INFO: [cleaner]: Agent inspector available at https://agentverse.ai/inspect/?uri=http%3A//127.0.0.1%3A8001&address=agent1qdfdx6952trs028fxyug7elgcktam9f896ays6u9art4uaf75hwy2j9m87w
-INFO: [cleaner]: Starting server on http://0.0.0.0:8001 (Press CTRL+C to quit)
-INFO: [cleaner]: Received service request from user `user`
-INFO: [cleaner]: I am available! Proposing price: 22.0.
-INFO: [cleaner]: Received booking request from user `user`
-INFO: [cleaner]: Accepted task and updated availability.
-```
-
-- User Agent:
-
-```
-INFO: [ user]: Registration on Almanac API successful
-INFO: [ user]: Registering on almanac contract...
-INFO: [ user]: Registering on almanac contract...complete
-INFO: [ user]: Agent inspector available at https://agentverse.ai/inspect/?uri=http%3A//127.0.0.1%3A8000&address=agent1qvrskj36y7urk2j9g4gu5hjgwvgr8v6jegm5druawmrpztmjjnep6ssn45p
-INFO: [ user]: Starting server on http://0.0.0.0:8000 (Press CTRL+C to quit)
-INFO: [ user]: Requesting cleaning service: user='user' location='London Kings Cross' time_start=datetime.datetime(2023, 4, 10, 16, 0, tzinfo=) duration=datetime.timedelta(seconds=14400) services=[, ] max_price=60.0
-INFO: [ user]: Cleaner is available, attempting to book now
-INFO: [ user]: Booking was successful
-```
\ No newline at end of file
diff --git a/pages/examples/agent/agents-interval-task.mdx b/pages/examples/agent/agents-interval-task.mdx
deleted file mode 100644
index 8f8030d38..000000000
--- a/pages/examples/agent/agents-interval-task.mdx
+++ /dev/null
@@ -1,70 +0,0 @@
-import { CodeGroup, DocsCode ,CodeSegment, GithubCodeSegment } from "../../../components/code"
-
-# Interval task with Agents
-
-## Introduction
-
-This file can be run on any platform supporting Python, with the necessary install permissions.
-This example shows how to use the uAgents Framework library to set up an interval task using the `on_interval()` decorator.
-
-Please check out the example code in our [examples repo ↗️](https://github.com/fetchai/uAgent-Examples/tree/main/5-documentation/examples/easy/agents-interval-task) to run this locally.
-
-### Guide
-
-- [Creating an interval task ↗️](/guides/agents/interval-task)
-
-### Supporting documentation
-
-- [Creating an agent ↗️](/guides/agents/create-a-uagent)
-
-### The agent
-
-
-
-
-
-
-
-
- ```py copy filename="interval-task.py"
-
- from uagents import Agent, Context
-
- alice = Agent(name="alice", seed="alice recovery phrase")
-
- @alice.on_interval(period=2.0)
- async def say_hello(ctx: Context):
- ctx.logger.info(f'hello, my name is {alice.name}')
-
- if __name__ == "__main__":
- alice.run()
-
- ```
-
-
-
- ```py copy filename="interval-task.py"
-
- from uagents import Agent, Context
-
- @agent.on_interval(period=2.0)
- async def say_hello(ctx: Context):
- ctx.logger.info(f'hello, my name is {agent.name}')
-
- ```
-
-
-
-
-
-
diff --git a/pages/examples/agent/agents-with-docker.mdx b/pages/examples/agent/agents-with-docker.mdx
deleted file mode 100644
index e78c5406e..000000000
--- a/pages/examples/agent/agents-with-docker.mdx
+++ /dev/null
@@ -1,187 +0,0 @@
-import { CodeGroup, DocsCode,GithubCodeSegment, CodeSegment } from "../../../components/code"
-
-# Running an Agent with Docker
-
-## Introduction
-
-This example shows how to run an agent using the uAgents library inside a Docker container with Docker Compose. It walks you through setting up everything you need so you can easily build and run the agent.
-
-### Supporting Documents
-
- - [Almanac contract overview ↗️](../../references/contracts/uagents-almanac/almanac-overview).
- - [How to create an agent ↗️](../../guides/agents/create-a-uagent).
- - [Registering in the Almanac Contract ↗️](../../guides/agents/register-in-almanac).
- - [Creating an interval task ↗️](/guides/agents/interval-task)
- - [Communicating with other agents ↗️](/guides/agents/communicating-with-other-agents)
-
-## Pre-requisites
-
-- **Python:** Download and install from [Python official website ↗️](https://www.python.org/downloads/).
-- **Poetry:** Install by following the instructions on [Poetry's official website ↗️](https://python-poetry.org/docs/#installation).
-- **Docker:** Download and install from [Docker official website ↗️](https://docs.docker.com/get-docker/).
-- **Docker Compose:** Download and install from [Docker Compose official documentation ↗️](https://docs.docker.com/compose/).
-
-## Project Structure
-
-```
-.agent_with_docker
-├── docker-compose.yml
-├── Dockerfile
-├── poetry.lock
-├── pyproject.toml
-├── README.md
-└── src
- └── agent.py
-```
-
-## Agent with Docker
-
-### `agent.py`
-
-This example demonstrates a simple agent-based communication system using the uAgents library. The `data_sender` agent sends a `DataPacket` message to the `data_receiver` agent every 4 seconds. Upon receiving the message, `data_receiver` logs it and sends an acknowledgment back to data_sender. Both agents log the messages they receive. The agents are running with Docker Compose using Docker.
-
- ```py copy filename="agent.py"
-
-
- from uagents import Agent, Bureau, Context, Model
-
-
- class DataPacket(Model):
- message: str
-
-
- data_sender = Agent(name="data_sender", seed="data_sender recovery phrase")
- data_receiver = Agent(name="data_receiver", seed="data_receiver recovery phrase")
-
-
- @data_sender.on_interval(period=4.0)
- async def send_data_packet(ctx: Context):
- """
- Event handler that gets triggered at regular intervals (every 4 seconds).
-
- Args:
- ctx (Context): The context in which the event is triggered.
-
- Returns:
- None: This function does not return any value but sends a DataPacket message from data_sender to data_receiver at intervals of (every 4 seconds).
- """
- await ctx.send(
- data_receiver.address, DataPacket(message="Initiating data transfer")
- )
-
-
- @data_sender.on_message(model=DataPacket)
- async def data_sender_message_handler(ctx: Context, sender: str, msg: DataPacket):
- """
- Event handler that gets triggered when data_sender receives a DataPacket message.
-
- Args:
- ctx (Context): The context in which the event is triggered.
- sender (str): The address of the sender.
- msg (DataPacket): The message received.
-
- Returns:
- None: This function does not return any value but logs the received message.
- """
- ctx.logger.info(f"Data Sender received a message from {sender}: {msg.message}")
-
-
- @data_receiver.on_message(model=DataPacket)
- async def data_receiver_message_handler(ctx: Context, sender: str, msg: DataPacket):
- """
- Event handler that gets triggered when data_receiver receives a DataPacket message.
-
- Args:
- ctx (Context): The context in which the event is triggered.
- sender (str): The address of the sender.
- msg (DataPacket): The message received.
-
- Returns:
- None: This function does not return any value but logs the received message and sends an acknowledgment back to data_sender.
- """
- ctx.logger.info(f"Data Receiver received a message from {sender}: {msg.message}")
- await ctx.send(
- data_sender.address, DataPacket(message="Acknowledging data transfer")
- )
-
-
- bureau = Bureau()
- bureau.add(data_sender)
- bureau.add(data_receiver)
-
- if __name__ == "__main__":
- bureau.run()
-
- ```
-
-
-
-
-### `Dockerfile`
-
-This Dockerfile sets up a Python environment with Poetry for dependency management. It installs necessary system packages, sets up the working directory, installs dependencies specified in `pyproject.toml`, and runs `agent.py` using Poetry. The application listens on port 8000.
-
- ```py copy filename="Dockerfile"
-
- FROM python:3.12-slim
- ENV PATH="$PATH:/root/.local/bin"
- RUN apt-get update && \
- apt-get install -y curl gcc && \
- curl -sSL https://install.python-poetry.org/ | python3 -
- WORKDIR /app
- ADD pyproject.toml poetry.lock /app/
- RUN poetry install
- ADD . /app
- EXPOSE 8000
- ENTRYPOINT ["poetry", "run"]
- CMD ["python", "agent.py"]
-
- ```
-
-
-
-### `docker-compose.yml`
-This Docker Compose configuration builds and runs a Python app using Poetry. It maps the current directory to the container, exposes port 8000, and starts the `agent.py` script.
-
- ```py copy filename="docker-compose.yml"
-
- version: '3.8'
-
- services:
- app:
- build: .
- container_name: poetry_app
- volumes:
- - .:/app
- ports:
- - "8000:8000"
- command: poetry run python src/agent.py
-
- ```
-
-
-## Poetry Dependencies
-
-```
-[tool.poetry.dependencies]
-python = "^3.10"
-uagents = { version = "^0.13.0", python = ">=3.10,<3.13" }
-```
-
-## How to Run This Example
-
-- Navigate to the root Folder of the Example.
-- Run `docker-compose build`
-- Run `docker-compose up`
-
-## Expected Output
-
-```
-Creating network "agent_with_docker_default" with the default driver
-Creating poetry_app ... done
-Attaching to poetry_app
-poetry_app | INFO: [data_receiver]: Data Receiver received a message from agent1qdccxu8z03y3m27p22emtuffjxng8ks3pm69yn703eec6pk5a8p5vzf97qz: Initiating data transfer
-poetry_app | INFO: [bureau]: Starting server on http://0.0.0.0:8000 (Press CTRL+C to quit)
-poetry_app | INFO: [data_sender]: Data Sender received a message from agent1qg0ejev64auhjg7c7xsd32v7npflvhvs5afe43r4gzm4eqmhqgxs7mlfss0: Acknowledging data transfer
-poetry_app | INFO: [data_receiver]: Data Receiver received a message from agent1qdccxu8z03y3m27p22emtuffjxng8ks3pm69yn703eec6pk5a8p5vzf97qz: Initiating data transfer
-```
\ No newline at end of file
diff --git a/pages/examples/agent/async-loops.mdx b/pages/examples/agent/async-loops.mdx
deleted file mode 100644
index f302fbae8..000000000
--- a/pages/examples/agent/async-loops.mdx
+++ /dev/null
@@ -1,170 +0,0 @@
-import { CodeGroup, DocsCode, CodeSegment, GithubCodeSegment } from "../../../components/code";
-
-# Agent Asynchronous Loops
-
-## Introduction
-
-In this example, we demonstrate how to use agents to communicate and exchange status updates in a decentralized system. Agents will send status messages to each other and handle acknowledgments in response. This example is useful for understanding how agents can interact, process messages, and maintain state.
-
-Please check out the example code in our [examples repo ↗️](https://github.com/fetchai/uAgent-Examples/tree/main/5-documentation/examples/advanced/async-loops) to run this locally.
-
-### Supporting documentation
-
-- [Creating an agent ↗️](/guides/agents/create-a-uagent)
-- [Creating an interval task ↗️](/guides/agents/interval-task)
-- [Communicating with other agents ↗️](/guides/agents/communicating-with-other-agents)
-- [Agent Handlers ↗️](/guides/agents/intermediate/handlers)
-
-### The scripts
-
-#### Script 1
-
-
-
-
-
-
-
- ```py copy filename="external_loop_attach.py"
-
- import asyncio
- import contextlib
-
- from uagents import Agent, Bureau, Context
-
- loop = asyncio.get_event_loop()
-
- agent = Agent(
- name="looper",
- seed="",
- )
-
- bureau = Bureau(
- agents=[agent],
- )
-
- @agent.on_event("startup")
- async def startup(ctx: Context):
- ctx.logger.info(">>> Looper is starting up.")
-
- @agent.on_event("shutdown")
- async def shutdown(ctx: Context):
- ctx.logger.info(">>> Looper is shutting down.")
-
- async def coro():
- while True:
- print("Doing hard work...")
- await asyncio.sleep(1)
-
- if __name__ == "__main__":
- print("Attaching the agent or bureau to the external loop...")
- loop.create_task(coro())
-
- # > when attaching the agent to the external loop
- loop.create_task(agent.run_async())
-
- # > when attaching a bureau to the external loop
- # loop.create_task(bureau.run_async())
-
- with contextlib.suppress(KeyboardInterrupt):
- loop.run_forever()
-
- ```
-
-
-
-
-
-
- This script demonstrates how to run an agent using an external event loop. For this example to run correctly, remember to provide a `seed` phrase to the agent. It initializes an agent and attaches it to a loop where it performs continuous background work (`coro()` function) alongside the agent's operations. You can choose to run either the agent or the entire `bureau` with the external loop. This approach provides greater flexibility when integrating the agent with other asynchronous tasks.
-
-#### Script 2
-
-
-
-
-
-
-
- ```py copy filename="external_loop_run.py"
-
- import asyncio
-
- from uagents import Agent, Bureau, Context
-
- loop = asyncio.get_event_loop()
-
- agent = Agent(
- name="looper",
- seed="",
- loop=loop,
- )
-
- bureau = Bureau(
- agents=[agent],
- loop=loop,
- )
-
- @agent.on_event("startup")
- async def startup(ctx: Context):
- ctx.logger.info(">>> Looper is starting up.")
-
- @agent.on_event("shutdown")
- async def shutdown(ctx: Context):
- ctx.logger.info(">>> Looper is shutting down.")
-
- async def coro():
- while True:
- print("Doing hard work...")
- await asyncio.sleep(1)
-
- if __name__ == "__main__":
- print("Starting the external loop from the agent or bureau...")
- loop.create_task(coro())
-
- # > when starting the external loop from the agent
- agent.run()
-
- # > when starting the external loop from the bureau
- # bureau.run()
-
- ```
-
-
-
-
-
-
- This script shows how to run an agent with its own **internal event loop**. For this example to run correctly, remember to provide a `seed` phrase to the agent. The agent is initialized with the `loop`, and both the agent and its background coroutine (`coro()` function) run within the same loop. This setup simplifies the integration by keeping everything within a single event `loop`, which can be advantageous for applications where you want the agent's lifecycle tightly coupled with its event handling function.
-
-### Expected Output
-
-- Script 1:
-
- ```
- Attaching the agent or bureau to the external loop...
- Doing hard work...
- Doing hard work...
- Doing hard work...
- >>> Looper is starting up.
- ```
-
-- Script 2:
-
- ```
- Starting the external loop from the agent or bureau...
- Doing hard work...
- Doing hard work...
- Doing hard work...
- >>> Looper is starting up.
- ```
diff --git a/pages/examples/agent/broadcast.mdx b/pages/examples/agent/broadcast.mdx
deleted file mode 100644
index b83f2aeea..000000000
--- a/pages/examples/agent/broadcast.mdx
+++ /dev/null
@@ -1,107 +0,0 @@
-import { CodeGroup, DocsCode, GithubCodeSegment, CodeSegment } from "../../../components/code"
-
-# Agents broadcast
-
-## Introduction
-
-This file can be run on any platform supporting Python, with the necessary install permissions. This example shows how to use a custom protocol to enable multiple agents communication.
-
-Please check out the example code in our [examples repo ↗️](https://github.com/fetchai/uAgent-Examples/tree/main/5-documentation/examples/intermediate/broadcast) to run this locally.
-
-### Supporting documentation
-
-- [Creating an agent↗️](/guides/agents/create-a-uagent)
-- [Creating an interval task ↗️](/guides/agents/interval-task)
-- [Communicating with other agents ↗️](/guides/agents/intermediate/communicating-with-other-agents)
-- [Register in Almanac ↗️](/guides/agents/register-in-almanac)
-- [Almanac Contract ↗️](/references/contracts/uagents-almanac/almanac-overview)
-- [Agents: broadcast ↗️](/guides/agents/broadcast)
-- [Protocols ↗️](/references/uagents/uagents-protocols/agent-protocols)
-
-### The script
-
-
-
-
-
-
-
- ```py copy filename="broadcast.py"
-
- from uagents import Agent, Bureau, Context, Model, Protocol
-
- # create agents
- # alice and bob will support the protocol
- # charles will try to reach all agents supporting the protocol
- alice = Agent(name="alice", seed="alice recovery phrase")
- bob = Agent(name="bob", seed="bob recovery phrase")
- charles = Agent(name="charles", seed="charles recovery phrase")
-
- class BroadcastExampleRequest(Model):
- pass
-
- class BroadcastExampleResponse(Model):
- text: str
-
- # define protocol
- proto = Protocol(name="proto", version="1.0")
-
- @proto.on_message(model=BroadcastExampleRequest, replies=BroadcastExampleResponse)
- async def handle_request(ctx: Context, sender: str, _msg: BroadcastExampleRequest):
- await ctx.send(
- sender, BroadcastExampleResponse(text=f"Hello from {ctx.agent.name}")
- )
-
- # include protocol
- # Note: after the first registration on the almanac smart contract, it will
- # take about 5 minutes before the agents can be found through the protocol
- alice.include(proto)
- bob.include(proto)
-
- # let charles send the message to all agents supporting the protocol
- @charles.on_interval(period=5)
- async def say_hello(ctx: Context):
- status_list = await ctx.broadcast(proto.digest, message=BroadcastExampleRequest())
- ctx.logger.info(f"Trying to contact {len(status_list)} agents.")
-
- @charles.on_message(model=BroadcastExampleResponse)
- async def handle_response(ctx: Context, sender: str, msg: BroadcastExampleResponse):
- ctx.logger.info(f"Received response from {sender}: {msg.text}")
-
- bureau = Bureau(port=8000, endpoint="http://localhost:8000/submit")
- bureau.add(alice)
- bureau.add(bob)
- bureau.add(charles)
-
- if __name__ == "__main__":
- bureau.run()
-
- ```
-
-
-
-
-
-
-### Expected output
-
- ```
- INFO: [alice]: Registering on almanac contract...
- INFO: [alice]: Registering on almanac contract...complete
- INFO: [ bob]: Registering on almanac contract...
- INFO: [ bob]: Registering on almanac contract...complete
- INFO: [charles]: Registering on almanac contract...
- INFO: [charles]: Registering on almanac contract...complete
- INFO: [bureau]: Starting server on http://0.0.0.0:8000 (Press CTRL+C to quit)
- INFO: [charles]: Received response from agent1qww3ju3h6kfcuqf54gkghvt2pqe8qp97a7nzm2vp8plfxflc0epzcjsv79t: Hello from alice
- INFO: [charles]: Received response from agent1q0mau8vkmg78xx0sh8cyl4tpl4ktx94pqp2e94cylu6haugt2hd7j9vequ7: Hello from bob
- INFO: [charles]: Trying to contact 2 agents.
- INFO: [charles]: Received response from agent1qww3ju3h6kfcuqf54gkghvt2pqe8qp97a7nzm2vp8plfxflc0epzcjsv79t: Hello from alice
- INFO: [charles]: Received response from agent1q0mau8vkmg78xx0sh8cyl4tpl4ktx94pqp2e94cylu6haugt2hd7j9vequ7: Hello from bob
- INFO: [charles]: Trying to contact 2 agents.
- ```
diff --git a/pages/examples/agent/first-agent.mdx b/pages/examples/agent/first-agent.mdx
deleted file mode 100644
index bc600181e..000000000
--- a/pages/examples/agent/first-agent.mdx
+++ /dev/null
@@ -1,86 +0,0 @@
-import { CodeGroup, DocsCode , GithubCodeSegment,CodeSegment } from "../../../components/code"
-
-# Create your first Agent
-
-## Introduction
-
-Welcome to your journey into the world of AI Agents! This example will equip you with the tools to create your very first intelligent agent using the uAgents Python library.
-
-**Ready to get started?**
-
-The code provided in this example can be run on any platform which supports Python with the necessary install permissions. As you progress throughout the examples, you'll get to understand topics in an increasingly difficult way.
-
-Let's get started and explore the basic concepts you need to develop your first Agent!
-
-Please check out the example code in our [examples repo ↗️](https://github.com/fetchai/uAgent-Examples/tree/main/5-documentation/examples/easy/create-your-first-agent) to run this locally.
-
-## Guide
-
-- [Agents - uAgents Framework ↗️](/guides/agents/getting-started/whats-an-agent)
-- [Installing the uAgents Framework ↗️](/guides/agents/getting-started/installing-uagent)
-- [Creating your first agent ↗️](/guides/agents/create-a-uagent)
-- [Agents address ↗️](/guides/agents/getting-started/getting-uagent-address)
-
-## The agent
-
-
-
-
-
-
-
-
- ```py copy filename="agent.py"
-
- # Import necessary classes from the uAgents library
- from uagents import Agent, Context
-
- # Create an agent named alice
- agent = Agent(name="alice")
-
- # Function to be called when the agent is started
- @agent.on_event("startup")
- async def introduce_agent(ctx: Context):
- # Print a greeting message with the agent's name and its address
- print(f"Hello, I'm agent {agent.name} and my address is {agent.address}.")
-
- # Run the agent only when the script is executed directly
- if __name__ == "__main__":
- agent.run()
-
- ```
-
-
-
- ```py copy filename="agent.py"
-
- # Import necessary classes from the uAgents library
- from uagents import Agent, Context
- # Function to be called when the agent is started
- @agent.on_event("startup")
- async def introduce_agent(ctx: Context):
- # Print a greeting message with the agent's name and its address
- print(f"Hello, I'm agent {agent.name} and my address is {agent.address}.")
-
- ```
-
-
-
-
-
-
-## Expected Output
-
-```
-Hello, I'm agent alice and my address is agent1qtx288pfqm9e5qausyzdy6zmmn65ytwygqdq2h7d4g0q80ft04rygg96jtt.
-```
\ No newline at end of file
diff --git a/pages/examples/agent/local-communication.mdx b/pages/examples/agent/local-communication.mdx
deleted file mode 100644
index 9487423bb..000000000
--- a/pages/examples/agent/local-communication.mdx
+++ /dev/null
@@ -1,191 +0,0 @@
-import { CodeGroup, DocsCode,GithubCodeSegment,CodeSegment } from "../../../components/code"
-
-# Local Network Interaction
-
-## Introduction
-
-This file can be run on any platform supporting Python, with the necessary install permissions. This example shows how to set up a local network interaction between two agents using the uAgents Python library.
-
-Please check out the example code in our [examples repo ↗️](https://github.com/fetchai/uAgent-Examples/tree/main/5-documentation/examples/easy/local-communication) to run this locally.
-
-### Supporting documentation
-
-- [Creating an agent ↗️](/guides/agents/create-a-uagent)
-- [Creating an interval task ↗️](/guides/agents/interval-task)
-- [Communicating with other agents ↗️](/guides/agents/communicating-with-other-agents)
-- [Communicating with other agents ↗️](/guides/agents/communicating-with-other-agents)
-- [Agents address ↗️](/guides/agents/getting-started/getting-uagent-address)
-
-### Agent 1
-
-
-
-
-
-
-
-
- ```py copy filename="agent_1.py"
-
- from uagents import Agent, Context, Model
-
- # NOTE: Run agent1.py before running agent2.py
-
- class Message(Model):
- message: str
-
- bob = Agent(
- name="bob",
- port=8001,
- seed="bob secret phrase",
- endpoint=["http://127.0.0.1:8001/submit"],
- )
-
- @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}")
-
- # send the response
- await ctx.send(sender, Message(message="Hello there alice."))
-
- if __name__ == "__main__":
- bob.run()
-
- ```
-
-
-
- ```py copy filename="agent_1.py"
-
- from uagents import Agent, Context, Model
-
- # NOTE: Run agent1.py before running agent2.py
-
- class Message(Model):
- message: str
-
- @agent.on_message(model=Message)
- async def message_handler(ctx: Context, sender: str, msg: Message):
- ctx.logger.info(f"Received message from {sender}: {msg.message}")
-
- # send the response
- await ctx.send(sender, Message(message="Hello there alice."))
-
- ```
-
-
-
-
-
-
-### Agent 2
-
-
-
-
-
-
-
-
- ```py copy filename="agent_2.py"
-
- from uagents import Agent, Context, Model
-
- class Message(Model):
- message: str
-
- RECIPIENT_ADDRESS = (
- "test-agent://agent1q2kxet3vh0scsf0sm7y2erzz33cve6tv5uk63x64upw5g68kr0chkv7hw50"
- )
-
- alice = Agent(
- name="alice",
- port=8000,
- seed="alice secret phrase",
- endpoint=["http://127.0.0.1:8000/submit"],
- )
-
- @alice.on_interval(period=2.0)
- async def send_message(ctx: Context):
- await ctx.send(RECIPIENT_ADDRESS, Message(message="Hello there bob."))
-
- @alice.on_message(model=Message)
- async def message_handler(ctx: Context, sender: str, msg: Message):
- ctx.logger.info(f"Received message from {sender}: {msg.message}")
-
- if __name__ == "__main__":
- alice.run()
-
- ```
-
-
-
- ```py copy filename="agent_2.py"
-
- from uagents import Agent, Context, Model
-
- class Message(Model):
- message: str
-
- RECIPIENT_ADDRESS = (
- "test-agent://agent1q2kxet3vh0scsf0sm7y2erzz33cve6tv5uk63x64upw5g68kr0chkv7hw50"
- )
-
- @agent.on_interval(period=2.0)
- async def send_message(ctx: Context):
- await ctx.send(RECIPIENT_ADDRESS, Message(message="Hello there bob."))
-
- @agent.on_message(model=Message)
- async def message_handler(ctx: Context, sender: str, msg: Message):
- ctx.logger.info(f"Received message from {sender}: {msg.message}")
-
- ```
-
-
-
-
-
-
-### Expected output
-
-- Bob:
-
- ```
- INFO: [ bob]: Registering on almanac contract...
- INFO: [ bob]: Registering on almanac contract...complete
- INFO: [ bob]: Starting server on http://0.0.0.0:8001 (Press CTRL+C to quit)
- INFO: [ bob]: Received message from agent1qdp9j2ev86k3h5acaayjm8tpx36zv4mjxn05pa2kwesspstzj697xy5vk2a: Hello there bob.
- INFO: [ bob]: Received message from agent1qdp9j2ev86k3h5acaayjm8tpx36zv4mjxn05pa2kwesspstzj697xy5vk2a: Hello there bob.
- INFO: [ bob]: Received message from agent1qdp9j2ev86k3h5acaayjm8tpx36zv4mjxn05pa2kwesspstzj697xy5vk2a: Hello there bob.
- ```
-
-- Alice:
-
- ```
- INFO: [alice]: Registering on almanac contract...
- INFO: [alice]: Registering on almanac contract...complete
- INFO: [alice]: Starting server on http://0.0.0.0:8000 (Press CTRL+C to quit)
- INFO: [alice]: Received message from agent1q2kxet3vh0scsf0sm7y2erzz33cve6tv5uk63x64upw5g68kr0chkv7hw50: Hello there alice.
- INFO: [alice]: Received message from agent1q2kxet3vh0scsf0sm7y2erzz33cve6tv5uk63x64upw5g68kr0chkv7hw50: Hello there alice.
- INFO: [alice]: Received message from agent1q2kxet3vh0scsf0sm7y2erzz33cve6tv5uk63x64upw5g68kr0chkv7hw50: Hello there alice.
- ```
diff --git a/pages/examples/agent/multiple-agents.mdx b/pages/examples/agent/multiple-agents.mdx
deleted file mode 100644
index 5580cd5f6..000000000
--- a/pages/examples/agent/multiple-agents.mdx
+++ /dev/null
@@ -1,58 +0,0 @@
-import { CodeGroup, DocsCode, GithubCodeSegment, CodeSegment } from "../../../components/code"
-
-# Multiple agents communication
-
-## Introduction
-
-This file can be run on any platform supporting Python, with the necessary install permissions. This example shows how to create two different agents and make them communicate using the uAgents Python library.
-
-Please check out the example code in our [examples repo ↗️](https://github.com/fetchai/uAgent-Examples/tree/main/5-documentation/examples/intermediate/multiple-agents) to run this locally.
-
-#### Supporting documentation
-
-- [Creating your first agent ↗️](/guides/agents/create-a-uagent)
-- [Communicating with other agents ↗️](/guides/agents/communicating-with-other-agents)
-- [Creating an interval task ↗️](/guides/agents/interval-task)
-
-#### The agent
-
-
-
-
-
-
-
- ```py copy filename="agents.py"
-
- from uagents import Agent, Bureau, Context
-
- alice = Agent(name="alice")
- bob = Agent(name="bob")
-
- @alice.on_interval(period=2.0)
- async def introduce_alice(ctx: Context):
- ctx.logger.info(f"Hello, I'm agent {alice.name}.")
-
- @bob.on_interval(period=2.0)
- async def introduce_bob(ctx: Context):
- ctx.logger.info(f"Hello, I'm agent {bob.name}.")
-
- bureau = Bureau()
- bureau.add(alice)
- bureau.add(bob)
-
- if __name__ == "__main__":
- bureau.run()
-
- ```
-
-
-
-
-
-
diff --git a/pages/examples/agent/on-query.mdx b/pages/examples/agent/on-query.mdx
deleted file mode 100644
index 8eeb0a944..000000000
--- a/pages/examples/agent/on-query.mdx
+++ /dev/null
@@ -1,296 +0,0 @@
-import { Callout } from 'nextra/components'
-import { CodeGroup, DocsCode, GithubCodeSegment,CodeSegment } from "../../../components/code"
-
-# On Query decorator example
-
-This documentation outlines the steps to set up and enable communication between Agent and flask app based webpage, using the uAgents framework. flask app sends a query to Agent, and Agent processes this query and responds. Both agent and app use a simple request-response model for communication.
-
-Please check out the example code in our [examples repo ↗️](https://github.com/fetchai/uAgent-Examples/tree/main/5-documentation/examples/intermediate/on-query-decorator-example) to run this locally.
-
-## Guide
-
-- [How to use on_query decorator ↗️](../../guides/agents/intermediate/handlers#answer-queries-with-on_query-handler)
-
-## Pre-requisites
-
-- **Python:** Download and install from [Python official website ↗️](https://www.python.org/downloads/).
-- **Poetry:** Install by following the instructions on [Poetry's official website ↗️](https://python-poetry.org/docs/#installation).
-
-## Supporting documentation
-
-- [Creating an agent ↗️](/guides/agents/getting-started/create-a-uagent)
-- [Communicating with other agents ↗️](/guides/agents/intermediate/communicating-with-other-agents)
-- [Register in Almanac ↗️](/guides/agents/advanced/register-in-almanac)
-- [Almanac Contract ↗️](/references/contracts/uagents-almanac/almanac-overview)
-- [Protocols ↗️](/references/uagents/uagents-protocols/agent-protocols)
-
-## Agent Script
-
-This agent handles queries related to job searches using SerpAPI. It provides information about available jobs for a job title specified by the user.
-
-
-
-
-
-
-
- ```py copy filename="job-search-agent.py"
-
- # import required libraries
- import json
-
- import aiohttp
- from uagents import Agent, Context, Model
- from uagents.setup import fund_agent_if_low
-
-
- # Define Request and Response Data Models
- class Request(Model):
- query: str
-
-
- class Response(Model):
- response: str
-
-
- # Define asynchronous function to handle job search queries using a serpapi url
- async def get_job_summary(query: str, location: str, api_key: str):
-
- url = "https://serpapi.com/search.json"
- params = {
- "q": query + " careers",
- "location": location,
- "engine": "google_jobs",
- "api_key": api_key,
- }
-
- async with aiohttp.ClientSession() as session:
- async with session.get(url, params=params) as response:
- if response.status == 200:
- data = await response.json()
- jobs = data.get("jobs_results", [])
- if jobs:
- job = jobs[0] if jobs else None # Ensuring there is a job to report
- if not job:
- return "No job details available."
- res_str = json.dumps(
- {
- "Title": job.get("title", "N/A"),
- "Company": job.get("company_name", "N/A"),
- "Location": job.get("location", "N/A"),
- "Link": job.get("link", "N/A"),
- "Posted": job.get("detected_extensions", {}).get(
- "posted_at", "N/A"
- ),
- "Type": job.get("detected_extensions", {}).get(
- "schedule_type", "N/A"
- ),
- "Description": job.get("description", "N/A"),
- },
- indent=2,
- )
- return res_str
- else:
- return "No job results found."
- else:
- return f"Failed to fetch data: {response.status}"
-
-
- # Define Search Agent
- SearchAgent = Agent(
- name="SearchAgent",
- port=8000,
- seed="",
- endpoint=["http://127.0.0.1:8000/submit"],
- ) # Update your agent's secret phrase
-
- # Registering agent on Almanac and funding it
- fund_agent_if_low(SearchAgent.wallet.address())
-
-
- # On agent startup printing address
- @SearchAgent.on_event("startup")
- async def agent_details(ctx: Context):
- ctx.logger.info(f"Search Agent Address is {SearchAgent.address}")
-
-
- # On_query decorator to handle jobs request
- @SearchAgent.on_query(model=Request, replies={Response})
- async def query_handler(ctx: Context, sender: str, msg: Request):
- ctx.logger.info("Query received")
- try:
- ctx.logger.info(f"Fetching job details for query: {msg.query}")
- response = await get_job_summary(
- msg.query, "United Kingdom", "" # Update your serpapi API key
- ) # Replace your serpAPI key.
- ctx.logger.info(f"Response: {response}")
- await ctx.send(sender, Response(response=response))
- except Exception as e:
- error_message = f"Error fetching job details: {str(e)}"
- ctx.logger.error(error_message)
- await ctx.send(sender, Response(response=str(error_message)))
-
-
- if __name__ == "__main__":
- SearchAgent.run()
-
- ```
-
-
-
-
-
-
-
- Please update agent's secret phrase and serpapi API key. You can find serpapi API key on [SerpAPI API key ↗️](https://serpapi.com/)
-
-
-### Flask App Script
-
-Async Agent-Based Flask App for Keyword base Job Search Results Retrieval.
-
-
-
-
-
-
-
- ```py copy filename="job-search-app.py"
-
- import json
-
- from flask import Flask, jsonify, request
- from uagents import Model
- from uagents.query import query
-
- app = Flask(__name__)
-
- # Define the address of your agent to send requests to
- AGENT_ADDRESS = "" # Update your agent address here
-
-
- # Define a data model for incoming requests
- class Request(Model):
- query: str
-
-
- # Define a route to handle job search queries
- @app.route("/search-jobs")
- async def search_jobs():
- keyword = request.args.get("q")
- if not keyword:
- return jsonify({"error": "No query provided.", "status": "error"}), 400
- # Make a call to the agent with the request and handle the response
- response = await make_agent_call(Request(query=keyword))
- # Check if the response indicates an unsuccessful agent call
- if isinstance(response, str) and response.startswith("Unsuccessful"):
- return jsonify({"error": response, "status": "failed"}), 500
-
- try:
- # Parse the response to a Python dictionary
- job_data = json.loads(response)
- # Return the job data in a structured format
- return jsonify({"results": job_data, "status": "success"})
- except json.JSONDecodeError:
- # Handle JSON decoding error
- return jsonify({"error": "Invalid response format", "status": "error"}), 500
-
-
- # Function to send a query to the agent
- async def agent_query(req):
- try:
- response = await query(destination=AGENT_ADDRESS, message=req, timeout=15.0)
- # Decode the response and extract data
- data = json.loads(response.decode_payload())
- return data.get("response", "No data found")
- except Exception as e:
- # Return a formatted error message if the agent call fails
- return f"Unsuccessful agent call - {str(e)}"
-
-
- # Function to initiate an agent call
- async def make_agent_call(req: Request):
- response = await agent_query(req)
- return response
-
-
- # Main function to run the Flask application
- if __name__ == "__main__":
- app.run(debug=True)
-
- ```
-
-
-
-
-
-
-### Poetry Dependencies
-
-```pyproject.toml copy filename="pyproject.toml"
-
-[tool.poetry.dependencies]
-python = ">=3.9,<3.13"
-uagents = "^0.17.1"
-flask = {extras = ["async"], version = "^3.1.0"}
-```
-
-## Steps to run the app
-
-- Navigate to the root folder of the example.
-- Install dependencies by running `poetry install`.
-- Update `Agent Address` in `jobsearchapp.py` and [`serpapi_api_key`](https://serpapi.com/google-jobs-api) in `JobSearchAgent.py`.
-- Run the JobSearchAgent with `python jobSearchAgent.py`
-- Run the Flask server with `python jobsearchapp.py`
-- Open new terminal window and run `curl "http://127.0.0.1:5000/search-jobs?q="`
-- Replace `your_job_search_query` with your query in above command.
-
-## Expected Output
-
-- `JobSearchAgent.py`
-
-```
-INFO: [SearchAgent]: Almanac registration is up to date!
-INFO: [SearchAgent]: Search Agent Address is agent1qdmgt4txxlvve4fmk8cw6jcp4gd2l709ctllx7jvz0kx4jzace5hu8n00hj
-INFO: [SearchAgent]: Starting server on http://0.0.0.0:8000 (Press CTRL+C to quit)
-INFO: [SearchAgent]: Query received
-INFO: [SearchAgent]: Fetching job details for query: data analyst
-INFO: [SearchAgent]: Fetching job details for query: data analyst
-INFO: [SearchAgent]: Response: {
- "Title": "Data Analyst - eCommerce",
- "Company": "Next Plc",
- "Location": " Leicester, United Kingdom ",
- "Link": "N/A",
- "Posted": "3 days ago",
- "Type": "Full-time",
- "Description": "Let\u2019s talk numbers. When it comes to UK retail, it\u2019s hard to find a bigger name. We sell thousands of items an hour and are expanding our eCommerce business by the second. For anyone in Data, this is the place to learn. To grow. And to thrive.\n\nOur International eCommerce Third parties team help to connect NEXT with other large selling platforms such as Zalando and La Redoute to sell thousands of products. These platforms deliver strong growth for NEXT and to continue to support this growth we need ever improving data points and manipulation.\n\nThe role\nAre you an expert in interpreting data? Here, you\u2019ll be at the forefront of understanding and interpreting customer data to drive strategic decisions and enhance online customer experiences. So what does this mean day-to-day for you as a Data Analyst at NEXT, specifically?\n\u2022 Presenting complex analytical findings into clear, concise reports and communicating your analysis to the wider team.\n\u2022 Building reports and visualizations for the... wider team and business.\n\u2022 Exploring the latest technologies and selecting the right tools for the job.\n\u2022 Interrogating large volumes of data from a range of sources, including transactional and online.\n\u2022 Supporting the creation of partner dashboards converting key partner information.\n\u2022 Proactively identifying opportunities to support improvements to the customer experience.\n\u2022 Manage and own new partner data requirements.\n\u2022 Communicating and collaborating with cross functional teams within eCommerce and the wider business.\n\nYou\u2019ll be doing all this from our Leicestershire Head Office. Our offices are inspiring, yes. But we understand that life happens. So, we\u2019re big on making sure your work, works for you which is why we offer flexible working. Bring your energy. Play to your strengths. Make things bigger and better than before. Let\u2019s Take It On.\n\nSo if you\u2019re an expert in this field, have strong SQL/Azure/Databricks skills and considerable data analysis knowledge, have a commercial understanding and background, work with initiative and can build great working relationships within the business, this is the place for you \u2013 and your career.\n\nThe benefits\n\nWe\u2019ll discuss more of what you\u2019ll get when you work for NEXT at interview, but here\u2019s an overview of what you can expect:\n\u2022 Profit\u2013related bonus\n\u2022 Contributions into a pension scheme\n\u2022 Life assurance\n\u2022 Sharesave scheme, which allows you to invest in NEXT and claim your share of our success\n\u2022 A newly refurbished subsidized restaurant and bar\n\u2022 On-site nursery (salary sacrifice scheme) in Leicester\n\u2022 Staff shop\n\u2022 Juice bar and coffee shop\n\u2022 Free parking on-site, including car sharing\n\u2022 Free company bus service to and from Leicester city center and other areas\n\u2022 25% staff discount on most NEXT products \u2013 either in our stores or delivered directly to your desk\n\u2022 National and local discounts on goods and services\n\u2022 A digital GP healthcare service"
-}
-
-```
-
-- Curl Response
-
-```
-{
- "results": {
- "Company": "Next Plc",
- "Description": "Let\u2019s talk numbers. When it comes to UK retail, it\u2019s hard to find a bigger name. We sell thousands of items an hour and are expanding our eCommerce business by the second. For anyone in Data, this is the place to learn. To grow. And to thrive.\n\nOur International eCommerce Third parties team help to connect NEXT with other large selling platforms such as Zalando and La Redoute to sell thousands of products. These platforms deliver strong growth for NEXT and to continue to support this growth we need ever improving data points and manipulation.\n\nThe role\nAre you an expert in interpreting data? Here, you\u2019ll be at the forefront of understanding and interpreting customer data to drive strategic decisions and enhance online customer experiences. So what does this mean day-to-day for you as a Data Analyst at NEXT, specifically?\n\u2022 Presenting complex analytical findings into clear, concise reports and communicating your analysis to the wider team.\n\u2022 Building reports and visualisations for the... wider team and business.\n\u2022 Exploring the latest technologies and selecting the right tools for the job.\n\u2022 Interrogating large volumes of data from a range of sources, including transactional and online.\n\u2022 Supporting the creation of partner dashboards converting key partner information.\n\u2022 Proactively identifying opportunities to support improvements to the customer experience.\n\u2022 Manage and own new partner data requirements.\n\u2022 Communicating and collaborating with cross functional teams within eCommerce and the wider business.\n\nYou\u2019ll be doing all this from our Leicestershire Head Office. Our offices are inspiring, yes. But we understand that life happens. So, we\u2019re big on making sure your work, works for you which is why we offer flexible working. Bring your energy. Play to your strengths. Make things bigger and better than before. Let\u2019s Take It On.\n\nSo if you\u2019re an expert in this field, have strong SQL/Azure/Databricks skills and considerable data analysis knowledge, have a commercial understanding and background, work with initiative and can build great working relationships within the business, this is the place for you \u2013 and your career.\n\nThe benefits\n\nWe\u2019ll discuss more of what you\u2019ll get when you work for NEXT at interview, but here\u2019s an overview of what you can expect:\n\u2022 Profit\u2013related bonus\n\u2022 Contributions into a pension scheme\n\u2022 Life assurance\n\u2022 Sharesave scheme, which allows you to invest in NEXT and claim your share of our success\n\u2022 A newly refurbished subsidised restaurant and bar\n\u2022 On-site nursery (salary sacrifice scheme) in Leicester\n\u2022 Staff shop\n\u2022 Juice bar and coffee shop\n\u2022 Free parking on-site, including car sharing\n\u2022 Free company bus service to and from Leicester city center and other areas\n\u2022 25% staff discount on most NEXT products \u2013 either in our stores or delivered directly to your desk\n\u2022 National and local discounts on goods and services\n\u2022 A digital GP healthcare service",
- "Link": "N/A",
- "Location": " Leicester, United Kingdom ",
- "Posted": "3 days ago",
- "Title": "Data Analyst - eCommerce",
- "Type": "Full-time"
- },
- "status": "success"
-}
-```
diff --git a/pages/examples/agent/on_query_example.mdx b/pages/examples/agent/on_query_example.mdx
deleted file mode 100644
index 07e9cb75a..000000000
--- a/pages/examples/agent/on_query_example.mdx
+++ /dev/null
@@ -1,402 +0,0 @@
-import { Callout } from 'nextra/components'
-import { CodeGroup, DocsCode, GithubCodeSegment, CodeSegment } from "../../../components/code"
-
-## Shopping Assistance Agent using `on_query`
-
-## Introduction
-
-This example creates a shopping assistant agent using FastAPI and uagents. The agent handles shopping questions, utilizes the OpenAI API to generate responses, and sends personalized shopping advice back to the user. The `on_query` method is key to processing and responding to these queries.
-
-Please check out the example code in our [examples repo ↗️](https://github.com/fetchai/uAgent-Examples/tree/main/5-documentation/examples/intermediate/on_query_example/src) to run this locally.
-
-### Supporting Documents
-
- - [Almanac contract overview ↗️](../../references/contracts/uagents-almanac/almanac-overview).
- - [How to create an agent ↗️](../../guides/agents/create-a-uagent).
- - [Registering in the Almanac Contract ↗️](../../guides/agents/register-in-almanac).
- - [How to use on_query decorator ↗️](../../guides/agents/intermediate/handlers).
-
-## Pre-requisites
-
- - **Python :** Download and install from [Python official website ↗️](https://www.python.org/downloads/).
-
-# Shopping Assistance Agent
-
- - **models :** This code defines two data models, `ShoppingRequest` and `ShoppingAssistResponse`, using the uAgents library, each with a single string attribute (question and answer, respectively).
-
-
-
-
-
-
-
- ```py copy filename="models.py"
-
- from uagents import Model
-
-
- class ShoppingRequest(Model):
- question: str
-
-
- class ShoppingAssistResponse(Model):
- answer: str
-
-
- ```
-
-
-
-
-
-
- - **Shopping Assistance Agent :** This code defines a shopping assistant agent using the uAgents framework. The agent listens for incoming `ShoppingRequest` messages, processes them by sending the user's question to OpenAI's GPT-4 API for a response, and then sends the generated response back to the sender as a `ShoppingAssistResponse`.
-
-
-
-
-
-
-
-
- ```py copy filename="agent.py"
-
- from uagents import Agent, Context
- from uagents.setup import fund_agent_if_low
- from models import ShoppingAssistResponse, ShoppingRequest
- import requests
- import json
-
-
- agent = Agent(
- name="Shopping Assistant",
- seed="shopping_assistant_seed_phrase",
- port=8001,
- endpoint="http://localhost:8001/submit",
- )
-
- fund_agent_if_low(agent.wallet.address())
-
- YOUR_OPEN_AI_API_KEY = "PASTE_YOUR_OPEN_AI_API_KEY"
-
-
- def get_chat_response(messages):
- """
- Sends a request to the OpenAI GPT-4 API to generate a chat response.
-
- Accepts:
- - messages: A list of dictionaries representing the conversation history,
- where each dictionary contains a 'role' (e.g., 'system' or 'user')
- and 'content' (the message text).
-
- What it does:
- - Sends a POST request to the OpenAI API with the conversation history.
- - Handles the API response, returning the generated response from the model
- or an error message if the request fails.
-
- Returns:
- - A string containing the model's response if the request is successful.
- - An error message string if the request fails.
- """
- api_url = "https://api.openai.com/v1/chat/completions"
- headers = {
- "Authorization": f"Bearer {YOUR_OPEN_AI_API_KEY}",
- "Content-Type": "application/json",
- }
-
- data = {
- "model": "gpt-4",
- "messages": messages,
- "max_tokens": 150,
- "temperature": 0.7,
- }
-
- response = requests.post(api_url, headers=headers, data=json.dumps(data))
-
- if response.status_code == 200:
- result = response.json()
- return result["choices"][0]["message"]["content"].strip()
- else:
- return f"Error: {response.status_code} - {response.text}"
-
-
- @agent.on_query(model=ShoppingRequest, replies=ShoppingAssistResponse)
- async def handler(ctx: Context, sender: str, msg: ShoppingRequest):
- """
- Handles incoming queries from other agents, specifically ShoppingRequest messages.
-
- Accepts:
- - ctx: The context object, used for logging and communication.
- - sender: A string representing the address of the agent that sent the message.
- - msg: A ShoppingRequest object containing the question from the user.
-
- What it does:
- - Logs the received question.
- - Prepares a conversation history for the chat model with the role of the assistant and user.
- - Sends the conversation history to the get_chat_response function to generate a response.
- - Logs the generated response.
- - Sends the response back to the sender as a ShoppingAssistResponse.
-
- Returns:
- - None (asynchronous function).
- """
- ctx.logger.info(f"Received message from {sender} with question: {msg.question}")
- messages = [{"role": "system", "content": "You are a helpful shopping assistant."}]
- messages.append({"role": "user", "content": msg.question})
- response = get_chat_response(messages)
- ctx.logger.info(f"Question: {msg.question}\nAnswer: {response}")
- await ctx.send(sender, ShoppingAssistResponse(answer=response))
-
-
- if __name__ == "__main__":
- agent.run()
-
-
- ```
-
-
-
- ```py copy filename="agent.py"
-
- from uagents import Agent, Context
- import requests
- import json
-
- YOUR_OPEN_AI_API_KEY = "PASTE_YOUR_OPEN_AI_API_KEY"
-
- class ShoppingRequest(Model):
- question: str
-
- class ShoppingAssistResponse(Model):
- answer: str
-
- def get_chat_response(messages):
- """
- Sends a request to the OpenAI GPT-4 API to generate a chat response.
-
- Accepts:
- - messages: A list of dictionaries representing the conversation history,
- where each dictionary contains a 'role' (e.g., 'system' or 'user')
- and 'content' (the message text).
-
- What it does:
- - Sends a POST request to the OpenAI API with the conversation history.
- - Handles the API response, returning the generated response from the model
- or an error message if the request fails.
-
- Returns:
- - A string containing the model's response if the request is successful.
- - An error message string if the request fails.
- """
- api_url = "https://api.openai.com/v1/chat/completions"
- headers = {
- "Authorization": f"Bearer {YOUR_OPEN_AI_API_KEY}",
- "Content-Type": "application/json",
- }
-
- data = {
- "model": "gpt-4",
- "messages": messages,
- "max_tokens": 150,
- "temperature": 0.7,
- }
-
- response = requests.post(api_url, headers=headers, data=json.dumps(data))
-
- if response.status_code == 200:
- result = response.json()
- return result["choices"][0]["message"]["content"].strip()
- else:
- return f"Error: {response.status_code} - {response.text}"
-
- @agent.on_query(model=ShoppingRequest, replies=ShoppingAssistResponse)
- async def handler(ctx: Context, sender: str, msg: ShoppingRequest):
- """
- Handles incoming queries from other agents, specifically ShoppingRequest messages.
-
- Accepts:
- - ctx: The context object, used for logging and communication.
- - sender: A string representing the address of the agent that sent the message.
- - msg: A ShoppingRequest object containing the question from the user.
-
- What it does:
- - Logs the received question.
- - Prepares a conversation history for the chat model with the role of the assistant and user.
- - Sends the conversation history to the get_chat_response function to generate a response.
- - Logs the generated response.
- - Sends the response back to the sender as a ShoppingAssistResponse.
-
- Returns:
- - None (asynchronous function).
- """
- ctx.logger.info(f"Received message from {sender} with question: {msg.question}")
- messages = [{"role": "system", "content": "You are a helpful shopping assistant."}]
- messages.append({"role": "user", "content": msg.question})
- response = get_chat_response(messages)
- ctx.logger.info(f"Question: {msg.question}\nAnswer: {response}")
- await ctx.send(sender, ShoppingAssistResponse(answer=response))
-
-
- ```
-
-
-
-
-
-
-
- You need to have an OpenAI API key to run this example. You can get it from [OpenAI ↗️](https://openai.com/) .
-
-
- - **main.py :** This FastAPI code starts by defining an endpoint `/api/question-answer` that accepts a query parameter message, sends it to an agent for processing, and returns the agent's response.
-
-
-
-
-
-
-
- ```py copy filename="main.py"
-
- from fastapi import FastAPI, Query
- from uagents.query import query
- from models import ShoppingRequest
- import json
-
- app = FastAPI()
-
- DESTINATION = "agent1qg9p5xppsdv6067lg570g8t3lzens32fg6d0fe88jawd2v0lsh8f6ru9ntc"
-
-
- @app.get("/api/question-answer")
- async def question_answering(
- message: str = Query(..., description="The message or question you want to ask")
- ):
- """
- Handles GET requests to the /api/question-answer endpoint.
-
- Accepts:
- - message: A string query parameter representing the message or question that you want to ask.
-
- What it does:
- - Creates a ShoppingRequest object using the provided message.
- - Sends the ShoppingRequest object to the specified agent (DESTINATION) using the query function.
- - Decodes the response payload received from the agent and parses it as JSON.
-
- Returns:
- - A dictionary containing the "response" with the answer retrieved from the agent.
- """
- shopping_request = ShoppingRequest(question=message)
- answer = await query(destination=DESTINATION, message=shopping_request)
- response_data = json.loads(answer.decode_payload())
- return {"response": response_data.get("answer")}
-
-
- @app.get("/")
- async def root():
- """
- Handles GET requests to the root endpoint ("/").
-
- What it does:
- - Returns a simple "Hello World" message.
-
- Returns:
- - A dictionary containing a "message" key with the value "Hello World".
- """
- return {"message": "Hello World"}
-
- ```
-
-
-
-
-
-
- - **pyproject.toml :** Poetry Dependencies
-
-```py copy filename="pyproject.toml"
-[tool.poetry.dependencies]
-python = ">=3.10,<3.12"
-fastapi = "^0.112.0"
-uvicorn = {extras = ["standard"], version = "^0.30.5"}
-uagents = "^0.15.1"
-```
-
-## How to Run This Example
-
-To get started with this example, follow these steps:
-
- - **Activate the Poetry Shell and Install Dependencies**
-
- Open your terminal and run the following command to activate the Poetry shell and install all dependencies:
-
- ```bash
- poetry shell
- ```
-
- - **Start the FastAPI Server**
-
- Navigate to the src directory and start the FastAPI server using uvicorn:
-
- ```bash
- cd src
- uvicorn main:app
- ```
-
- - **Run the Agent Code**
-
- Execute the agent code with the following command:
- ```bash
- python agent.py
- ```
-
-## Expected output
-
- - Curl Request
-
-```bash copy
-curl -G -L --data-urlencode "message=I want to purchase a MacBook" "http://localhost:8000/api/question-answer/"
-```
-
- - Curl Response
-
-```bash
-{"response":"Great choice! MacBooks are known for their sleek design, impressive performance, and high-quality display. Here are some things to consider before your purchase:\n\n1. **Model**: Apple currently offers MacBook Air and MacBook Pro. Each model comes with different sizes and specifications. The MacBook Air is a slim, lightweight machine, perfect for casual use or on-the-go work. The MacBook Pro is a more powerful machine, suitable for heavy-duty tasks like video editing, graphic design, and professional applications.\n\n2. **Specifications**: Depending on your needs, you might need more or less power. Consider the processor speed, the amount of RAM, the size of the solid-state drive (SSD), and the type of graphics card.\n\n3. **Budget**: Mac"}
-```
-
- - Shopping Assistance Agent
-
-```
-INFO: [Shopping Assistant]: Almanac registration is up to date!
-INFO: [Shopping Assistant]: Starting server on http://0.0.0.0:8001 (Press CTRL+C to quit)
-INFO: [Shopping Assistant]: Received message from user1fu0nqpf7mgxyms0wwvphgt8p3a7cvzfqqq6tkmxlhkr740glxzjsmzudat with question: I want to purchase a MacBook
-INFO: [Shopping Assistant]: Question: I want to purchase a MacBook
-Answer: Great choice! MacBooks are known for their sleek design, impressive performance, and high-quality display. Here are some things to consider before your purchase:
-
-1. **Model**: Apple currently offers MacBook Air and MacBook Pro. Each model comes with different sizes and specifications. The MacBook Air is a slim, lightweight machine, perfect for casual use or on-the-go work. The MacBook Pro is a more powerful machine, suitable for heavy-duty tasks like video editing, graphic design, and professional applications.
-
-2. **Specifications**: Depending on your needs, you might need more or less power. Consider the processor speed, the amount of RAM, the size of the solid-state drive (SSD), and the type of graphics card.
-
-3. **Budget**: Mac
-```
-
diff --git a/pages/examples/agent/search-example.mdx b/pages/examples/agent/search-example.mdx
deleted file mode 100644
index b38c51915..000000000
--- a/pages/examples/agent/search-example.mdx
+++ /dev/null
@@ -1,217 +0,0 @@
-# Search with Agents
-
-## Introduction
-This example covers how to use the `uagents` library to search for agents based on user queries. It demonstrates how an AI-powered search agent processes the query and retrieves relevant agents, returning the results in a structured workflow.
-
-## Explanation of the `ai` Function
-The `ai` function is responsible for interacting with search API to retrieve search results. Here's how it works:
-
- ```py copy
- def ai(
- query: str,
- protocol: Optional[
- str
- ] = "proto:a03398ea81d7aaaf67e72940937676eae0d019f8e1d8b5efbadfef9fd2e98bb2",
- ) -> dict:
- url = "https://agentverse.ai/v1/search/agents"
- headers = {
- "Content-Type": "application/json",
- }
-
- data = {
- "search_text": query,
- "sort": "relevancy",
- "filters": {
- "protocol_digest": [protocol],
- },
- "direction": "asc",
- "offset": 0,
- "limit": 10,
- }
-
- try:
- response = httpx.post(url, json=data, headers=headers, timeout=10.0)
- return {"ais": response.json().get("agents", [])}
- except httpx.RequestError as exc:
- return {"ais": [], "error": f"{exc}"}
- ```
-
-### Parameters
-
-- `query`: A string representing the user's search query.
-- `protocol` (optional): A string representing the protocol digest used to filter search results. Default is a sample protocol string.
-
-### Implementation
-
-1. API Endpoint and Headers:
- - The function sends a POST request to `https://agentverse.ai/v1/search/agents`.
-2. Request Data:
- - `search_text`: The user's query.
- - `filters`: Filters results based on the provided protocol digest.
- - `direction`: Determines the order of results (ascending by default).
- - `offset` and `limit`: Pagination parameters for the results.
-3. Error Handling:
- - If the API call fails, the function catches the exception and returns an error message.
-
-### Return Value
-
-The function returns a dictionary containing the search results or an error message if the request fails.
-
-## Agent Mechanism
-
-### Overview
-
-Two agents, `query_agent` and `search_agent`, coordinate to handle user queries and responses.
-
-### Workflow
-
-1. Startup Event:
- - `query_agent` sends the user-provided query to `search_agent` upon startup.
-2. Message Handling:
- - `search_agent` receives the query, processes it using the `ai` function, and sends back the search results.
- - `query_agent` receives and logs the response.
-
-### Code Details
-
-#### Query Agent
-
-- Handles user input and initiates communication with the search agent.
-- Logs startup and response events.
-
-#### Search Agent
-
-- Processes the query using the `ai` function.
-- Sends the results back to the `query_agent`.
-
-```py copy
-
-from uagents import Agent, Bureau, Context, Model
-from typing import Optional, Dict
-import httpx
-
-class Query(Model):
- message: str
-
-class Response(Model):
- response: Dict
-
-def ai(
- query: str,
- protocol: Optional[
- str
- ] = "proto:a03398ea81d7aaaf67e72940937676eae0d019f8e1d8b5efbadfef9fd2e98bb2",
-) -> dict:
- url = "https://agentverse.ai/v1/search/agents"
- headers = {
- "Content-Type": "application/json",
- }
-
- data = {
- "search_text": query,
- "sort": "relevancy",
- "filters": {
- "protocol_digest": [protocol],
- },
- "direction": "asc",
- "offset": 0,
- "limit": 10,
- }
-
- try:
- response = httpx.post(url, json=data, headers=headers, timeout=10.0)
- return {"ais": response.json().get("agents", [])}
- except httpx.RequestError as exc:
- return {"ais": [], "error": f"{exc}"}
-
-query_agent = Agent(name="query_agent", seed="query_agent recovery phrase")
-search_agent = Agent(name="search_agent", seed="search_agent recovery phrase")
-
-user_query = input("Enter your query: ")
-
-@query_agent.on_event("startup")
-async def send_message(ctx: Context):
- ctx.logger.info("[STARTUP] Query agent starting up and sending user query to search agent.")
- await ctx.send(search_agent.address, Query(message=user_query))
-
-@search_agent.on_message(model=Query)
-async def search_message_handler(ctx: Context, sender: str, msg: Query):
- ctx.logger.info(f"[RECEIVED] Query received from {sender}. Message: '{msg.message}'")
- results = ai(msg.message)
- ctx.logger.info("[PROCESSING] Searching completed. Sending response back to the query agent.")
- await ctx.send(query_agent.address, Response(response=results))
-
-@query_agent.on_message(model=Response)
-async def response_message_handler(ctx: Context, sender: str, msg: Response):
- ctx.logger.info(f"[RECEIVED] Response received from search agent {sender}. Response: {msg.response}")
-
-bureau = Bureau()
-bureau.add(query_agent)
-bureau.add(search_agent)
-
-if __name__ == "__main__":
- bureau.run()
-
-```
-
-### Running the Example
-
-#### Setup the poetry environment
-
-1. Create a Virtual Environment:
- ```bash
- poetry shell
- ```
-
-2. Install Dependencies:
- ```bash
- poetry add httpx uagents
- ```
-
-#### Run the example
-
-1. Save the script as `search_agents.py`.
-2. Run the script:
- ```bash
- python search_agents.py
- ```
-3. Enter a query when prompted.
-4. Observe the interaction in the logs as the query is processed and results are returned.
-
-### Expected Output
-
-```
-Enter your query: i want to buy a macbook
-INFO: [query_agent]: Starting agent with address: agent1qdpstehd8x39n3jr0mas3adcy9d7rh4ss8wtw6euch0mq04tqu66kpfcu3q
-INFO: [query_agent]: [STARTUP] Query agent starting up and sending user query to search agent.
-INFO: [search_agent]: Starting agent with address: agent1qgj8y2mswcc4jm275tsnq948fa7aqe8d9v0jd78h0nx9ak6v3fnxj6m6pkj
-INFO: [search_agent]: [RECEIVED] Query received from agent1qdpstehd8x39n3jr0mas3adcy9d7rh4ss8wtw6euch0mq04tqu66kpfcu3q. Message: 'i want to buy a macbook'
-INFO:httpx:HTTP Request: POST https://agentverse.ai/v1/search/agents "HTTP/1.1 200 OK"
-INFO: [search_agent]: [PROCESSING] Searching completed. Sending response back to the query agent.
-INFO: [bureau]: Starting server on http://0.0.0.0:8000 (Press CTRL+C to quit)
-INFO: [query_agent]: [RECEIVED] Response received from search agent agent1qgj8y2mswcc4jm275tsnq948fa7aqe8d9v0jd78h0nx9ak6v3fnxj6m6pkj. Response: {
- 'ais': [
- {
- 'address': 'agent1qwpd8cy9ymhjyuj4x2k75dv69vlxquk0xtwhmw09khv8jdkszw32y7rfd99',
- 'name': 'tarot-agent',
- 'readme': '\n My AI\'s description of capabilities and offerings\n \n My AI returns your Tarot reading\n \n \n The requirements your AI has for requests\n \n \n Date of birth\n I need your date of birth\n \n \n gender\n I need your gender\n \n \n \n ',
- 'protocols': [
- {
- 'name': '',
- 'version': '',
- 'digest': 'proto:a03398ea81d7aaaf67e72940937676eae0d019f8e1d8b5efbadfef9fd2e98bb2'
- }
- ],
- 'avatar_href': None,
- 'total_interactions': 0,
- 'recent_interactions': 0,
- 'rating': None,
- 'status': 'active',
- 'type': 'local',
- 'category': 'community',
- 'featured': False,
- 'geo_location': None,
- 'last_updated': '2025-01-07T09:29:23Z',
- 'created_at': '2024-12-09T16:18:18Z'
- },...more]
-}
-```
diff --git a/pages/examples/agent/send-tokens-agents.mdx b/pages/examples/agent/send-tokens-agents.mdx
deleted file mode 100644
index cf572d719..000000000
--- a/pages/examples/agent/send-tokens-agents.mdx
+++ /dev/null
@@ -1,109 +0,0 @@
-import { CodeGroup, DocsCode, GithubCodeSegment,CodeSegment } from "../../../components/code"
-
-# Send tokens with Agents
-
-## Introduction
-
-This file can be run on any platform supporting Python, with the necessary install permissions.
-This example shows how to use Agents to make them send tokens to each other.
-
-Please check out the example code in our [examples repo ↗️](https://github.com/fetchai/uAgent-Examples/tree/main/5-documentation/examples/intermediate/send-tokens-agents) to run this locally.
-
-### Supporting documentation
-
-- [Creating an agent ↗️](/guides/agents/create-a-uagent)
-- [Creating an interval task ↗️](/guides/agents/interval-task)
-- [Communicating with other agents ↗️](/guides/agents/communicating-with-other-agents)
-- [Register in Almanac ↗️](/guides/agents/register-in-almanac)
-- [Almanac Contract ↗️](/references/contracts/uagents-almanac/almanac-overview)
-- [Protocols ↗️](/references/uagents/uagents-protocols/agent-protocols)
-- [How to use agents to send tokens ↗️](/guides/agents/intermediate/send-tokens)
-
-### The agent
-
-
-
-
-
-
-
- ```py copy filename="local-sending_tokens.py"
-
- from uagents import Agent, Bureau, Context, Model
- from uagents.network import wait_for_tx_to_complete
- from uagents.setup import fund_agent_if_low
-
- class PaymentRequest(Model):
- wallet_address: str
- amount: int
- denom: str
-
- class TransactionInfo(Model):
- tx_hash: str
-
- AMOUNT = 100
- DENOM = "atestfet"
-
- alice = Agent(name="alice", seed="alice secret phrase")
- bob = Agent(name="bob", seed="bob secret phrase")
-
- fund_agent_if_low(alice.wallet.address())
- fund_agent_if_low(bob.wallet.address(), min_balance=AMOUNT)
-
- @alice.on_interval(period=10.0)
- async def request_funds(ctx: Context):
- await ctx.send(
- bob.address,
- PaymentRequest(
- wallet_address=str(alice.wallet.address()), amount=AMOUNT, denom=DENOM
- ),
- )
-
- @alice.on_message(model=TransactionInfo)
- async def confirm_transaction(ctx: Context, sender: str, msg: TransactionInfo):
- ctx.logger.info(f"Received transaction info from {sender}: {msg}")
-
- tx_resp = await wait_for_tx_to_complete(msg.tx_hash, ctx.ledger)
- coin_received = tx_resp.events["coin_received"]
-
- if (
- coin_received["receiver"] == str(alice.wallet.address())
- and coin_received["amount"] == f"{AMOUNT}{DENOM}"
- ):
- ctx.logger.info(f"Transaction was successful: {coin_received}")
-
- @bob.on_message(model=PaymentRequest, replies=TransactionInfo)
- async def send_payment(ctx: Context, sender: str, msg: PaymentRequest):
- ctx.logger.info(f"Received payment request from {sender}: {msg}")
- transaction = ctx.ledger.send_tokens(
- msg.wallet_address, msg.amount, msg.denom, bob.wallet
- )
-
- await ctx.send(alice.address, TransactionInfo(tx_hash=transaction.tx_hash))
-
- bureau = Bureau()
- bureau.add(alice)
- bureau.add(bob)
-
- if __name__ == "__main__":
- bureau.run()
-
- ```
-
-
-
-
-
-
-### Expected output
-
- ```
- [ bob]: Received payment request from agent1qdp9j2ev86k3h5acaayjm8tpx36zv4mjxn05pa2kwesspstzj697xy5vk2a: wallet_address='fetch1967p3vkp0yngdfturv4ypq2p4g760ml705wcxy' amount=100 denom='atestfet'
- [alice]: Received transaction info from agent1q2kxet3vh0scsf0sm7y2erzz33cve6tv5uk63x64upw5g68kr0chkv7hw50: tx_hash='DB662CCF415C7B0C9A02928967BE1817506D02A041AA05CA48DCE5CF87D5A638'
- [alice]: Transaction was successful: {'receiver': 'fetch1967p3vkp0yngdfturv4ypq2p4g760ml705wcxy', 'amount': '100atestfet'}
- ```
diff --git a/pages/examples/agent/sending-and-verifying-token-transactions-with-agent.mdx b/pages/examples/agent/sending-and-verifying-token-transactions-with-agent.mdx
deleted file mode 100644
index a42a0f077..000000000
--- a/pages/examples/agent/sending-and-verifying-token-transactions-with-agent.mdx
+++ /dev/null
@@ -1,340 +0,0 @@
-import { CodeGroup, DocsCode, GithubCodeSegment,CodeSegment } from "../../../components/code"
-
-# Sending and verifying token transactions with Agent
-
-## Introduction
-
-This example demonstrates the integration of uAgents with Web3.py to interact with Ethereum smart contracts and manage agent systems. It highlights the process of initiating a USDC transfer, processing the transaction, and verifying the transaction status using the agent system. The example also shows how uAgents can facilitate token transfers to smart contracts and enable seamless fund transfers.
-
-Please check out the example code in our [examples repo ↗️](https://github.com/fetchai/uAgent-Examples/tree/main/5-documentation/examples/intermediate/sending-and-verifying-token-transactions-with-agent) to run this locally.
-
-### Supporting Documents
-
- - [Almanac contract overview ↗️](../../references/contracts/uagents-almanac/almanac-overview).
- - [How to create an agent ↗️](../../guides/agents/create-a-uagent).
- - [Registering in the Almanac Contract ↗️](../../guides/agents/register-in-almanac).
- - [Creating an interval task ↗️](/guides/agents/interval-task)
- - [Communicating with other agents ↗️](/guides/agents/communicating-with-other-agents)
-
-## Pre-requisites
-
-- **Python:** Download and install from [Python official website ↗️](https://www.python.org/downloads/).
-- **Poetry:** Install by following the instructions on [Poetry's official website ↗️](https://python-poetry.org/docs/#installation).
-- A running Ethereum node (or a provider like Infura) on [Infura official website ↗️](https://www.infura.io/).
-- **Contract ABI:** USDC smart contract ABI (in abi.json file) on [sepolia.etherscan.io official website ↗️](https://sepolia.etherscan.io/address/0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238#code).
-
-## Project Structure
-
-```
-.sending-and-verifying-token-transactions-with-agent
-├── poetry.lock
-├── pyproject.toml
-├── README.md
-└── web3
- ├── abi.json
- └── transaction.py
-```
-
-## Sending and Verifying Token Transactions with Agents
-
-This example demonstrates how to build a simple agent-based system for transferring USDC (USD Coin) using the uAgents library. The system consists of three agents: `transaction_initiator`, `transaction_processor`, and `verification_agent`. These agents work together to initiate, process, and verify a USDC transaction on the Ethereum blockchain.
-
-### Get the Infura API Key and Endpoints
-
-- Sign Up : Create an account on Infura.
-- Create a New API Key : After logging in, navigate to the dashboard and click on `Create a New API Key`
-- Access the URL : Once the API key is created, click on the API key to get endpoint URLs for different Ethereum networks.
-- Select Network : Choose the Sepolia testnet to obtain the specific URL, which includes your API key (e.g., `https://sepolia.infura.io/v3/{your-api-key}`).
-
-### Get the ABI JSON, Contract Address and Private Key.
-
-- Visit the contract's Etherscan page (in this case, we are using USDC on the Sepolia testnet) [Link](https://sepolia.etherscan.io/address/0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238#code).
-- ABI JSON : Download the ABI JSON File.
-- Get the Contract Address: You can also find the Contract Address at the top of the page
-- Private key : Access your crypto wallet and retrieve the private key associated with your account. Ensure you keep this private key secure and confidential.
-
-### Agents Overview
-
-#### 1. `transaction_initiator`
-
-- Role : Initiates the transaction process by sending a request to the `transaction_processor`.
-- Event : On startup, it triggers a transaction request.
-- Handles : Responses from `transaction_processor` and sends verification requests to `verification_agent`.
-
-#### 2. `transaction_processor`
-
-- Role : Processes the transaction request by building, signing, and sending the USDC transfer.
-- Handles : Requests from `transaction_initiator` and responds with the transaction receipt.
-
-#### 3. `verification_agent`
-
-- Role : Verifies the transaction status using the transaction hash.
-- Handles : Verification requests from `transaction_initiator` and stores the verification receipt.
-
-### Workflow
-
-#### 1. Transaction Initiation:
- - `transaction_initiator` starts up and sends a `TransactionRequest` to the `transaction_processor` to initiate a USDC transfer.
-
-#### 2. Transaction Processing:
- - `transaction_processor` receives the request, builds and signs the transaction using the sender's private key, and sends the transaction to the blockchain. After receiving the transaction receipt, it sends a `TransactionResponse` back to the `transaction_initiator`.
-
-#### 3. Transaction Verification:
- - Upon receiving the transaction receipt, `transaction_initiator` sends a `VerificationRequest` to the `verification_agent`. The `verification_agent` checks the transaction status on the blockchain and logs the result.
-
-
-
-
-
-
-
- ```py copy filename="transaction.py"
-
- from uagents import Agent, Bureau, Context, Model
- from web3 import Web3
- from dotenv import load_dotenv
- from typing import Optional, Dict
- import os
- import json
-
- load_dotenv()
- provider_url = os.getenv("WEB3_PROVIDER_URL")
- sender_address = os.getenv("SENDER_ADDRESS")
- receiver_address = os.getenv("RECEIVER_ADDRESS")
- sender_private_key = os.getenv("SENDER_PRIVATE_KEY")
- usdc_contract_address = os.getenv("USDC_CONTRACT_ADDRESS")
- amount = os.getenv("AMOUNT")
-
-
- class TransactionRequest(Model):
- message: str
- action: str
- transaction_hash: Optional[str] = None
-
-
- class TransactionResponse(Model):
- message: str
- balance: Optional[int] = 0
- transaction_receipt: Optional[Dict] = None
-
-
- class VerificationRequest(Model):
- transaction_hash: str
-
-
- class VerificationResponse(Model):
- status: str
- receipt: Optional[Dict] = None
-
-
- with open("abi.json") as abi_file:
- proxy_abi = json.load(abi_file)
-
- w3 = Web3(Web3.HTTPProvider(provider_url))
- proxy_contract = w3.eth.contract(address=usdc_contract_address, abi=proxy_abi)
-
-
- transaction_initiator = Agent(
- name="transaction_initiator", seed="transaction_initiator recovery phrase"
- )
-
- transaction_processor = Agent(
- name="transaction_processor", seed="transaction_processor recovery phrase"
- )
-
- verification_agent = Agent(
- name="verification_agent", seed="verification_agent recovery phrase"
- )
-
-
- @transaction_initiator.on_event("startup")
- async def initiate_transaction(ctx: Context):
- """
- Triggered on startup. Sends a transaction request to the
- transaction processor to initiate a USDC transfer.
- """
- ctx.logger.info(f"*** Transaction Initiator startup event triggered. ***")
- await ctx.send(
- transaction_processor.address,
- TransactionRequest(message="Requesting transaction", action="send_usdc"),
- )
-
-
- @transaction_initiator.on_message(
- model=TransactionResponse, replies=VerificationRequest
- )
- async def transaction_initiator_response_handler(
- ctx: Context, sender: str, msg: TransactionResponse
- ):
- """
- Handles the transaction response. Logs the transaction
- receipt and sends a verification request if successful.
- """
- ctx.logger.info(f"*** Received response from {sender}: {msg.message} ***")
- if msg.transaction_receipt is not None:
- ctx.logger.info(
- f"*** USDC Transaction successful: {msg.transaction_receipt} ***"
- )
- transaction_hash = msg.transaction_receipt["transactionHash"]
- print(transaction_hash)
- await ctx.send(
- verification_agent.address,
- VerificationRequest(transaction_hash=transaction_hash),
- )
-
-
- @transaction_processor.on_message(model=TransactionRequest, replies=TransactionResponse)
- async def transaction_processor_request_handler(
- ctx: Context, sender: str, msg: TransactionRequest
- ):
- """
- Processes the transaction request. Builds, signs, and sends a
- USDC transfer transaction, then sends the receipt back.
- """
- ctx.logger.info(
- f"*** Transaction Processor received request from {sender}: {msg.message} with action {msg.action} ***"
- )
-
- if msg.action == "send_usdc":
- ctx.logger.info(
- f"*** Preparing to send USDC from {sender_address} to {receiver_address} ***"
- )
- sender_account = w3.eth.account.from_key(sender_private_key)
- gas_price = w3.eth.gas_price
- usdc_amount = w3.to_wei(amount, "mwei")
- transaction = proxy_contract.functions.transfer(
- receiver_address, usdc_amount
- ).build_transaction(
- {
- "chainId": w3.eth.chain_id,
- "nonce": w3.eth.get_transaction_count(sender_address),
- "gas": 600000,
- "gasPrice": gas_price,
- }
- )
-
- signed_txn = sender_account.sign_transaction(transaction)
- raw_transaction = signed_txn.raw_transaction
- tx_hash = w3.eth.send_raw_transaction(raw_transaction)
- receipt = w3.eth.wait_for_transaction_receipt(tx_hash)
-
- receipt_dict = {
- "transactionHash": receipt.transactionHash.hex(),
- "transactionIndex": receipt.transactionIndex,
- "blockNumber": receipt.blockNumber,
- "blockHash": receipt.blockHash.hex(),
- "cumulativeGasUsed": receipt.cumulativeGasUsed,
- "gasUsed": receipt.gasUsed,
- "status": receipt.status,
- }
-
- ctx.logger.info(
- f"*** USDC Transaction complete. Receipt details: {receipt_dict} ***"
- )
-
- await ctx.send(
- sender,
- TransactionResponse(
- message="USDC Transaction complete", transaction_receipt=receipt_dict
- ),
- )
-
-
- @verification_agent.on_message(model=VerificationRequest, replies=VerificationResponse)
- async def verification_request_handler(
- ctx: Context, sender: str, msg: VerificationRequest
- ):
- """
- Verifies the transaction using the provided hash. Logs the
- status and stores the receipt in the agent's context.
- """
- ctx.logger.info(
- f"*** Verification Agent received request: {msg.transaction_hash} ***"
- )
-
- try:
- receipt = w3.eth.get_transaction_receipt(msg.transaction_hash)
- if receipt:
- status = "Success" if receipt.status == 1 else "Failure"
- receipt_dict = {
- "transactionHash": receipt.transactionHash.hex(),
- "transactionIndex": receipt.transactionIndex,
- "blockNumber": receipt.blockNumber,
- "blockHash": receipt.blockHash.hex(),
- "cumulativeGasUsed": receipt.cumulativeGasUsed,
- "gasUsed": receipt.gasUsed,
- "status": status,
- }
- ctx.logger.info(f"*** Transaction Verification: {status} ***")
- ctx.storage.set("receipt", receipt_dict)
- else:
- ctx.logger.info(f"*** Transaction not found: {msg.transaction_hash} ***")
- except Exception as e:
- ctx.logger.error(f"*** Error during verification: {e} ***")
-
-
- bureau = Bureau()
- bureau.add(transaction_initiator)
- bureau.add(transaction_processor)
- bureau.add(verification_agent)
-
- if __name__ == "__main__":
- bureau.run()
-
-
- ```
-
-
-
-
-
-
-### Poetry Dependencies
-
-```pyproject.toml copy filename="pyproject.toml"
-[tool.poetry.dependencies]
-python = "^3.10"
-web3 = "^7.0.0"
-python-dotenv = "^1.0.1"
-uagents = { version = "^0.13.0", python = ">=3.10,<3.13" }
-```
-
-### How to Run This Example
-
-#### Update the Required environment variables
-
-```env copy filename=".env.example"
-WEB3_PROVIDER_URL=
-SENDER_ADDRESS=
-RECEIVER_ADDRESS=
-SENDER_PRIVATE_KEY=
-USDC_CONTRACT_ADDRESS=
-AMOUNT=
-```
-
-#### Instructions to execute the example.
-
-- Navigate to the root folder of the example.
-- Update the `.env` file.
-- Install dependencies by running `poetry install`.
-- Execute the script with python transaction.py.
-
-### Expected Output
-
-```
-INFO: [transaction_initiator]: *** Transaction Initiator startup event triggered. ***
-INFO: [transaction_processor]: *** Transaction Processor received request from agent1qg4qyv4xtnh9v9ct8uk6yhgllr4sj47uryc5hzk76wqr5nt6vgjtvyfhfjt: Requesting transaction with action send_usdc ***
-INFO: [transaction_processor]: *** Preparing to send USDC from 0x6E45CaC31883cff53d5Dbc0Fdc2b73b5aa7e1157 to 0xd0385eac66580C189cd721cD09FB671B0840Cac2 ***
-INFO: [transaction_processor]: *** USDC Transaction complete. Receipt details: {'transactionHash': '0596f4c91aa7fd88b8eab59f705fba4c8ba1530b3e5767f6bde969eee0d75b40', 'transactionIndex': 6, 'blockNumber': 6598943, 'blockHash': '3d18bac50491aa6b65711304a7cd6a21de2e90f10a132ac422917fa5691a2363', 'cumulativeGasUsed': 524654, 'gasUsed': 45059, 'status': 1} ***
-INFO: [transaction_initiator]: *** Received response from agent1qg874jqdg7kfh0d3g7l049a7q5jecv3wkmy4rkqky3fxl60824dq2g4rdga: USDC Transaction complete ***
-INFO: [transaction_initiator]: *** USDC Transaction successful: {'transactionHash': '0596f4c91aa7fd88b8eab59f705fba4c8ba1530b3e5767f6bde969eee0d75b40', 'transactionIndex': 6, 'blockNumber': 6598943, 'blockHash': '3d18bac50491aa6b65711304a7cd6a21de2e90f10a132ac422917fa5691a2363', 'cumulativeGasUsed': 524654, 'gasUsed': 45059, 'status': 1} ***
-0596f4c91aa7fd88b8eab59f705fba4c8ba1530b3e5767f6bde969eee0d75b40
-INFO: [verification_agent]: *** Verification Agent received request: 0596f4c91aa7fd88b8eab59f705fba4c8ba1530b3e5767f6bde969eee0d75b40 ***
-INFO: [verification_agent]: *** Transaction Verification: Success ***
-INFO: [bureau]: Starting server on http://0.0.0.0:8000 (Press CTRL+C to quit)
-```
\ No newline at end of file
diff --git a/pages/examples/agent/simple-agent-communication-with-bureau.mdx b/pages/examples/agent/simple-agent-communication-with-bureau.mdx
deleted file mode 100644
index d8c8c0e55..000000000
--- a/pages/examples/agent/simple-agent-communication-with-bureau.mdx
+++ /dev/null
@@ -1,66 +0,0 @@
-import { CodeGroup, DocsCode,GithubCodeSegment,CodeSegment } from "../../../components/code"
-
-# Agents communication
-
-## Introduction
-
-This file can be run on any platform supporting Python, with the necessary install permissions. This example shows two agents communicating with each other using the uAgents Python library.
-
-Please check out the example code in our [examples repo ↗️](https://github.com/fetchai/uAgent-Examples/tree/main/5-documentation/examples/easy/simple-agent-communication-with-bureau) to run this locally.
-
-#### Supporting documentation
-
-- [Creating an agent↗️](/guides/agents/create-a-uagent)
-- [Creating an interval task ↗️](/guides/agents/interval-task)
-- [Communicating with other agents ↗️](/guides/agents/communicating-with-other-agents)
-- [Agents address ↗️](/guides/agents/getting-started/getting-uagent-address)
-
-#### The agent
-
-
-
-
-
-
-
- ```py copy filename="agents_communication.py"
-
- from uagents import Agent, Bureau, Context, Model
-
- class Message(Model):
- message: str
-
- sigmar = Agent(name="sigmar", seed="sigmar recovery phrase")
- slaanesh = Agent(name="slaanesh", seed="slaanesh recovery phrase")
-
- @sigmar.on_interval(period=3.0)
- async def send_message(ctx: Context):
- await ctx.send(slaanesh.address, Message(message="hello there slaanesh"))
-
- @sigmar.on_message(model=Message)
- async def sigmar_message_handler(ctx: Context, sender: str, msg: Message):
- ctx.logger.info(f"Received message from {sender}: {msg.message}")
-
- @slaanesh.on_message(model=Message)
- async def slaanesh_message_handler(ctx: Context, sender: str, msg: Message):
- ctx.logger.info(f"Received message from {sender}: {msg.message}")
- await ctx.send(sigmar.address, Message(message="hello there sigmar"))
-
- bureau = Bureau()
- bureau.add(sigmar)
- bureau.add(slaanesh)
- if __name__ == "__main__":
- bureau.run()
-
- ```
-
-
-
-
-
-
diff --git a/pages/examples/agent/staking-and-unstaking-with-an-agent.mdx b/pages/examples/agent/staking-and-unstaking-with-an-agent.mdx
deleted file mode 100644
index 624d325e4..000000000
--- a/pages/examples/agent/staking-and-unstaking-with-an-agent.mdx
+++ /dev/null
@@ -1,340 +0,0 @@
-import { Callout } from 'nextra/components'
-import { CodeGroup, DocsCode, GithubCodeSegment,CodeSegment } from "../../../components/code"
-
-# Staking and unstaking with an Agent
-
-## Introduction
-
-In this example, we explore the implementation of staking and unstaking tokens using autonomous uAgents in a Web3 environment. Staking refers to the process of locking tokens in a smart contract to support network operations or earn rewards, while unstaking involves the withdrawal of these tokens after a specified period or conditions have been met. By leveraging the uAgents library and Web3, this setup enables agents to interact with smart contracts.
-
-Please check out the example code in our [examples repo ↗️](https://github.com/fetchai/uAgent-Examples/tree/main/5-documentation/examples/intermediate/staking-and-unstaking) to run this locally.
-
-### Supporting Documents
-
- - [Almanac contract overview ↗️](../../references/contracts/uagents-almanac/almanac-overview).
- - [How to create an agent ↗️](../../guides/agents/create-a-uagent).
- - [Registering in the Almanac Contract ↗️](../../guides/agents/register-in-almanac).
- - [Creating an interval task ↗️](/guides/agents/interval-task)
- - [Communicating with other agents ↗️](/guides/agents/communicating-with-other-agents)
-
-## Pre-requisites
-
-- **Python:** Download and install from [Python official website ↗️](https://www.python.org/downloads/).
-- **Poetry:** Install by following the instructions on [Poetry's official website ↗️](https://python-poetry.org/docs/#installation).
-- A running Ethereum node (or a provider like Infura) on [Infura official website ↗️](https://www.infura.io/).
-- **Contract ABI:** The ABI of the deployed contract where you want to perform staking and unstaking operations is required.
-
-
-## Project Structure
-
-```
-.staking-and-unstaking-with-agent
-├── poetry.lock
-├── pyproject.toml
-├── README.md
-└── web3
- ├── contract_abi.json
- └── staking-and-unstaking-with-agent.py
-```
-
-## Staking and Unstaking the Tokens with an Agents
-
-This example uses `uAgents` to facilitate staking and unstaking of tokens on a blockchain. The `user_agent` gathers user input to decide on the action and directs either the `stake_agent` or `unstake_agent` to execute the transaction. The `stake_agent` locks funds by creating and sending a staking transaction, while the `unstake_agent` processes unstaking transactions. Both agents handle transaction signing and receipt retrieval. All agents are managed and executed within a `Bureau`.
-
-
-### For staking and unstaking tokens, you need to consider the following:
-
-- Infura API Key and Endpoints: Obtain your Infura API key and endpoints to connect to the Ethereum network. you can see steps [Link ↗️](sending-and-verifying-token-transactions-with-agent#get-the-infura-api-key-and-endpoints)
-
-#### ABI JSON and Contract Information:
-- ABI JSON: Obtain the ABI (Application Binary Interface) JSON of the deployed staking contract. Alternatively, you can deploy your own contract with staking and unstaking functions. For instance, you can create and deploy your own contract using [Remix ↗️](https://remix-project.org/?lang=en). In this example, we have deployed our own contract.
-- Contract Address: Get the address of the deployed staking contract.
-- Private Key: Use your wallet private key to sign transactions.
-
-
-
-
- Approve the Contract: Ensure that the contract has been approved to perform staking and unstaking operations on your behalf.
-
-
-
-### Agents Overview
-
-#### 1. `User Agent`
-- Purpose: Acts as the primary interface for user interaction. It listens for `startup` events and prompts the user to decide whether to stake or unstake tokens.
-- Key Actions:
- - On startup, it asks the user if they want to stake or unstake tokens.
- - Based on user input, it sends a `StakingRequest` to either the `stake_agent` or `unstake_agent`.
-
-#### 2. `Stake Agent`
-- Purpose: Handles the staking of tokens.
-- Key Actions:
- - Receives a `StakingRequest` with the action `stake_tokens`.
- - Constructs and sends a transaction to stake tokens.
- - After the transaction is processed, it sends a `StakingResponse` with the transaction receipt back to the `user_agent`.
-
-#### 3. `Unstake Agent`
-- Purpose: Handles the unstaking of tokens.
-- Key Actions:
- - Receives a `StakingRequest` with the action `unstake_tokens`.
- - Constructs and sends a transaction to unstake tokens.
- - After the transaction is processed, it sends a `StakingResponse` with the transaction receipt back to the `user_agent`.
-
-### Workflow
-
-#### 1. User Interaction:
- - When the system starts, the `user_agent` triggers a startup event.
- - The `user_agent` prompts the user to choose between staking or unstaking tokens.
-
-#### 2. Request Handling:
- - Based on the user's choice, the `user_agent` sends a `StakingRequest` to the appropriate agent (`stake_agent` or `unstake_agent`).
-
-#### 3. Transaction Execution:
- - The `stake_agent` or `unstake_agent` receives the `StakingRequest` and performs the following:
- - Builds and signs a transaction using the Web3 library.
- - Sends the transaction to the blockchain.
- - Waits for the transaction to be mined and retrieves the transaction receipt.
-
-4. Response Handling:
- - After processing the transaction, the `stake_agent` or `unstake_agent` sends a `StakingResponse` back to the `user_agent`.
- - The `user_agent` receives the response and logs the transaction receipt details.
- - The `user_agent` updates the storage with the transaction receipt and informs the user of the transaction status.
-
-
-
-
-
-
-
-
-
-```py copy filename="staking-and-unstaking-with-agent.py"
-from uagents import Agent, Bureau, Context, Model
-from web3 import Web3
-from dotenv import load_dotenv
-from typing import Optional, Dict
-import os
-import json
-
-load_dotenv()
-
-
-provider_url = os.getenv("WEB3_PROVIDER_URL")
-sender_address = os.getenv("SENDER_ADDRESS")
-sender_private_key = os.getenv("SENDER_PRIVATE_KEY")
-deployed_contract_address = os.getenv("DEPLOYED_CONTRACT_ADDRESS")
-amount = os.getenv("AMOUNT")
-
-
-with open("contract_abi.json") as abi_file:
- proxy_abi = json.load(abi_file)
-
-
-w3 = Web3(Web3.HTTPProvider(provider_url))
-proxy_contract = w3.eth.contract(address=deployed_contract_address, abi=proxy_abi)
-stake_amount = w3.to_wei(amount, "mwei")
-
-
-class StakingRequest(Model):
- action: str
- transaction_hash: Optional[str] = None
-
-
-class StakingResponse(Model):
- message: str
- transaction_receipt: Optional[Dict] = None
-
-
-user_agent = Agent(name="user_agent", seed="user_agent recovery phrase")
-stake_agent = Agent(name="stake_agent", seed="stake_agent recovery phrase")
-unstake_agent = Agent(name="unstake_agent", seed="unstake_agent recovery phrase")
-
-
-def create_receipt_dict(receipt) -> Dict:
- """
- Creates a dictionary from the transaction receipt details.
- Args:
- receipt: The transaction receipt returned by the Web3 `wait_for_transaction_receipt` function.
- Returns:
- A dictionary containing details of the transaction receipt.
- """
- return {
- "transactionHash": receipt.transactionHash.hex(),
- "transactionIndex": receipt.transactionIndex,
- "blockNumber": receipt.blockNumber,
- "blockHash": receipt.blockHash.hex(),
- "cumulativeGasUsed": receipt.cumulativeGasUsed,
- "gasUsed": receipt.gasUsed,
- "status": receipt.status,
- }
-
-
-def sign_and_send_transaction(transaction, sender_account):
- """
- Signs and sends a transaction to the blockchain.
- Args:
- transaction: The transaction to be sent.
- sender_account: The account object used to sign the transaction.
- Returns:
- The receipt of the transaction.
- """
- signed_txn = sender_account.sign_transaction(transaction)
- tx_hash = w3.eth.send_raw_transaction(signed_txn.raw_transaction)
- return w3.eth.wait_for_transaction_receipt(tx_hash)
-
-
-@user_agent.on_event("startup")
-async def handle_user_input(ctx: Context):
- ctx.logger.info(f"*** User Agent startup event triggered. ***")
- action = input("Do you want to 'stake' or 'unstake' tokens? ")
- if action.lower() == "stake":
- await ctx.send(stake_agent.address, StakingRequest(action="stake_tokens"))
- elif action.lower() == "unstake":
- await ctx.send(unstake_agent.address, StakingRequest(action="unstake_tokens"))
- else:
- ctx.logger.info("*** Invalid action. Please enter 'stake' or 'unstake'. ***")
-
-
-@user_agent.on_message(model=StakingResponse)
-async def user_agent_response_handler(ctx: Context, sender: str, msg: StakingResponse):
- ctx.logger.info(f"*** Received response from {sender}: {msg.message} ***")
- if msg.transaction_receipt is not None:
- ctx.storage.set("receipt", msg.transaction_receipt)
- ctx.logger.info(f"*** Transaction successful: {msg.transaction_receipt} ***")
-
-
-@stake_agent.on_message(model=StakingRequest, replies=StakingResponse)
-async def stake_handler(ctx: Context, sender: str, msg: StakingRequest):
- sender_account = w3.eth.account.from_key(sender_private_key)
- gas_price = w3.eth.gas_price
- nonce = w3.eth.get_transaction_count(sender_address)
- ctx.logger.info(f"*** Preparing to stake tokens ***")
- stake_transaction = proxy_contract.functions.stake(stake_amount).build_transaction(
- {
- "chainId": w3.eth.chain_id,
- "gas": 400000,
- "gasPrice": gas_price,
- "nonce": nonce,
- }
- )
- receipt = sign_and_send_transaction(stake_transaction, sender_account)
- receipt_dict = create_receipt_dict(receipt)
- ctx.logger.info(
- f"*** Staking Transaction complete. Receipt details: {receipt_dict} ***"
- )
- await ctx.send(
- sender,
- StakingResponse(
- message="Staking Transaction complete", transaction_receipt=receipt_dict
- ),
- )
-
-
-@unstake_agent.on_message(model=StakingRequest, replies=StakingResponse)
-async def unstake_handler(ctx: Context, sender: str, msg: StakingRequest):
- sender_account = w3.eth.account.from_key(sender_private_key)
- gas_price = w3.eth.gas_price
- nonce = w3.eth.get_transaction_count(sender_address)
- ctx.logger.info(f"*** Preparing to unstake tokens ***")
- unstake_transaction = proxy_contract.functions.unstake(
- stake_amount
- ).build_transaction(
- {
- "chainId": w3.eth.chain_id,
- "gas": 400000,
- "gasPrice": gas_price,
- "nonce": nonce,
- }
- )
- receipt = sign_and_send_transaction(unstake_transaction, sender_account)
- receipt_dict = create_receipt_dict(receipt)
- ctx.logger.info(
- f"*** Unstaking Transaction complete. Receipt details: {receipt_dict} ***"
- )
- await ctx.send(
- sender,
- StakingResponse(
- message="Unstaking Transaction complete", transaction_receipt=receipt_dict
- ),
- )
-
-
-bureau = Bureau()
-bureau.add(user_agent)
-bureau.add(stake_agent)
-bureau.add(unstake_agent)
-if __name__ == "__main__":
- bureau.run()
-```
-
-
-
-
-### Poetry Dependencies
-
-```pyproject.toml copy filename="pyproject.toml"
-[tool.poetry.dependencies]
-python = "^3.10"
-web3 = "^7.0.0"
-python-dotenv = "^1.0.1"
-uagents = { version = "^0.13.0", python = ">=3.10,<3.13" }
-```
-
-### How to Run This Example
-
-#### Update the Required environment variables
-
-```env copy filename=".env.example"
-WEB3_PROVIDER_URL=
-SENDER_ADDRESS=
-SENDER_PRIVATE_KEY=
-DEPLOYED_CONTRACT_ADDRESS=
-AMOUNT=
-```
-
-#### Instructions to execute the example.
-
-- Navigate to the root folder of the example.
-- Update the `.env` file.
-- Install dependencies by running `poetry install`.
-- Execute the script with `python staking-and-unstaking-with-agent.py`.
-
-### Expected Output
-
-
-
-#### Output for Staking the Token:
-
-```
-INFO: [user_agent]: *** User Agent startup event triggered. ***
-Do you want to 'stake' or 'unstake' tokens? stake
-INFO: [stake_agent]: *** Preparing to stake tokens ***
-INFO: [stake_agent]: *** Staking Transaction complete. Receipt details: {'transactionHash': 'e9df2da422e44944abcb643e898958b6a938c70ad4fef7e05f23b8c9439160a7', 'transactionIndex': 19, 'blockNumber': 6630791, 'blockHash': '9e15205b94d9fff8f0818ed8ae1b2c3ac74b718be03efb43ce66ce42c62b60e6', 'cumulativeGasUsed': 1501911, 'gasUsed': 67147, 'status': 1} ***
-INFO: [user_agent]: *** Received response from agent1qw2lerut2he47tr5rn8yngvzcwt7kak99q9cafux54s8tua5ueu2jgvudue: Staking Transaction complete ***
-INFO: [user_agent]: *** Transaction successful: {'transactionHash': 'e9df2da422e44944abcb643e898958b6a938c70ad4fef7e05f23b8c9439160a7', 'transactionIndex': 19, 'blockNumber': 6630791, 'blockHash': '9e15205b94d9fff8f0818ed8ae1b2c3ac74b718be03efb43ce66ce42c62b60e6', 'cumulativeGasUsed': 1501911, 'gasUsed': 67147, 'status': 1} ***
-INFO: [bureau]: Starting server on http://0.0.0.0:8000 (Press CTRL+C to quit)
-```
-
-#### Output for Unstaking the Token:
-
-```
-INFO: [user_agent]: *** User Agent startup event triggered. ***
-Do you want to 'stake' or 'unstake' tokens? unstake
-INFO: [unstake_agent]: *** Preparing to unstake tokens ***
-INFO: [unstake_agent]: *** Unstaking Transaction complete. Receipt details: {'transactionHash': '8e5ad8ce49c85bbdd6b0babc87f0f5c5c661353fbd9383c543115703073840fe', 'transactionIndex': 62, 'blockNumber': 6630800, 'blockHash': '4abd693bd7e51efadba94e77ce894ed8660bfb773f16af03f5fd701b5cd4837c', 'cumulativeGasUsed': 9297352, 'gasUsed': 61263, 'status': 1} ***
-INFO: [bureau]: Starting server on http://0.0.0.0:8000 (Press CTRL+C to quit)
-INFO: [user_agent]: *** Received response from agent1qgl0x9vpre6almvnytddl8gqtrtcx4cmxssp4m5adhs5gq99y30jy3v60ct: Unstaking Transaction complete ***
-INFO: [user_agent]: *** Transaction successful: {'transactionHash': '8e5ad8ce49c85bbdd6b0babc87f0f5c5c661353fbd9383c543115703073840fe', 'transactionIndex': 62, 'blockNumber': 6630800, 'blockHash': '4abd693bd7e51efadba94e77ce894ed8660bfb773f16af03f5fd701b5cd4837c', 'cumulativeGasUsed': 9297352, 'gasUsed': 61263, 'status': 1} ***
-```
-
-
-
-
-
-
-
diff --git a/pages/examples/agent/storage.mdx b/pages/examples/agent/storage.mdx
deleted file mode 100644
index c22e30d2b..000000000
--- a/pages/examples/agent/storage.mdx
+++ /dev/null
@@ -1,79 +0,0 @@
-import { CodeGroup, DocsCode, GithubCodeSegment, CodeSegment } from "../../../components/code"
-
-# Agents storage
-
-## Introduction
-
-This file can be run on any platform supporting Python, with the necessary install permissions. This example shows how to use an Agent's storage through the uAgents Python library.
-
-Please check out the example code in our [examples repo ↗️](https://github.com/fetchai/uAgent-Examples/tree/main/5-documentation/examples/easy/agent-storage) to run this locally.
-
-## Supporting documentation
-
-- [Creating your first agent ↗️](/guides/agents/create-a-uagent)
-- [Creating an interval task ↗️](/guides/agents/interval-task)
-- [Agents storage functions ↗️](/guides/agents/intermediate/storage-function)
-
-### The agent
-
-
-
-
-
-
-
-
- ```py copy filename="storage.py"
-
- from uagents import Agent, Context
-
- agent = Agent(name="bob")
-
- @agent.on_event("startup")
- async def initialize_storage(ctx: Context):
- ctx.storage.set("count", 0)
-
- @agent.on_interval(period=1.0)
- async def on_interval(ctx: Context):
- current_count = ctx.storage.get("count")
- ctx.logger.info(f"My count is: {current_count}")
- ctx.storage.set("count", current_count + 1)
-
- if __name__ == "__main__":
- agent.run()
-
- ```
-
-
-
- ```py copy filename="storage.py"
-
- from uagents import Agent, Context
-
- @agent.on_event("startup")
- async def initialize_storage(ctx: Context):
- ctx.storage.set("count", 0)
-
- @agent.on_interval(period=1.0)
- async def on_interval(ctx: Context):
- current_count = ctx.storage.get("count")
- ctx.logger.info(f"My count is: {current_count}")
- ctx.storage.set("count", current_count + 1)
-
-```
-
-
-
-
-
-
diff --git a/pages/examples/agent/table-booking-demo.mdx b/pages/examples/agent/table-booking-demo.mdx
deleted file mode 100644
index 3998022a6..000000000
--- a/pages/examples/agent/table-booking-demo.mdx
+++ /dev/null
@@ -1,543 +0,0 @@
-import { CodeGroup, DocsCode, GithubCodeSegment,CodeSegment } from "../../../components/code"
-
-# Table booking service with Agents
-
-## Introduction
-
-This file can be run on any platform supporting Python, with the necessary install permissions.
-This example shows how to use Agents to create a table booking service at a restaurant.
-
-Please check out the example code in our [examples repo ↗️](https://github.com/fetchai/uAgent-Examples/tree/main/5-documentation/examples/intermediate/table-booking-demo) to run this locally.
-
-### Supporting documentation
-
-- [Creating an agent ↗️](/guides/agents/create-a-uagent)
-- [Creating an interval task ↗️](/guides/agents/interval-task)
-- [Communicating with other agents ↗️](/guides/agents/communicating-with-other-agents)
-- [Register in Almanac ↗️](/guides/agents/register-in-almanac)
-- [Almanac Contract ↗️](/references/contracts/uagents-almanac/almanac-overview)
-- [Protocols ↗️](/references/uagents/uagents-protocols/agent-protocols)
-- [Agents address ↗️](/guides/agents/getting-started/getting-uagent-address)
-
-## Project Structure
-
-Outline of basic structure of the project:
-
-```
-table-booking-demo/
-.
-├── protocols/
-│ ├── query.py
-│ └── book.py
-│
-└── agents/
- ├── restaurant.py
- └── user.py
-```
-
-### The Protocols
-
-#### Query table
-
-
-
-
-
-
-
-
- ```py copy filename="query.py"
-
- from typing import List
-
- from uagents import Context, Model, Protocol
-
- class TableStatus(Model):
- seats: int
- time_start: int
- time_end: int
-
- class QueryTableRequest(Model):
- guests: int
- time_start: int
- duration: int
-
- class QueryTableResponse(Model):
- tables: List[int]
-
- class GetTotalQueries(Model):
- pass
-
- class TotalQueries(Model):
- total_queries: int
- query_proto = Protocol()
-
- @query_proto.on_message(model=QueryTableRequest, replies=QueryTableResponse)
- async def handle_query_request(ctx: Context, sender: str, msg: QueryTableRequest):
- tables = {
- int(num): TableStatus(**status)
- for (
- num,
- status,
- ) in ctx.storage._data.items()
- if isinstance(num, int)
- }
- available_tables = []
- for number, status in tables.items():
- if (
- status.seats >= msg.guests
- and status.time_start <= msg.time_start
- and status.time_end >= msg.time_start + msg.duration
- ):
- available_tables.append(int(number))
- ctx.logger.info(f"Query: {msg}. Available tables: {available_tables}.")
- await ctx.send(sender, QueryTableResponse(tables=available_tables))
- total_queries = int(ctx.storage.get("total_queries") or 0)
- ctx.storage.set("total_queries", total_queries + 1)
-
- @query_proto.on_query(model=GetTotalQueries, replies=TotalQueries)
- async def handle_get_total_queries(ctx: Context, sender: str, _msg: GetTotalQueries):
- total_queries = int(ctx.storage.get("total_queries") or 0)
- await ctx.send(sender, TotalQueries(total_queries=total_queries))
-
- ```
-
-
-
- ```py copy filename="query.py"
-
- from typing import List
-
- from uagents import Context, Model, Protocol
-
- class TableStatus(Model):
- seats: int
- time_start: int
- time_end: int
-
- class QueryTableRequest(Model):
- guests: int
- time_start: int
- duration: int
-
- class QueryTableResponse(Model):
- tables: List[int]
-
- class GetTotalQueries(Model):
- pass
-
- class TotalQueries(Model):
- total_queries: int
- query_proto = Protocol()
-
- @query_proto.on_message(model=QueryTableRequest, replies=QueryTableResponse)
- async def handle_query_request(ctx: Context, sender: str, msg: QueryTableRequest):
- tables = {
- int(num): TableStatus(**status)
- for (
- num,
- status,
- ) in ctx.storage.items()
- if isinstance(num, int)
- }
- available_tables = []
- for number, status in tables.items():
- if (
- status.seats >= msg.guests
- and status.time_start <= msg.time_start
- and status.time_end >= msg.time_start + msg.duration
- ):
- available_tables.append(int(number))
- ctx.logger.info(f"Query: {msg}. Available tables: {available_tables}.")
- await ctx.send(sender, QueryTableResponse(tables=available_tables))
- total_queries = int(ctx.storage.get("total_queries") or 0)
- ctx.storage.set("total_queries", total_queries + 1)
-
- @query_proto.on_query(model=GetTotalQueries, replies=TotalQueries)
- async def handle_get_total_queries(ctx: Context, sender: str, _msg: GetTotalQueries):
- total_queries = int(ctx.storage.get("total_queries") or 0)
- await ctx.send(sender, TotalQueries(total_queries=total_queries))
-
- ```
-
-
-
-
-
-
-#### Book table
-
-
-
-
-
-
-
-
- ```py copy filename="book.py"
-
- from uagents import Context, Model, Protocol
- from .query import TableStatus
-
- class BookTableRequest(Model):
- table_number: int
- time_start: int
- duration: int
-
- class BookTableResponse(Model):
- success: bool
-
- book_proto = Protocol()
- @book_proto.on_message(model=BookTableRequest, replies=BookTableResponse)
- async def handle_book_request(ctx: Context, sender: str, msg: BookTableRequest):
- tables = {
- int(num): TableStatus(**status)
- for (
- num,
- status,
- ) in ctx.storage._data.items()
- if isinstance(num, int)
- }
- table = tables[msg.table_number]
- if (
- table.time_start <= msg.time_start
- and table.time_end >= msg.time_start + msg.duration
- ):
- success = True
- table.time_start = msg.time_start + msg.duration
- ctx.storage.set(msg.table_number, table.dict())
- else:
- success = False
- # send the response
- await ctx.send(sender, BookTableResponse(success=success))
-
- ```
-
-
-
- ```py copy filename="book.py"
-
-
- from uagents import Context, Model, Protocol
- from .query import TableStatus
-
- class BookTableRequest(Model):
- table_number: int
- time_start: int
- duration: int
-
- class BookTableResponse(Model):
- success: bool
-
- book_proto = Protocol()
- @book_proto.on_message(model=BookTableRequest, replies=BookTableResponse)
- async def handle_book_request(ctx: Context, sender: str, msg: BookTableRequest):
- tables = {
- int(num): TableStatus(**status)
- for (
- num,
- status,
- ) in ctx.storage._data.items()
- if isinstance(num, int)
- }
- table = tables[msg.table_number]
- if (
- table.time_start <= msg.time_start
- and table.time_end >= msg.time_start + msg.duration
- ):
- success = True
- table.time_start = msg.time_start + msg.duration
- ctx.storage.set(msg.table_number, table.dict())
- else:
- success = False
- # send the response
- await ctx.send(sender, BookTableResponse(success=success))
-
- ```
-
-
-
-
-
-
-### The Agents
-
-#### Restaurant
-
-
-
-
-
-
-
-
- ```py copy filename="restaurant.py"
-
- from uagents import Agent, Context
- from uagents.setup import fund_agent_if_low
- from protocols.book import book_proto
- from protocols.query import query_proto, TableStatus
-
- restaurant = Agent(
- name="restaurant",
- port=8001,
- seed="restaurant secret phrase",
- endpoint=["http://127.0.0.1:8001/submit"],
- )
-
- fund_agent_if_low(restaurant.wallet.address())
-
- # build the restaurant agent from stock protocols
- restaurant.include(query_proto)
- restaurant.include(book_proto)
- TABLES = {
- 1: TableStatus(seats=2, time_start=16, time_end=22),
- 2: TableStatus(seats=4, time_start=19, time_end=21),
- 3: TableStatus(seats=4, time_start=17, time_end=19),
- }
-
- # set the table availability information in the restaurant protocols
- for (number, status) in TABLES.items():
- restaurant._storage.set(number, status.dict())
-
- if __name__ == "__main__":
- restaurant.run()
-
- ```
-
-
-
- ```py copy filename="restaurant.py"
-
- from uagents import Agent, Context
- from book import book_proto
- from query import query_proto, TableStatus
-
- # build the restaurant agent from stock protocols
- agent.include(query_proto)
- agent.include(book_proto)
-
- TABLES = {
- 1: TableStatus(seats=2, time_start=16, time_end=22),
- 2: TableStatus(seats=4, time_start=19, time_end=21),
- 3: TableStatus(seats=4, time_start=17, time_end=19),
- }
-
- # set the table availability information in the restaurant protocols
- for (number, status) in TABLES.items():
- agent._storage.set(number, status.dict())
-
- ```
-
-
-
-
-
-
-#### Customer/user
-
-
-
-
-
-
-
-
- ```py copy filename="user.py"
-
- from protocols.book import BookTableRequest, BookTableResponse
- from protocols.query import (
- QueryTableRequest,
- QueryTableResponse,
- )
- from uagents import Agent, Context
- from uagents.setup import fund_agent_if_low
-
- RESTAURANT_ADDRESS = "agent1qw50wcs4nd723ya9j8mwxglnhs2kzzhh0et0yl34vr75hualsyqvqdzl990"
-
- user = Agent(
- name="user",
- port=8000,
- seed="user secret phrase",
- endpoint=["http://127.0.0.1:8000/submit"],
- )
-
- fund_agent_if_low(user.wallet.address())
-
- table_query = QueryTableRequest(
- guests=3,
- time_start=19,
- duration=2,
- )
-
- # This on_interval agent function performs a request on a defined period
- @user.on_interval(period=3.0, messages=QueryTableRequest)
- async def interval(ctx: Context):
- completed = ctx.storage.get("completed")
-
- if not completed:
- await ctx.send(RESTAURANT_ADDRESS, table_query)
-
- @user.on_message(QueryTableResponse, replies={BookTableRequest})
- async def handle_query_response(ctx: Context, sender: str, msg: QueryTableResponse):
- if len(msg.tables) > 0:
- ctx.logger.info("There is a free table, attempting to book one now")
-
- table_number = msg.tables[0]
-
- request = BookTableRequest(
- table_number=table_number,
- time_start=table_query.time_start,
- duration=table_query.duration,
- )
-
- await ctx.send(sender, request)
-
- else:
-
- ctx.logger.info("No free tables - nothing more to do")
- ctx.storage.set("completed", True)
-
- @user.on_message(BookTableResponse, replies=set())
- async def handle_book_response(ctx: Context, _sender: str, msg: BookTableResponse):
- if msg.success:
- ctx.logger.info("Table reservation was successful")
-
- else:
- ctx.logger.info("Table reservation was UNSUCCESSFUL")
-
- ctx.storage.set("completed", True)
-
- if __name__ == "__main__":
- user.run()
-
- ```
-
-
-
- ```py copy filename="user.py"
-
- from book import BookTableRequest, BookTableResponse
- from query import (
- QueryTableRequest,
- QueryTableResponse,
- )
- from uagents import Agent, Context
-
- RESTAURANT_ADDRESS = "agent1qw50wcs4nd723ya9j8mwxglnhs2kzzhh0et0yl34vr75hualsyqvqdzl990"
-
- table_query = QueryTableRequest(
- guests=3,
- time_start=19,
- duration=2,
- )
-
- # This on_interval agent function performs a request on a defined period
- @agent.on_interval(period=3.0, messages=QueryTableRequest)
- async def interval(ctx: Context):
- completed = ctx.storage.get("completed")
-
- if not completed:
- await ctx.send(RESTAURANT_ADDRESS, table_query)
-
- @agent.on_message(QueryTableResponse, replies={BookTableRequest})
- async def handle_query_response(ctx: Context, sender: str, msg: QueryTableResponse):
- if len(msg.tables) > 0:
- ctx.logger.info("There is a free table, attempting to book one now")
-
- table_number = msg.tables[0]
-
- request = BookTableRequest(
- table_number=table_number,
- time_start=table_query.time_start,
- duration=table_query.duration,
- )
-
- await ctx.send(sender, request)
-
- else:
-
- ctx.logger.info("No free tables - nothing more to do")
- ctx.storage.set("completed", True)
-
- @agent.on_message(BookTableResponse, replies=set())
- async def handle_book_response(ctx: Context, _sender: str, msg: BookTableResponse):
- if msg.success:
- ctx.logger.info("Table reservation was successful")
-
- else:
- ctx.logger.info("Table reservation was UNSUCCESSFUL")
-
- ctx.storage.set("completed", True)
-
- ```
-
-
-
-
-
-
-### Expected output
-
-- Restaurant:
-
- ```
- INFO: [restaurant]: Registration on Almanac API successful
- INFO: [restaurant]: Registering on almanac contract...
- INFO: [restaurant]: Registering on almanac contract...complete
- INFO: [cleaner]: Agent inspector available at https://agentverse.ai/inspect/?uri=http%3A//127.0.0.1%3A8001&address=agent1qdfdx6952trs028fxyug7elgcktam9f896ayu9art4uaf75hwy2j9m87w
- INFO: [restaurant]: Starting server on http://0.0.0.0:8001 (Press CTRL+C to quit)
- INFO: [restaurant]: Query: guests=3 time_start=19 duration=2. Available tables: [2].
- ```
-
-- User:
-
- ```
- INFO: [ user]: Registration on Almanac API successful
- INFO: [ user]: Registering on almanac contract...
- INFO: [ user]: Registering on almanac contract...complete
- INFO: [ user]: Agent inspector available at https://agentverse.ai/inspect/?uri=http%3A//127.0.0.1%3A8000&address=agent1qvrskj36y7urk2j9g4gujgwvgr8v6jegm5druawmrpztmjjnep6ssn45p
- INFO: [ user]: Starting server on http://0.0.0.0:8000 (Press CTRL+C to quit)
- INFO: [ user]: There is a free table, attempting to book one now
- INFO: [ user]: Table reservation was successful
- ```
diff --git a/pages/examples/agent/verify-messages.mdx b/pages/examples/agent/verify-messages.mdx
deleted file mode 100644
index 37f39b1e6..000000000
--- a/pages/examples/agent/verify-messages.mdx
+++ /dev/null
@@ -1,108 +0,0 @@
-import { CodeGroup, DocsCode, GithubCodeSegment, CodeSegment } from "../../../components/code"
-
-# Verify messages with Agents
-
-## Introduction
-
-This file can be run on any platform supporting Python, with the necessary install permissions.
-This example shows how to use Agents to make them verify authenticity of messages sent with one another.
-
-Please check out the example code in our [examples repo ↗️](https://github.com/fetchai/uAgent-Examples/tree/main/5-documentation/examples/intermediate/verify-messages) to run this locally.
-
-### Supporting documentation
-
-- [Creating an agent ↗️](/guides/agents/create-a-uagent)
-- [Communicating with other agents ↗️](/guides/agents/communicating-with-other-agents)
-- [Register in Almanac ↗️](/guides/agents/register-in-almanac)
-- [Almanac Contract ↗️](/references/contracts/uagents-almanac/almanac-overview)
-- [Protocols ↗️](/references/uagents/uagents-protocols/agent-protocols)
-- [How to use agents to verify messages ↗️](/guides/agents/advanced/message-verification)
-
-### The agent
-
-
-
-
-
-
-
- ```py copy filename="message_verification.py"
-
- import hashlib
- from uagents import Agent, Bureau, Context, Model
- from uagents.crypto import Identity
- class Message(Model):
- message: str
- digest: str
- signature: str
-
- def encode(message: str) -> bytes:
- hasher = hashlib.sha256()
- hasher.update(message.encode())
- return hasher.digest()
-
- alice = Agent(name="alice", seed="alice recovery password")
- bob = Agent(name="bob", seed="bob recovery password")
-
- @alice.on_interval(period=3.0)
- async def send_message(ctx: Context):
- msg = "hello there bob"
- digest = encode(msg)
-
- await ctx.send(
- bob.address,
- Message(message=msg, digest=digest.hex(), signature=alice.sign_digest(digest)),
- )
-
- @alice.on_message(model=Message)
- async def alice_rx_message(ctx: Context, sender: str, msg: Message):
- assert Identity.verify_digest(
- sender, bytes.fromhex(msg.digest), msg.signature
- ), "couldn't verify bob's message"
-
- ctx.logger.info("Bob's message verified!")
- ctx.logger.info(f"Received message from {sender}: {msg.message}")
-
- @bob.on_message(model=Message)
- async def bob_rx_message(ctx: Context, sender: str, msg: Message):
- assert Identity.verify_digest(
- sender, bytes.fromhex(msg.digest), msg.signature
- ), "couldn't verify alice's message"
-
- ctx.logger.info("Alice's message verified!")
- ctx.logger.info(f"Received message from {sender}: {msg.message}")
-
- msg = "hello there alice"
- digest = encode(msg)
-
- await ctx.send(
- alice.address,
- Message(message=msg, digest=digest.hex(), signature=bob.sign_digest(digest)),
- )
-
- bureau = Bureau()
- bureau.add(alice)
- bureau.add(bob)
-
- if __name__ == "__main__":
- bureau.run()
-
- ```
-
-
-
-
-
-
-### Expected output
- ```
- [ bob]: Alice's message verified!
- [ bob]: Received message from agent1qf5gfqm48k9acegez3sg82ney2aa6l5fvpwh3n3z0ajh0nam3ssgwnn5me7: hello there bob
- [alice]: Bob's message verified!
- [alice]: Received message from agent1qvjjle8dlf22ff7zsh6wr3gl8tdepzygftdxpc2vn8539ngt962a709c90s: hello there alice
- ```
\ No newline at end of file
diff --git a/pages/examples/agent/wallet-messaging.mdx b/pages/examples/agent/wallet-messaging.mdx
deleted file mode 100644
index 8aa6d45e0..000000000
--- a/pages/examples/agent/wallet-messaging.mdx
+++ /dev/null
@@ -1,250 +0,0 @@
-import { CodeGroup, DocsCode, GithubCodeSegment, CodeSegment } from "../../../components/code"
-
-# Communicating with other agents wallet
-
-## Introduction
-
-Communication is an essential feature agent network. It allows agents to work together, exchange information, and forms an organic
-marketplace. Wallet messaging is feature of agents which makes them able to communicate with other agent's wallet information. This
-can include sending and receiving payments, querying account balances, and handling other wallet-related tasks.
-
-In this example we will create two agents locally using `uagents` library and make them share wallet information with each other.
-
-Please check out the example code in our [examples repo ↗️](https://github.com/fetchai/uAgent-Examples/tree/main/5-documentation/examples/intermediate/wallet-messaging) to run this locally.
-
-### Supporting documentation
-
-- [Creating an agent↗️](/guides/agents/create-a-uagent)
-- [Creating an interval task ↗️](/guides/agents/interval-task)
-- [Communicating with other agents ↗️](/guides/agents/communicating-with-other-agents)
-- [Register in Almanac ↗️](/guides/agents/register-in-almanac)
-- [Almanac Contract ↗️](/references/contracts/uagents-almanac/almanac-overview)
-- [Agents address ↗️](/guides/agents/getting-started/getting-uagent-address)
-
-### Script Breakdown
-
- - Importing required libraries
-
-
-
-
-
-
-
- ```py copy filename="wallet_messaging.py"
-
- from uagents import Agent, Bureau, Context
- from uagents.wallet_messaging import WalletMessage
-
- ```
-
-
-
-
-
-
- This step imports necessary libraries for creating agents and handling wallet messaging.
-
- - Defining two agents that can communicate with each other.
-
-
-
-
-
-
-
- ```py copy filename="wallet_messaging.py"
-
-
- ALICE_SEED = "alice dorado recovery phrase"
- BOB_SEED = "bob dorado recovery phrase"
-
- alice = Agent(name="alice", seed=ALICE_SEED, enable_wallet_messaging = True)
- bob = Agent(name="bob", seed=BOB_SEED, enable_wallet_messaging = True)
-
-
- ```
-
-
-
-
-
-
- This step defines two agents, Alice and Bob, using predefined seed phrases. These agents will communicate with each other's wallets.
-
- - Agent 1 wallet message handler:
-
-
-
-
-
-
-
- ```py copy filename="wallet_messaging.py"
-
- @alice.on_wallet_message()
- async def reply(ctx: Context, msg: WalletMessage):
- ctx.logger.info(f"Got wallet message: {msg.text}")
- await ctx.send_wallet_message(msg.sender, "hey, thanks for the message")
-
- ```
-
-
-
-
-
-
- This step defines a message handler for Alice, which responds to incoming wallet messages from Bob. Upon receiving a message, Alice sends a reply.
-
- - Agent 2 wallet message handler and `on_interval` sender:
-
-
-
-
-
-
-
- ```py copy filename="wallet_messaging.py"
-
-
- @bob.on_interval(period=5)
- async def send_message(ctx: Context):
- ctx.logger.info("Sending message...")
- await ctx.send_wallet_message(alice.address, "hello")
-
- @bob.on_wallet_message()
- async def wallet_reply(ctx: Context, msg: WalletMessage):
- ctx.logger.info(f"Got wallet message: {msg.text}")
-
-
- ```
-
-
-
-
-
-
- This step defines a message handler for Bob, which logs incoming wallet messages. Additionally, it sets up an interval function for Bob to send a message to Alice every 5 seconds.
-
- - Defining `Bureau` and adding agents:
-
-
-
-
-
-
-
- ```py copy filename="wallet_messaging.py"
-
-
- bureau = Bureau()
- bureau.add(alice)
- bureau.add(bob)
- bureau.run()
-
- ```
-
-
-
-
-
-
- This step creates a Bureau, which manages the agents, and adds both Alice and Bob to it. Then, it starts the bureau to begin agent interactions.
-
-### Whole Script
-
-This section presents the entire script in one block, allowing users to easily copy and paste it for testing or deployment.
-
-
-
-
-
-
-
- ```py copy filename="wallet_messaging.py"
-
- from uagents import Agent, Bureau, Context
- from uagents.wallet_messaging import WalletMessage
-
- ALICE_SEED = "alice dorado recovery phrase"
- BOB_SEED = "bob dorado recovery phrase"
-
- alice = Agent(name="alice", seed=ALICE_SEED, enable_wallet_messaging = True)
- bob = Agent(name="bob", seed=BOB_SEED, enable_wallet_messaging = True)
-
-
- @alice.on_wallet_message()
- async def reply(ctx: Context, msg: WalletMessage):
- ctx.logger.info(f"Got wallet message: {msg.text}")
- await ctx.send_wallet_message(msg.sender, "hey, thanks for the message")
-
- @bob.on_interval(period=5)
- async def send_message(ctx: Context):
- ctx.logger.info("Sending message...")
- await ctx.send_wallet_message(alice.address, "hello")
-
- @bob.on_wallet_message()
- async def wallet_reply(ctx: Context, msg: WalletMessage):
- ctx.logger.info(f"Got wallet message: {msg.text}")
-
- bureau = Bureau()
- bureau.add(alice)
- bureau.add(bob)
- bureau.run()
-
- ```
-
-
-
-
-
-
-### Script Execution
-
- - Open terminal and navigate to the folder where `wallet_messaging.py` is stored.
- - Run `pip3 install uagents[wallet]` on your terminal.
- - Execute `wallet_messaging.py` using `python wallet_messaging.py` on terminal.
-
-### Expected Output
-
- ```
- INFO: [alice]: Connecting to wallet messaging server
- INFO: [ bob]: Sending message...
- INFO: [ bob]: Connecting to wallet messaging server
- INFO: [bureau]: Starting server on http://0.0.0.0:8000 (Press CTRL+C to quit)
- INFO: [alice]: Got wallet message: hello
- INFO: [ bob]: Got wallet message: hey, thanks for the message
- INFO: [ bob]: Sending message...
- INFO: [alice]: Got wallet message: hello
- INFO: [ bob]: Got wallet message: hey, thanks for the message
- ```
diff --git a/pages/examples/agentverse-api/_meta.json b/pages/examples/agentverse-api/_meta.json
deleted file mode 100644
index 750a2194c..000000000
--- a/pages/examples/agentverse-api/_meta.json
+++ /dev/null
@@ -1,12 +0,0 @@
-{
- "agent-and-function-api": {
- "title": "Agents and Functions Creation using APIs [intermediate]",
- "tags": ["Intermediate", "Python", "Functions", "Agentverse"],
- "timestamp": true
- },
- "agent-secret-api": {
- "title": "Adding Secret to agent using Agentverse API [intermediate]",
- "tags": ["Intermediate", "Python", "Secrets", "Agentverse"],
- "timestamp": true
- }
-}
diff --git a/pages/examples/agentverse-api/agent-and-function-api.mdx b/pages/examples/agentverse-api/agent-and-function-api.mdx
deleted file mode 100644
index 5539f0b42..000000000
--- a/pages/examples/agentverse-api/agent-and-function-api.mdx
+++ /dev/null
@@ -1,467 +0,0 @@
-import { CodeGroup, DocsCode, GithubCodeSegment, CodeSegment } from "../../../components/code"
-
-# Agents and Functions Creation using APIs
-
-## Introduction
-
-This example provides details on how to create Agents and respective Agent Functions in Agentverse using APIs. We provide a Python script that interacts with Agentverse allowing us to create Agents and Agent Functions.
-
-Please check out the example code in our [examples repo ↗️](https://github.com/fetchai/uAgent-Examples/tree/main/5-documentation/examples/intermediate/agent-and-function-api) to run this locally.
-
-## Prerequisites
-
-- Before you begin, ensure you have the following:
-
- - Python version greater than 3.9 and less than 3.11.
- - The requests library installed. You can install it using `pip install requests`.
- - [Agentverse ↗️](https://agentverse.ai/) Credentials.
-
-## Steps to get API Tokens
-
- - Go to Profile section in [Agentverse ↗️](https://agentverse.ai/).
- - Click on button `+ New API Key`.
- - Give name to your API key.
- - Click on `write` for `Access to all resources in Agentverse` and click on `Generate API Key`
-
-
-
-## Steps to create agent and respective function
-
- - Open terminal and create a directory `agents` using `mkdir agents`.
- - Create a python file `agent.py` in this directory and include the following sample script in the Python file.
-
-
-
-
-
-
-
-
- ```py copy filename="agent.py"
-
- from uagents import Agent, Bureau, Context, Model
- from uagents.setup import fund_agent_if_low
- import requests
- from ai_engine import UAgentResponse, UAgentResponseType
-
-
- class Coordinates(Model):
- location: 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!
- location_agent = Agent(
- name="location_agent",
- seed=SEED_PHRASE,
- mailbox=True
- )
-
- fund_agent_if_low(location_agent.wallet.address())
-
- # Copy the address shown below
- print(f"Your agent's address is: {location_agent.address}")
-
- location_protocol = Protocol("Location Coordinates")
-
-
- async def location_coordinates(latitude, longitude):
- url = "https://geocoding-by-api-ninjas.p.rapidapi.com/v1/reversegeocoding"
- querystring = {"lat": latitude, "lon": longitude}
-
- headers = {
- "X-RapidAPI-Key": "YOUR_API_KEY",
- "X-RapidAPI-Host": "geocoding-by-api-ninjas.p.rapidapi.com",
- }
-
- response = requests.get(url, headers=headers, params=querystring)
-
- data = response.json()[0]["name"]
-
- return data
-
-
- @location_protocol.on_message(model=Coordinates, replies=UAgentResponse)
- async def location_coordinates_calculator(ctx: Context, sender: str, msg: Coordinates):
- ctx.logger.info(msg.location)
- latitude, longitude = map(str.strip, msg.location.split(","))
- city = location_coordinates(latitude, longitude)
- ctx.logger.info(city)
- message = city
- await ctx.send(
- sender, UAgentResponse(message=message, type=UAgentResponseType.FINAL)
- )
-
-
- location_agent.include(location_protocol)
-
- location_agent.run()
-
-```
-
-
-
- ```py copy filename="agent.py"
-
- import requests
- from ai_engine import UAgentResponse, UAgentResponseType
-
- class Coordinates(Model):
- location: str
-
- location_protocol = Protocol("Location Coordinates")
-
- async def location_coordinates(latitude, longitude):
- url = "https://geocoding-by-api-ninjas.p.rapidapi.com/v1/reversegeocoding"
- querystring = {"lat": latitude, "lon": longitude}
-
- headers = {
- "X-RapidAPI-Key": "YOUR_API_KEY",
- "X-RapidAPI-Host": "geocoding-by-api-ninjas.p.rapidapi.com",
- }
-
- response = requests.get(url, headers=headers, params=querystring)
-
- data = response.json()[0]["name"]
-
- return data
-
- @location_protocol.on_message(model=Coordinates, replies=UAgentResponse)
- async def location_coordinates_calculator(ctx: Context, sender: str, msg: Coordinates):
- ctx.logger.info(msg.location)
- latitude, longitude = map(str.strip, msg.location.split(","))
- city = location_coordinates(latitude, longitude)
- ctx.logger.info(city)
- message = city
- await ctx.send(
- sender, UAgentResponse(message=message, type=UAgentResponseType.FINAL)
- )
-
- agent.include(location_protocol)
-
-```
-
-
-
-
-
-
-- Create a python file with name `agent_create.py`.
-
-### Script breakdown
-
-- Importing required libraries and setting up authorization token:
-
-``` python
-# Importing Required libraries
-import time
-import requests
-
-# Define access token
-token = 'Bearer '
-```
-
-- Taking agent Name from user and storing agent address:
-
-```python
-# Take name of agent from user
-name = input("Please give name of your agent? ")
-# Create payload for agent creation request
-agent_creation_data = {"name": name}
-# Post request to create an agent and store address
-response_agent = requests.post(
- "https://agentverse.ai/v1/hosting/agents",
- json=agent_creation_data,
- headers={"Authorization": token},
-).json()
-
-address = response_agent["address"]
-print(f"Agent Address : {address}")
-```
-
-- Taking code from `agent.py` file and storing it as created agent script:
-
-```python
-# Reading code to be placed in agent
-with open("agent.py", "r") as file:
- code = file.read()
-agent_code_data = {"code": code}
-
-# Creating agent.py script for created agent
-response_code_update = requests.put(
- f"https://agentverse.ai/v1/hosting/agents/{address}/code",
- json=agent_code_data,
- headers={"Authorization": token},
-)
-
-# Starting the agent
-requests.post(
- f"https://agentverse.ai/v1/hosting/agents/{address}/start",
- headers={"Authorization": token},
-)
-time.sleep(10) # waiting before getting agent's protocol
-```
-
-- Requesting protocol digest for the created Agent:
-
-```python
-# Request to get agent protocol digest
-response_protcol = requests.get(
- f"https://agentverse.ai/v1/almanac/agents/{address}",
- headers={"Authorization": token},
-)
-protocol_digest = response_protcol.json()["protocols"][1]
-print(f"Protocol Digest : {protocol_digest}")
-time.sleep(10) # Waiting before getting model_digest
-
-# Request to get agent's model details
-response_model = requests.get(
- f"https://agentverse.ai/v1/almanac/manifests/protocols/{protocol_digest}",
- headers={"Authorization": token},
-)
-model = response_model.json()["models"]
-time.sleep(10) # Waiting before storing details to create functions
-
-function_group_ids = requests.get(
- "https://agentverse.ai/v1beta1/function-groups/", headers={"Authorization": token}
-)
-function_group_id = function_group_ids.json()[0]["uuid"]
-time.sleep(10)
-```
-
-- Saving all the details required for creating function and creating function on basis of details received:
-
-```python
-# Taking inputs from user for details required to create a function
-name_service = input("Please give function name: ")
-description = input("Please enter function description: ")
-field_name = input("Please enter field name: ")
-field_description = input("Please enter field description: ")
-tasktype = input("Please tell primary or secondary function: ").upper()
-
-# Logging details provided by user
-print(
- f"Service name: {name_service} \nFunction Description: {description} \nField Name: {field_name}\nField Description: {field_description}\nTask Type: {tasktype}"
-)
-
-# Storing model digest and name to be used for function creation
-model_digest = response_model.json()["interactions"][0]["request"].replace("model:", "")
-print(f"Model Digest : {model_digest}")
-model_name = model[0]["schema"]["title"]
-print(f"Model Name : {model_name}")
-
-# Creating payload for function creation
-data = {
- "agent": address,
- "name": name_service,
- "description": description,
- "protocolDigest": protocol_digest,
- "modelDigest": model_digest,
- "modelName": model_name,
- "arguments": [
- {
- "name": field_name,
- "required": True,
- "type": "string",
- "description": field_description,
- }
- ],
- "type": tasktype,
-}
-
-# Requesting AI Engine function API to create a function with created payload and storing the response.
-response_function = requests.post(
- "https://agentverse.ai/v1beta1/functions/",
- json=data,
- headers={"Authorization": token},
-)
-# Storing name of function and printing it to check if function was created successfully
-name = response_function.json()["name"]
-print(f"Function Created with name: {name}")
-```
-
-### Whole Script
-
-
-
-
-
-
-
- ```py copy filename="agent_create.py"
-
- # Importing Required libraries
- import time
- import requests
-
- # Decode the refresh token
- token = f'Bearer '
-
- # Take name of agent from user
- name = input("Please give name of your agent? ")
- # Create payload for agent creation request
- agent_creation_data = {"name": name}
- # Post request to create an agent and store address
- response_agent = requests.post(
- "https://agentverse.ai/v1/hosting/agents",
- json=agent_creation_data,
- headers={"Authorization": token},
- ).json()
-
- address = response_agent["address"]
- print(f"Agent Address : {address}")
-
- # Reading code to be placed in agent
- with open("agent.py", "r") as file:
- code = file.read()
- agent_code_data = {"code": code}
-
- # Creating agent.py script for created agent
- response_code_update = requests.put(
- f"https://agentverse.ai/v1/hosting/agents/{address}/code",
- json=agent_code_data,
- headers={"Authorization": token},
- )
-
- # Starting the agent
- requests.post(
- f"https://agentverse.ai/v1/hosting/agents/{address}/start",
- headers={"Authorization": token},
- )
- time.sleep(10) # waiting before getting agent's protocol
-
- # Request to get agent protocol digest
- response_protcol = requests.get(
- f"https://agentverse.ai/v1/almanac/agents/{address}",
- headers={"Authorization": token},
- )
- protocol_digest = response_protcol.json()["protocols"][1]
- print(f"Protocol Digest : {protocol_digest}")
- time.sleep(10) # Waiting before getting model_digest
-
- # Request to get agent's model details
- response_model = requests.get(
- f"https://agentverse.ai/v1/almanac/manifests/protocols/{protocol_digest}",
- headers={"Authorization": token},
- )
- model = response_model.json()["models"]
- time.sleep(10) # Waiting before storing details to create functions
-
- function_group_ids = requests.get(
- "https://agentverse.ai/v1beta1/function-groups/", headers={"Authorization": token}
- )
- function_group_id = function_group_ids.json()[0]["uuid"]
- time.sleep(10)
-
- # Taking inputs from user for details required to create a function
- name_service = input("Please give function name: ")
- description = input("Please enter function description: ")
- field_name = input("Please enter field name: ")
- field_description = input("Please enter field description: ")
- tasktype = input("Please tell primary or secondary function: ").upper()
-
- # Logging details provided by user
- print(
- f"Service name: {name_service} \nFunction Description: {description} \nField Name: {field_name}\nField Description: {field_description}\nTask Type: {tasktype}"
- )
-
- # Storing model digest and name to be used for function creation
- model_digest = response_model.json()["interactions"][0]["request"].replace("model:", "")
- print(f"Model Digest : {model_digest}")
- model_name = model[0]["schema"]["title"]
- print(f"Model Name : {model_name}")
-
- # Creating payload for function creation
- data = {
- "agent": address,
- "name": name_service,
- "description": description,
- "protocolDigest": protocol_digest,
- "modelDigest": model_digest,
- "modelName": model_name,
- "arguments": [
- {
- "name": field_name,
- "required": True,
- "type": "string",
- "description": field_description,
- }
- ],
- "type": tasktype,
- }
-
- # Requesting AI Engine function API to create a function with created payload and storing the response.
- response_function = requests.post(
- "https://agentverse.ai/v1beta1/functions/",
- json=data,
- headers={"Authorization": token},
- )
- # Storing name of function and printing it to check if function was created successfully
- name = response_function.json()["name"]
- print(f"Function Created with name: {name}")
-
-```
-
-
-
-
-
-
-## Steps to run the script
-
-1. Open terminal and go to directory `agents` created above.
-2. Make sure `agent.py` and `agent_create.py` are in this directory.
-3. Open [Agentverse ↗️](https://agentverse.ai/) and [generate API keys ↗️](../../guides/apis/agent-function-creation-apis#how-to-get-agentverse-api-tokens).
-4. Open script in editor and replace `token`.
-5. Run command `python agent_create.py` and enter the required details.
-6. Provide Agent and Function Details as asked and check agent and function on Agentverse.
-
-## Expected Output
-
-- Provide all details asked in the script.
-
-```
-abc@xyz-MacBook-Pro agents % python3 agents_create.py
-Please give name of your agent? my first API agent
-Agent Address : agent1q06l8hekn859e5rtwufewmyhwghe6j9y00g0wc8u7gcx05cjfk98jyf6lte
-Protocol Digest : c7a6f160fd8d8b7cb357dad9b5be420510ce466dbb67051c07caf2b860216b01
-Please give function name: location finder
-Please enter function description: this function helps to find nearest city using coordinates
-Please enter field name: location
-Please enter field description: this describes the coordinates of the location in string format longitude latitude
-Please tell primary or secondary function: primary
-Service name: location finder
-Function Description: this function helps to find nearest city using coordinates
-Field Name: location
-Field Description: this describes the coordinates of the location in string format longitude latitude
-Task Type: PRIMARY
-Model Digest : 10a2f843c4c92955688d5e7f22fabe79623869eabfcd97d97da83527b436d3e2
-Model Name : Coordinates
-Function Created with name: location finder
-```
-
-- Agent created on Agentverse
-
-
-
-- Function created on Agentverse
-
-
diff --git a/pages/examples/agentverse-api/agent-secret-api.mdx b/pages/examples/agentverse-api/agent-secret-api.mdx
deleted file mode 100644
index 97c7f78d0..000000000
--- a/pages/examples/agentverse-api/agent-secret-api.mdx
+++ /dev/null
@@ -1,94 +0,0 @@
-import { CodeGroup, DocsCode, GithubCodeSegment, CodeSegment } from "../../../components/code"
-
-# Adding Secret to agent using Agentverse API
-
-## Introduction
-
-This example provides details on how to use the hosting API to add a secret to an agent. Secrets are added to an agent to ensure they remain hidden from end users and to enhance security.
-
-Please check out the example code in our [examples repo ↗️](https://github.com/fetchai/uAgent-Examples/tree/main/5-documentation/examples/intermediate/agent-secret-api) to run this locally.
-
-## Prerequisites
-
-- Before you begin, ensure you have the following:
- - Python version greater than 3.9 and less than 3.11.
- - The requests library installed. You can install it using `pip install requests`.
- - [Agentverse ↗️](https://agentverse.ai/) Credentials.
-
-## Steps to get API Tokens
-
- - Go to Profile section in [Agentverse ↗️](https://agentverse.ai/).
- - Click on button `+ New API Key`.
- - Give name to your API key.
- - Click on `write` for `Access to all resources in Agentverse` and click on `Generate API Key`
-
-
-
-## Script to add secret to agent
-
-
-
-
-
-
-
- ```py copy filename="agent-secret.py"
-
- # Importing libraries
- import requests
-
- # Decode the refresh token
- token = 'Bearer fauna_access_token'
-
- # Take name of agent and secret details from user
- address = input('Please enter address of agent to which you want to add the secret: ')
- name = input("Please enter name for your secret: ")
- secret = input("Please enter value for your secret: ")
-
- # Create Payload for post request
- data = {
- 'address': address,
- 'name': name,
- 'secret': secret
- }
-
- # Post request to add secret to agent
- response_agent = requests.post("https://agentverse.ai/v1/hosting/secrets", json=data, headers={"Authorization": token})
-
-
- # Check if the response code is 200
- if response_agent.status_code == 200:
- print("Secret added successfully.")
- else:
- print(f"Failed to add secret. Status code: {response_agent.status_code}")
-
-```
-
-
-
-
-
-
-## Steps to add secret to agent using API
-
- - Navigate to the directory where the `agent-secret` script is located using the terminal.
- - Open [Agentverse ↗️](https://agentverse.ai/) and [generate API keys ↗️](../../guides/apis/agent-function-creation-apis#how-to-get-agentverse-api-tokens).
- - Open script in editor and replace `fauna_access_token`.
- - Run `agent-secret.py` using `python agent-secret.py`.
- - Provide agent's address, secret name and secret value.
- - Use the secret name in the script instead of the value, for example `APIKey` in our case.
-
-### Expected Output
-
-- Provide details and response based on whether the secret was added to the agent in Agentverse or not.
-
-
-
-
-
-
\ No newline at end of file
diff --git a/pages/examples/agentverse/_meta.json b/pages/examples/agentverse/_meta.json
deleted file mode 100644
index 62adb08cd..000000000
--- a/pages/examples/agentverse/_meta.json
+++ /dev/null
@@ -1,23 +0,0 @@
-{
- "mailbox-agents": {
- "title": "Agents communication using Agentverse Mailbox service [intermediate]",
- "tags": ["Intermediate", "Python", "Communication", "Mailbox"],
- "timestamp": true
- },
-
- "on-query-proxy": {
- "title": "Query an agent using a proxy API [intermediate]",
- "tags": ["Intermediate", "Python", "Communication", "FastAPI", "Proxy"],
- "timestamp": true
- },
- "name-service": {
- "title": "Agents Name Service [intermediate]",
- "tags": ["Intermediate", "Python", "Name Service"],
- "timestamp": true
- },
- "running-an-agent-on-agentverse": {
- "title": "Run Agents on Agentverse [intermediate]",
- "tags": ["Intermediate", "Python", "Functions", "Agentverse"],
- "timestamp": true
- }
-}
diff --git a/pages/examples/agentverse/local-agent-registration.mdx b/pages/examples/agentverse/local-agent-registration.mdx
deleted file mode 100644
index 18354f0ef..000000000
--- a/pages/examples/agentverse/local-agent-registration.mdx
+++ /dev/null
@@ -1,126 +0,0 @@
-import { CodeGroup, DocsCode, GithubCodeSegment, CodeSegment } from "../../../components/code"
-
-# Register a local Agent as a Function
-
-## Introduction
-
-This file can be run on any platform supporting Python, with the necessary install permissions. This example shows one local agent registered as an Agent Function on the Agentverse and which can be queried on [DeltaV ↗️](/concepts/ai-engine/deltav).
-
-Please check out the example code in our [examples repo ↗️](https://github.com/fetchai/uAgent-Examples/tree/main/5-documentation/examples/intermediate/local-agent-registration) to run this locally.
-
-### Supporting documentation
-
-- [Creating an agent↗️](/guides/agents/create-a-uagent)
-
-- [Register in Almanac ↗️](/guides/agents/register-in-almanac)
-
-- [Almanac Contract ↗️](/references/contracts/uagents-almanac/almanac-overview)
-
-- [Protocols ↗️](/references/uagents/uagents-protocols/agent-protocols)
-
-- [Agentverse Functions ↗️](/guides/services/services)
-
-- [Running locally ↗️](/guides/agents/running-locally)
-
-- [Register an Agent Function on the Agentverse ↗️](/guides/agentverse/registering-agent-services)
-
-- [Register a local Agent Function on the Agentverse ↗️](/guides/agents/running-locally#register-your-agent-function-on-the-agentverse)
-
-### The script
-
-
-
-
-
-
-
-
- ```py copy filename="agent.py"
-
- from uagents.setup import fund_agent_if_low
- from uagents import Agent, Context, Protocol, Model
- import random
- from uagents import Field
- from ai_engine import UAgentResponse, UAgentResponseType
- import sys
-
- dungeons = Agent(
- name="dungeonsanddragonsdiceroll",
- port=6145,
- seed="RANDOM STRINGS",
- endpoint=["http://YOUR_IP:6145/submit"],
- )
-
- fund_agent_if_low(dungeons.wallet.address())
-
- @dungeons.on_event("startup")
- async def hi(ctx: Context):
- ctx.logger.info(dungeons.address)
-
- class Request(Model):
- dice_sides: int = Field(description="How many sides does your dice need?")
-
- dice_roll_protocol = Protocol("DungeonsAndDragonsDiceRoll")
-
- @dice_roll_protocol.on_message(model=Request, replies={UAgentResponse})
- async def roll_dice(ctx: Context, sender: str, msg: Request):
- result = str(random.randint(1, msg.dice_sides))
- message = f"Dice roll result: {result}"
- await ctx.send(
- sender, UAgentResponse(message=message, type=UAgentResponseType.FINAL)
- )
-
- dungeons.include(dice_roll_protocol, publish_manifest=True)
-
- dungeons.run()
-
- ```
-
-
-
- ```py copy filename="agent.py"
-
- from uagents import Agent, Context, Protocol, Model
- import random
- from uagents import Field
- from ai_engine import UAgentResponse, UAgentResponseType
-
- @agent.on_event("startup")
- async def hi(ctx: Context):
- ctx.logger.info(dungeons.address)
-
- class Request(Model):
- dice_sides: int = Field(description="How many sides does your dice need?")
-
- dice_roll_protocol = Protocol("DungeonsAndDragonsDiceRoll")
-
- @agent.on_message(model=Request, replies={UAgentResponse})
- async def roll_dice(ctx: Context, sender: str, msg: Request):
- result = str(random.randint(1, msg.dice_sides))
- message = f"Dice roll result: {result}"
- await ctx.send(
- sender, UAgentResponse(message=message, type=UAgentResponseType.FINAL)
- )
-
- agent.include(dice_roll_protocol, publish_manifest=True)
-
- ```
-
-
-
-
-
-
-### Register Agent Function
-
-For this step, head to this guide for [registering a local Agent Function on the Agentverse ↗️](/guides/agents/running-locally#register-your-agent-function-on-the-agentverse) for a detailed overview of the registration process.
diff --git a/pages/examples/agentverse/mailbox-agents.mdx b/pages/examples/agentverse/mailbox-agents.mdx
deleted file mode 100644
index 6d78456a2..000000000
--- a/pages/examples/agentverse/mailbox-agents.mdx
+++ /dev/null
@@ -1,121 +0,0 @@
-import { CodeGroup, DocsCode, GithubCodeSegment, CodeSegment } from "../../../components/code"
-
-# Agents communication using Agentverse Mailbox feature
-
-## Introduction
-
-This file can be run on any platform supporting Python, with the necessary install permissions. This example shows how to set up a communication between two agents using the uAgents Python library and the **Agentverse Mailbox service**.
-
-A **Mailbox** allows your agent to receive messages sent to its address even when this agent is offline. The Mailbox will automatically retrieve and handle stored messages once it comes online back again.
-
-Please check out the example code in our [examples repo ↗️](https://github.com/fetchai/uAgent-Examples/tree/main/5-documentation/examples/intermediate/mailbox-agents) to run this locally.
-
-### Supporting documentation
-
-- [Creating an agent↗️](/guides/agents/create-a-uagent)
-- [Creating an interval task ↗️](/guides/agents/interval-task)
-- [Communicating with other agents ↗️](/guides/agents/communicating-with-other-agents)
-- [Register in Almanac ↗️](/guides/agents/register-in-almanac)
-- [Almanac Contract ↗️](/references/contracts/uagents-almanac/almanac-overview)
-- [Utilising the Agentverse Mailroom service ↗️](/guides/agentverse/utilising-the-mailbox)
-
-### Agent 1: Local Agent
-
-
-
-
-
-
-
-
-
- ```py copy filename="agent_1.py"
- from uagents import Agent, Context, Model
- from uagents.setup import fund_agent_if_low
-
- 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,
- )
-
- fund_agent_if_low(agent.wallet.address())
-
- # 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}")
- ctx.logger.info("Sending message to bob")
- await ctx.send(sender, Message(message="hello there bob"))
-
- if __name__ == "__main__":
- agent.run()
- ```
-
-
-
-
-
-### Agent 2: Agentverse Agent
-
-
-
-
-
-
-
- ```py copy filename="agent_2.py"
- from uagents import Agent, Context, Model
-
- class Message(Model):
- message: str
-
- # Copy ALICE_ADDRESS generated in agent_1.py
- ALICE_ADDRESS = "agent1qfa53drat8rzau90u4494gx5mhj3v87tm4t5cuzkd7gkegxcm5vx5pku7kf"
-
- @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}")
- ```
-
-
-
-### Output
-
-1. Agentverse Agent output:
-
- ```
- 2024-06-27 11:20:19 Info Agent [INFO]: Sending message to alice
- 2024-06-27 11:20:19 Info Agent [INFO]: Received message from agent1qfa53drat8rzau90u4494gx5mhj3v87tm4t5cuzkd7gkegxcm5vx5pku7kf: hello there bob
- ```
-
-2. Local Agent output:
-
- ```
- INFO: [ALICE]: Received message from agent1qd3hd6peaejavk3uredlxz05e8tcx6purl5gpuamk22xduj7e37k2sqetaa: hello there alice
- INFO: [ALICE]: Sending message to bob
- ```
\ No newline at end of file
diff --git a/pages/examples/agentverse/name-service.mdx b/pages/examples/agentverse/name-service.mdx
deleted file mode 100644
index 70acfd4e3..000000000
--- a/pages/examples/agentverse/name-service.mdx
+++ /dev/null
@@ -1,174 +0,0 @@
-import { CodeGroup, DocsCode, GithubCodeSegment, CodeSegment } from "../../../components/code"
-
-# Agents Name Service
-
-## Introduction
-
-This file can be run on any platform supporting Python, with the necessary install permissions. This example shows how to set up Agents Name Services using the uAgents and CosmPy Python libraries.
-
-Please check out the example code in our [examples repo ↗️](https://github.com/fetchai/uAgent-Examples/tree/main/5-documentation/examples/intermediate/name-service) to run this locally.
-
-### Supporting documentation
-
-- [Creating an agent ↗️](/guides/agents/create-a-uagent)
-- [Creating an interval task ↗️](/guides/agents/interval-task)
-- [Communicating with other agents ↗️](/guides/agents/communicating-with-other-agents)
-- [Register in Almanac ↗️](/guides/agents/register-in-almanac)
-- [Almanac Contract ↗️](/references/contracts/uagents-almanac/almanac-overview)
-- [Wallets and private keys ↗️](/guides/fetch-network/cosmpy/creating-wallet)
-
-## The Agents
-
-### Agent 1
-
-
-
-
-
-
-
- ```py copy filename="agent_1.py"
-
- from cosmpy.aerial.wallet import LocalWallet
-
- from uagents.network import get_name_service_contract
- from uagents.setup import fund_agent_if_low
- from uagents import Agent, Context, Model
-
- class Message(Model):
- message: str
-
- bob = Agent(
- name="bob-0",
- seed="agent bob-0 secret phrase",
- port=8001,
- endpoint=["http://localhost:8001/submit"],
- )
-
- my_wallet = LocalWallet.from_unsafe_seed("registration test wallet")
- name_service_contract = get_name_service_contract(test=True)
- DOMAIN = "agent"
-
- for wallet in [my_wallet, bob.wallet]:
- fund_agent_if_low(wallet.address())
-
- @bob.on_event("startup")
- async def register_agent_name(ctx: Context):
- await name_service_contract.register(
- bob.ledger, my_wallet, bob.address, bob.name, DOMAIN
- )
-
- @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}")
-
- if __name__ == "__main__":
- bob.run()
-
- ```
-
-
-
-
-
-
-### Agent 2
-
-
-
-
-
-
-
-
- ```py copy filename="agent_2.py"
-
- from uagents.setup import fund_agent_if_low
- from uagents import Agent, Context, Model
-
- class Message(Model):
- message: str
-
- alice = Agent(
- name="alice-0",
- seed="agent alice-0 secret phrase",
- port=8000,
- endpoint=["http://localhost:8000/submit"],
- )
-
- fund_agent_if_low(alice.wallet.address())
-
- @alice.on_interval(period=5)
- async def alice_interval_handler(ctx: Context):
- bob_name = "bob-0.agent"
- ctx.logger.info(f"Sending message to {bob_name}...")
- await ctx.send(bob_name, Message(message="Hello there bob."))
-
- if __name__ == "__main__":
- alice.run()
-
- ```
-
-
-
- ```py copy filename="agent_2.py"
-
- from uagents import Agent, Context, Model
-
- class Message(Model):
- message: str
-
- @agent.on_interval(period=5)
- async def alice_interval_handler(ctx: Context):
- bob_name = "bob-0.agent"
- ctx.logger.info(f"Sending message to {bob_name}...")
- await ctx.send(bob_name, Message(message="Hello there bob."))
-
- ```
-
-
-
-
-
-
-## Expected output
-
-- Bob:
-
- ```
- INFO: [bob-0]: Registering on almanac contract...
- INFO: [bob-0]: Registering on almanac contract...complete
- INFO: [network]: Registering name...
- INFO: [network]: Registering name...complete
- INFO: [bob-0]: Starting server on http://0.0.0.0:8001 (Press CTRL+C to quit)
- INFO: [bob-0]: Received message from agent1qwquu2d237gntfugrnwch38g8jkl76vdr05qjm4wyps6ap04fvt8vtzhpqw: Hello there bob.
- INFO: [bob-0]: Received message from agent1qwquu2d237gntfugrnwch38g8jkl76vdr05qjm4wyps6ap04fvt8vtzhpqw: Hello there bob.
- INFO: [bob-0]: Received message from agent1qwquu2d237gntfugrnwch38g8jkl76vdr05qjm4wyps6ap04fvt8vtzhpqw: Hello there bob.
- INFO: [bob-0]: Received message from agent1qwquu2d237gntfugrnwch38g8jkl76vdr05qjm4wyps6ap04fvt8vtzhpqw: Hello there bob.
- ```
-- Alice:
-
- ```
- INFO: [alice-0]: Registering on almanac contract...
- INFO: [alice-0]: Registering on almanac contract...complete
- INFO: [alice-0]: Sending message to bob-0.agent...
- INFO: [alice-0]: Starting server on http://0.0.0.0:8000 (Press CTRL+C to quit)
- INFO: [alice-0]: Sending message to bob-0.agent...
- INFO: [alice-0]: Sending message to bob-0.agent...
- INFO: [alice-0]: Sending message to bob-0.agent...
- ```
diff --git a/pages/examples/agentverse/on-query-proxy.mdx b/pages/examples/agentverse/on-query-proxy.mdx
deleted file mode 100644
index 250abe0b2..000000000
--- a/pages/examples/agentverse/on-query-proxy.mdx
+++ /dev/null
@@ -1,180 +0,0 @@
-import { CodeGroup, DocsCode,GithubCodeSegment,CodeSegment } from "../../../components/code"
-
-# Query an agent using a proxy API
-
-## Introduction
-
-This file can be run on any platform supporting Python, with the necessary install permissions.
-This example shows how to query an agent using a proxy API.
-
-Please check out the example code in our [examples repo ↗️](https://github.com/fetchai/uAgent-Examples/tree/main/5-documentation/examples/intermediate/on-query-proxy) to run this locally.
-
-#### Supporting documentation
-
-- [Creating an agent ↗️](/guides/agents/create-a-uagent)
-- [Communicating with other agents ↗️](/guides/agents/communicating-with-other-agents)
-- [Register in Almanac ↗️](/guides/agents/register-in-almanac)
-- [Almanac Contract ↗️](/references/contracts/uagents-almanac/almanac-overview)
-- [Protocols ↗️](/references/uagents/uagents-protocols/agent-protocols)
-
-#### The agent
-
-
-
-
-
-
-
-
- ```py copy filename="agent.py"
-
- from uagents import Agent, Context, Model
-
- class TestRequest(Model):
- message: str
-
- class Response(Model):
- text: str
-
- agent = Agent(
- name="your_agent_name_here",
- seed="your_agent_seed_here",
- port=8001,
- endpoint="http://localhost:8001/submit",
- )
-
- @agent.on_event("startup")
- async def startup(ctx: Context):
- ctx.logger.info(f"Starting up {agent.name}")
- ctx.logger.info(f"With address: {agent.address}")
- ctx.logger.info(f"And wallet address: {agent.wallet.address()}")
-
- @agent.on_query(model=TestRequest, replies={Response})
- async def query_handler(ctx: Context, sender: str, _query: TestRequest):
- ctx.logger.info("Query received")
- try:
- # do something here
- await ctx.send(sender, Response(text="success"))
- except Exception:
- await ctx.send(sender, Response(text="fail"))
-
- if __name__ == "__main__":
- agent.run()
-
- ```
-
-
-
- ```py copy filename="agent.py"
-
- from uagents import Agent, Context, Model
-
- class TestRequest(Model):
- message: str
-
- class Response(Model):
- text: str
-
- @agent.on_event("startup")
- async def startup(ctx: Context):
- ctx.logger.info(f"Starting up {agent.name}")
- ctx.logger.info(f"With address: {agent.address}")
- ctx.logger.info(f"And wallet address: {agent.wallet.address()}")
-
- @agent.on_query(model=TestRequest, replies={Response})
- async def query_handler(ctx: Context, sender: str, _query: TestRequest):
- ctx.logger.info("Query received")
- try:
- # do something here
- await ctx.send(sender, Response(text="success"))
- except Exception:
- await ctx.send(sender, Response(text="fail"))
-
- ```
-
-
-
-
-
-
-The agent is created using the `Agent` class from `uagents` library. It is initialized with a `name`, `seed`, `port`, and `endpoint`.
-It defines an `on_event` handler for the "startup" event, where it logs information about the agent's initialization.
-It defines an `on_query` handler for handling queries of type `TestRequest`. Upon receiving a query, it processes it and sends back a `Response`.
-The agent is then set to run.
-
-#### Proxy
-
-
-
-
-
-
-
- ```py copy filename="proxy.py"
-
- import json
-
- from fastapi import FastAPI
- from pydantic import BaseModel
- from uagents.query import query
-
- AGENT_ADDRESS = "agent1qt6ehs6kqdgtrsduuzslqnrzwkrcn3z0cfvwsdj22s27kvatrxu8sy3vag0"
-
- class TestRequest(BaseModel):
- message: str
-
- async def agent_query(req):
- response = await query(destination=AGENT_ADDRESS, message=req, timeout=15.0)
- data = json.loads(response.decode_payload())
- return data["text"]
-
- app = FastAPI()
-
- @app.get("/")
- def read_root():
- return "Hello from the Agent controller"
-
- @app.post("/endpoint")
- async def make_agent_call(req: TestRequest):
- try:
- res = await agent_query(req)
- return f"successful call - agent response: {res}"
- except Exception:
- return "unsuccessful agent call"
-
- ```
-
-
-
-
-
-
-The proxy is implemented using `FastAPI`. It sets up two routes: `"/"` for a simple root message and `"/endpoint"` for receiving requests.
-When a `POST` request is made to `"/endpoint"` with a JSON payload containing a `TestRequest`, it triggers the `make_agent_call` function.
-Inside make_agent_call, it calls `agent_query` to communicate with the agent. The `agent` receives the query, processes it, and sends back a response.
-The proxy receives the response from the agent and sends back a success message along with the response text.
-
-#### Run the example
-
-In separate terminals:
-
-1. Run the FastAPI proxy: `uvicorn proxy:app`
-
-2. Run the agent: `python agent.py`
-
-3. Query the agent via the proxy: `curl -d '{"message": "test"}' -H "Content-Type: application/json" -X POST http://localhost:8000/endpoint`
diff --git a/pages/examples/agentverse/running-an-agent-on-agentverse.mdx b/pages/examples/agentverse/running-an-agent-on-agentverse.mdx
deleted file mode 100644
index 853ce017f..000000000
--- a/pages/examples/agentverse/running-an-agent-on-agentverse.mdx
+++ /dev/null
@@ -1,194 +0,0 @@
-import { CodeGroup, DocsCode, GithubCodeSegment,CodeSegment } from "../../../components/code"
-
-# Run Agents on Agentverse
-
-## Introduction
-
-You can create, host and run any type of agent you want to create within the [Agentverse ↗️](/concepts/agent-services/agentverse-intro). There are multiple ways you can do so. You can decide to either **create your agent directly on the Agentverse** platform using its functionalities and allowed imports, or you can **create your agents locally** and then enrol them within the Agentverse by using an **Endpoint** or a **Mailbox** to make them retrievable by any other agent registered on the ASI Network.
-
-Let's get started!
-
-Please check out the example code in our [examples repo ↗️](https://github.com/fetchai/uAgent-Examples/tree/main/5-documentation/examples/intermediate/running-an-agent-on-agentverse) to run this locally.
-
-## Supporting documentation
-
-- [Creating an agent ↗️](/guides/agents/create-a-uagent)
-- [Register in Almanac ↗️](/guides/agents/register-in-almanac)
-- [Almanac Contract ↗️](/references/contracts/uagents-almanac/almanac-overview)
-- [Agents address ↗️](/guides/agents/getting-started/getting-uagent-address)
-- [Protocols ↗️](/references/uagents/uagents-protocols/agent-protocols)
-- [Creating an Agentverse hosted agent ↗️](/guides/agentverse/creating-agentverse-agents/creating-a-hosted-agent)
-- [Agent Mailboxes ↗️](/guides/agents/intermediate/mailbox)
-- [Utilizing the Agentverse Mailroom feature ↗️](/guides/agentverse/agentverse-mailbox/utilising-the-mailbox)
-- [Options for running your Agents ↗️](/guides/agents/intermediate/options-for-running-local-agents)
-- [Agentverse: allowed imports ↗️](/guides/agentverse/creating-agentverse-agents/allowed-imports)
-
-## Create Agents hosted on the Agentverse
-
-It is possible to create agents directly on the Agentverse using the [My Agents ↗️](/concepts/agent-services/agent-hosting) tab.
-
-### Create and run an agent on Agentverse
-
-Let's create a simple agent introducing itself and printing its `address` every 3 seconds using the tools provided within the Agentverse platform. Sign in to [Agentverse ↗️](https://agentverse.ai/) and select the **My Agents** tab. Here, select an option to create an agent by clicking on the **+ New Agent** button and select **Blank Agent**. Copy the code below and paste it into the Agent Editor window that appears after you enter the Agent Name:
-
- ```py copy filename="simple_agent.py"
- @agent.on_interval(period=3.0)
- async def say_hello(ctx: Context):
- ctx.logger.info(f"Hello, I'm an agent and my address is {agent.address}.")
-
- if __name__ == "__main__":
- agent.run()
- ```
-
-Once you are happy with the code, click on **Start** button to start your agent and see the output within the in-built terminal. You should see something similar to:
-
- ```
- 2024-07-10 13:48:54 Info Agent [INFO]: Hello, I'm an agent and my address is agent1qv7qyzyjw4kse7x4p7nv2m2qfxur2r4m03m4x2h4qssyl4k3stz72gas84s.
- 2024-07-10 13:48:57 Info Agent [INFO]: Hello, I'm an agent and my address is agent1qv7qyzyjw4kse7x4p7nv2m2qfxur2r4m03m4x2h4qssyl4k3stz72gas84s.
- 2024-07-10 13:49:00 Info Agent [INFO]: Hello, I'm an agent and my address is agent1qv7qyzyjw4kse7x4p7nv2m2qfxur2r4m03m4x2h4qssyl4k3stz72gas84s.
- ```
-
-For a better understanding of Agentverse hosted agents, head over to this [guide ↗️](/guides/agentverse/creating-agentverse-agents/creating-a-hosted-agent).
-
-## Create agents locally
-
-You can also run a **local agent** on the Agentverse so to make it able to communicate with other agents registered on the ASI Network and the Agentverse. This may be the case where you want to run an agent on your own hardware or infrastructure (e.g., VM, your laptop, Raspberry pi or tweak for Agentverse).
-
-Whenever you create a local agent, you can either run a it on the Agentverse by using an **endpoint** or an Agentverse **Mailbox**.
-
-### Run a local agent using an endpoint
-
-Let's consider the following local agent code:
-
-
-
-
-
-
-
- ```py copy filename="agent.py"
-
- from uagents import Agent, Model, Protocol
-
-
- class Message(Model):
- message: str
-
-
- agent = Agent(
- name="TestAgent",
- port=6145,
- seed="RANDOM STRINGS",
- endpoint=["http://YOUR_IP:6145/submit"],
- )
-
- test_protocol = Protocol("TestProtocol")
-
- # Define your agent protocols
- # Include the protocols within your agent
- agent.include(test_protocol, publish_manifest=True)
-
- agent.run()
-
- ```
-
-
-
-
-
-
-The agent is initialized with an **endpoint** and a **port** so that it can receive messages, and other agents know where to send them.
-
-You need to define the agent's protocols to define what type of messages it will expect and produce whenever interacting with other agents. For an example of a complete code for a local agent with protocols, checkout this [guide ↗️](/guides/agents/intermediate/options-for-running-local-agents#the-agent).
-
-By implementing the `uagents-ai-engine` library, you will make your agent [AI Engine compatible ↗️](/guides/agents/intermediate/ai-engine-compatible-agent) and retrievable via DeltaV.
-
-When running the above local agent, you will see something like this in your terminal:
-
- ```
- INFO: [TestAgent]: Manifest published successfully: TestProtocol
- INFO: [TestAgent]: Registering on almanac contract...
- INFO: [TestAgent]: Registering on almanac contract...complete
- INFO: [TestAgent]: agent1qvwk0ntr38yyghccrg530hnnm88r5uske4hdcalsa7gqp7sjgx42k4mp62r
- INFO: [TestAgent]: Starting server on http://0.0.0.0:6145 (Press CTRL+C to quit)
- ```
-
-**Great! You have successfully registered your local agent on the ASI Network and the Agentverse.** You can validate this by heading to the [Agentverse Explorer ↗️](/concepts/agent-services/agent-explorer) tab and paste the address of the local agent you just registered. You should be able to see your local agent's details and protocols.
-
-### Run a local agent using a Mailbox
-
-**Mailboxes** allow for communication between your local agents and any other agents registered within the ASI Network and Agentverse without the need for you to be constantly present to operate them.
-
-Let's consider the following local agent example:
-
-
-
-
-
-
-
- ```py copy filename="mailbox-agent.py"
-
- from uagents import Agent, Context, Model, Protocol
-
- class Message(Model):
- message: str
-
- SEED_PHRASE = "put_your_seed_phrase_here"
-
- agent = Agent(
- name="MailboxTestAgent",
- seed=SEED_PHRASE,
- mailbox=True
- )
-
- print(f"Your agent's address is: {agent.address}")
-
- test_protocol = Protocol("TestProtocol")
-
- # Define your agent protocols and behaviour
- # Include the protocols within your agent
-
- if __name__ == "__main__":
- agent.run()
-
- ```
-
-
-
-
-
-
-You can create a Mailbox by retrieving your **local agent address** and head over to the **Agentverse: My Agents** tab. Click on **Local Agents** and click on **Connect Local Agent** button. Provide the address and name of the local agent you wish to retrieve and wait for confirmation. You will then be able to see a **Mailbox API Key**. Copy and paste it within your local agent code by filling up the `AGENT_MAILBOX_KEY` field inline and restart the agent.
-
-For an example of a complete code for a local agent with protocols registered on the Agentverse using the Mailbox feature, checkout this [example ↗️](/examples/examplestech/local-agent-langchain).
-
-When running the above local agent, you will see something like this on your terminal:
-
- ```
- Your agent's address is: agent1qfa53drat8rzau90u4494gx5mhj3v87tm4t5cuzkd7gkegxcm5vx5pku7kf
- INFO: [MailboxTestAgent]: Registering on almanac contract...
- INFO: [MailboxTestAgent]: Registering on almanac contract...complete
- INFO: [MailboxTestAgent]: Connecting to mailbox server at agentverse.ai
- INFO: [MailboxTestAgent]: Mailbox access token acquired
- ```
-
-**Great! You have successfully registered your local agent on the Agentverse and ASI Network using a Mailbox.**
-
-### Create Agents and Agent Functions using APIs
-
-If you wish to to create **Agents** and **Agent Functions** in Agentverse using APIs, head over to this [guide ↗️](/guides/apis/agent-function-creation-apis) which shows how set up a Python script that interacts with the Agentverse and helps you creating Agents and Agent Functions using APIs.
-
-## Next steps
-
-Now that you have a complete understanding on how to run agents on the Agentverse platform, you are ready to create your first [Agent Function ↗️](/guides/agents/intermediate/agent-functions), [Register it on the Agentverse ↗️](/guides/agentverse/agentverse-functions/registering-agent-services) and make it retrievable via [DeltaV ↗️](/concepts/ai-engine/deltav).
diff --git a/pages/examples/ai-engine-api/_meta.json b/pages/examples/ai-engine-api/_meta.json
deleted file mode 100644
index d27ca66eb..000000000
--- a/pages/examples/ai-engine-api/_meta.json
+++ /dev/null
@@ -1,7 +0,0 @@
-{
- "chat_api_example": {
- "title": "Chat API example [Advanced]",
- "tags": ["Advanced", "Python", "Dialogues", "Use cases"],
- "timestamp": true
- }
-}
diff --git a/pages/examples/ai-engine-api/chat_api_example.mdx b/pages/examples/ai-engine-api/chat_api_example.mdx
deleted file mode 100644
index f80739009..000000000
--- a/pages/examples/ai-engine-api/chat_api_example.mdx
+++ /dev/null
@@ -1,751 +0,0 @@
-# AI Engine Chat API guide
-## Introduction
-
-This guide offers details on utilizing the AI engine's Chat APIs to interact with [AI
-Engine ↗️](/concepts/ai-engine/ai-engine-intro) and create [DeltaV ↗️](https://deltav.agentverse.ai) like GUI. We will demonstrate a Python script that interacts with AI engine via the chat API, handling session IDs, sending messages, managing responses, and processing user requests and selections.
-
-## Prerequisites
-
- - Before you begin, ensure you have the following:
-
- - Python version greater than 3.9 and less than 3.11.
- - The requests library installed. You can install it using `pip install requests`.
- - [Agentverse ↗️](https://agentverse.ai/) Credentials.
-
-## Steps to get API Tokens
-
- - Go to Profile section in [Agentverse ↗️](https://agentverse.ai/).
- - Click on button `+ New API Key`.
- - Give name to your API key.
- - Click on `write` for `Access to all resources in Agentverse` and click on `Generate API Key`
-
-
-
-We use this value as `refreshed_token` below.
-
-## Script Break down
-
-- Importing Required libraries:
-
- ```python
- # Importing Required libraries
- import re
- import requests
- import time
- import json
- ```
-
- These libraries are used to handle user regular expressions, HTTP requests, time delays and JSON responses.
-
-- OAuth and API Configuration.
-
- ```python
- # OAuth and API Configuration
- FAUNA_URL = 'https://accounts.fetch.ai'
- TOKEN_URL = f'{FAUNA_URL}/v1/tokens'
- CLIENT_ID = 'agentverse' # Ensure this is your actual Client ID
- SCOPE = 'av'
-
- # Your encoded refresh token here
- refreshed_token = ""
- # Decode the refresh token
- token = f'Bearer ' # Placeholder for initial token
- ```
-
- This script includes various functions for handling different API interactions. Below is a summary of the main functions and their respective purposes.
-
-1. `refresh_tokens` function:
-
- ```python
- def refresh_tokens(refresh_token):
- """Attempt to refresh the access and refresh tokens."""
- response = requests.post(
- TOKEN_URL,
- json={
- 'grant_type': 'refresh_token',
- 'refresh_token': refresh_token,
- 'client_id': CLIENT_ID,
- 'scope': SCOPE,
- }
- )
- if response.status_code == 200:
- print('New token generated.')
- response_data = response.json()
- return response_data['access_token'], response_data.get('refresh_token', refresh_token)
- else:
- print("Error refreshing tokens:", response.text)
- return None, None
- ```
-
- This function helps generate new pair of `access_token` and `refresh_token` if the current access_token is expired.
-
-2. `normalize_question` function:
-
- ``` python
- # Define function to normalize questions asked by AI-engine
- def normalize_question(question):
- question_lower = question.lower()
- question_normalized = re.sub(r'[^\w\s]', '', question_lower)
- return question_normalized
- ```
-
- This function converts questions from a JSON response, identified by the key 'text', into lowercase and removes any punctuation.
- It helps standardize user input for consistent processing.
-
-3. `is_uuid` function:
-
- ``` python
- # Define function to check if option is uuid (Subtask Key)
- def is_uuid(key):
- # Function to check if a string is a valid UUID
- pattern = re.compile(r"^[0-9a-f]{8}-[0-9a-f]{4}-[1-4][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", re.IGNORECASE)
- return pattern.match(key)
- ```
-
- This function checks whether the given key is in UUID (Universal Unique Identifier) format.The function uses a regular expression pattern to match the
- standard UUID format, which consists of 32 hexadecimal characters split into five groups separated by hyphens (8-4-4-4-12).
-
-4. `update_token` function:
-
- ```python
- # Function to update and refresh the access token
- def update_token():
- global token, refreshed_token
- new_tokens = refresh_tokens(refreshed_token)
- fauna_token = new_tokens[0]
- refreshed_token = new_tokens[1]
- token = f'Bearer {fauna_token}'
- ```
-
- This function refreshes the `fauna token` and `refresh fauna token` in case current fauna token expires.
-
-5. `post_request` function:
-
- ```python
- # Function to handle POST requests with automatic token refresh
- def post_request(url, json_data, headers):
- global token
- response = requests.post(url, json=json_data, headers=headers)
- if response.status_code != 200:
- update_token()
- headers["Authorization"] = token
- response = requests.post(url, json=json_data, headers=headers)
- return response`
- ```
-
- This function makes post request to Agentverse and if response is not 200 it gets new `acess_token` and `refresh_token`.
-
-6. `get_request` function:
-
- ```python
- # Function to handle GET requests with automatic token refresh
- def get_request(url, headers):
- global token
- response = requests.get(url, headers=headers)
- if response.status_code != 200:
- update_token()
- headers["Authorization"] = token
- response = requests.get(url, headers=headers)
- return response
- ```
- This function makes get request to Agentverse and if response is not 200 it gets new `acess_token` and `refresh_token`.
-
-7. `send_user_choice_as_uuid` function:
-
- ```python
- # Function to send UUID choice message to AI-Engine
- def send_user_choice_as_uuid(session_id, user_choice, token):
- data = {
- "payload": {
- "type": "user_json",
- "user_json": {
- "type": "options",
- "selection": [user_choice]
- },
- "session_id": session_id
- }
- }
- return post_request(f"https://agentverse.ai/v1beta1/engine/chat/sessions/{session_id}/submit", data, {"Authorization": token})
- ```
-
- This function is designed to send user's choice back to AI-engine through Chat API, specially in case of user getting options from multiple
- subtask options as UUID. The function takes three parameters:
-
- - `session_id` - chat session Id on DeltaV.
- - `user_choice` - the choice of subtask user wants AI-Engine to use.
- - `token` - AI-Engine fauna token to connect DeltaV or AI-Engine.
-
-8. `send_user_message` function:
-
- ``` python
- # Function to send normal message to AI-Engine
- def send_user_message(session_id, user_message, token):
- data = {
- "payload": {
- "type": "user_message",
- "user_message": user_message
- },
- "session_id": session_id
- }
- return post_request(f"https://agentverse.ai/v1beta1/engine/chat/sessions/{session_id}/submit", data, {"Authorization": token})
- ```
-
- This function is designed to send a message from the user to the chat session. This is used to submit user input as part of the chat flow.
- The session_id and token parameters are same as 'Send_user_choice_as_uuid' function, 'user_message' is the message which user wants to send to
- the ongoing chat session.
-
-9. `stop_session` functions:
-
- ``` python
- # Define function to stop user session
- def stop_session(session_id, token):
- data = {"payload": {"type": "stop"}}
- response = post_request(f"https://agentverse.ai/v1beta1/engine/chat/sessions/{session_id}/submit", data, {"Authorization": token})
- print("Session stopped:", response.json())
- ```
-
- This function is designed to stop the ongoing deltaV chat session.
-
-## Main Script Flow
-
-The main script flow includes:
-
- 1. Importing required libraries.
- 2. Setting up OAuth flow and API authentication.
- 2. Setting up a chat session on DeltaV using AI-Engine Chat API.
- 3. Taking input from the user for service they want to assemble or objective to achieve.
- 4. Handling the chat flow which includes sending messages and processing requests.
- 5. Managing User selection from provided options.
- 6. Handling special requests where agents ask the same questions back to back. (The same question is asked in agent_json and agent_info response type when user input is required.)
- 7. Handling error codes provided by agent.
- 8. Stopping chat session with the user.
-
-### Chunk-by-chunk explanation:
-
-- Setting up a Chat Session with AI Engine Chat API:
-
- ```python
- # User and model details
- data = {
- "email": "", # replace with agentverse username
- "requestedModel": "talkative-01" # Model type for chat interaction
- }
-
- # Connecting to deltaV and getting session ID
- response_data = post_request("https://agentverse.ai/v1beta1/engine/chat/sessions", data, {"Authorization": token}).json()
- session_id = response_data.get('session_id')
- print("Session Id:", session_id)
- ```
-
- The above section of code creates payload(data) for request to start a session. Please update the following details accordingly:
- `email`: Update this with your agentverse email-id.
- `requestedModel`: This is the chat model you want to make request to
-
- On the basis of details provided and POST request sent to chat API. AI Engine responds with a session-Id where we can communicate further with deltaV.
- Session-id is extracted from the response which is vital for interacting with DeltaV.
-
- - Taking user input from the user for service they would like to assemble/Objective they want to accomplish.
-
- ``` python
- # Taking user query as input
- objective = input('What Service would you like to assemble?\n')
-
- # Defining initial payload for querying DeltaV
- data_query = {
- "payload": {
- "type": "start",
- "objective": objective,
- "context": f"User full Name: Test User\nUser email: {data['email']}\nUser location: latitude=51.5072, longitude=0.1276\n",
- "session_id": session_id
- }
- }
-
- # Sending query to user
- response = post_request(f"https://agentverse.ai/v1beta1/engine/chat/sessions/{session_id}/submit", data2,{"Authorization": token} )
- # waiting to get next response from AI engine
- time.sleep(10)
- response = get_request(f"https://agentverse.ai/v1beta1/engine/chat/sessions/{session_id}/responses",{"Authorization": token}).json()
- ```
-
- This section of code is responsible for sending a start message after chat session is initialized. Below is the step-by-step explanation:
-
- 1. Taking user objective/query as input.
- 2. Creating a payload to make a start request to AI Engine Chat API. which includes objective, username, location and session-id.
- 3. POST start request with query to AI Engine.
- 4. Getting latest responses from AI Engine chat API using GET Request.
-
-- Selecting required function from options and sending response back to AI Engine:
-
- ```python
- # Getting agent response for the services options
- agent_response = response['agent_response'][0]
- agent_response_dict = json.loads(agent_response)
- # Getting Services options for user's objective
- agent_json = agent_response_dict['agent_json']
-
- # Taking input from user for which service to use.
- for option in agent_json['options']:
- print(f"{option['key']}: {option['value']}")
- user_choice = input("Please select an option by entering the corresponding key: \n")
-
- # Payload for selected service
- data_service = {
- "payload": {
- "type": "user_json",
- "user_json": {
- "type": "task_list",
- "selection": [user_choice]
- }
- }
- }
-
- # Submitting selected service to DeltaV
- response = post_request(f"https://agentverse.ai/v1beta1/engine/chat/sessions/{session_id}/submit", data3,{"Authorization": token})
- ```
-
- The above section of code gets response for available services options for the user query or objective. Below is step-by-step guide to achieve this:
-
- 1. Getting agent response for the service options
- 2. Displaying options to the user and taking user choice input.
- 3. Creating payload for selected Agent Function.
- 4. submitting selected service to DeltaV.
-
-- Handling the chat flow which includes sending messages and processing responses:
-
- ```python
- # Setting response count to track not responsive agent.
- no_response_count = 0
- ## Variables to track the last question and response
- last_question = ""
- last_response = ""
-
- while True:
- time.sleep(5) # Wait before fetching responses to avoid overwhelming the server
- response = get_request(f"https://agentverse.ai/v1beta1/engine/chat/sessions/{session_id}/responses", {"Authorization": token})
-
- if response.status_code != 200:
- raise Exception(f"Error in fetching responses: Status code {response.status_code}")
-
- response = response.json()
-
- # Handling unresponsive deltaV
- if not response['agent_response']:
- no_response_count += 1
- if no_response_count < 10:
- continue # Wait for a bit longer if no response yet
- else:
- print("No response from the agent.")
- stop_session(session_id, token)
- break # Exit loop if no response after several attempts
-
- no_response_count = 0 # Reset counter on receiving a response
- ```
-
- This section of the script implements a loop to continuously monitor responses from the DeltaV agent within a chat session:
-
- 1. Initialize a counter for response to track empty DeltaV agent responses.
- 2. Tracing last interaction questions, and responses to avoid asking same questions to the user.
- 3. The script is in continuous infinite loop repeatedly every 5 seconds unless we get 10 empty responses.
-
- ```python
- # Reading agent response
- for agent_resp in response['agent_response']:
- agent_resp_dict = json.loads(agent_resp) #getting response dictionary from deltaV
- current_message_text = "" # Setting current message to empty string
-
- if agent_resp_dict.get('type') == 'agent_json': #handling agent_json type response
- agent_json = agent_resp_dict['agent_json']
- current_message_text = normalize_question(agent_json.get('text', '')) # Setting current message from deltaV
-
- # Handle options provided in agent_json
- if 'options' in agent_json and agent_json['options']:
- option_keys = [str(option['key']) for option in agent_json['options']] # setting options keys in list to check if its UUID
-
- # Automatically select the first option if it's a UUID
- if is_uuid(option_keys[0]):
- print(f"Automatically selecting option: {option_keys[0]}")
- send_user_choice_as_uuid(session_id, option_keys[0], token)
- last_response = option_keys[0] # Update last response
- continue # Skip the rest of the loop to wait for the next agent response
- else:
- # If the first option is not a UUID, prompt for user input
- print(agent_json.get('text', '')) # printing deltaV message on terminal
- for option in agent_json['options']:
- print(f"{option['key']}: {option['value']}") # Printing options on terminal
- user_choice = input("Your Response: ") # Taking user selection from options
- send_user_message(session_id, user_choice, token) # Sending response to deltaV
- last_response = user_choice # Update last response
- else:
- # No options provided
- print(agent_json.get('text', 'Please confirm the details or provide the requested information:')) # Printing user message
- if agent_json.get('context_json') and 'args' in agent_json['context_json']: #Printing arguments to confirm if present
- args = agent_json['context_json']['args']
- for key, value in args.items():
- print(f"{key}: {value}")
- user_confirmation = input("Your confirmation/details: ") # Confirming arguments by user
- send_user_message(session_id, user_confirmation, token)
- last_response = user_confirmation # Update last response
- ```
-
- This section of scripts processes responses from the agent in DeltaV system:
-
- 1. The loop continuously iterates through each response and converts json string into python dictionary.
- 2. The script initializes `current_message_text` as an empty string to prepare for new messages.
- 3. This script handles different types of responses. If the response type is `agent_json`:
-
- 3.1. Extracts the message and normalizes it using the normalize_question function, which converts the text to lowercase and removes punctuation.
- 3.2. Checks if there are options associated with the message, if there are:
-
- 3.2.1. It extracts the option keys and checks if the first option is a UUID, indicating a subtask trigger.
- 3.2.2. If it is a UUID, the script automatically selects first option without user intervention, updating last_response and skipping the remaining loop to await further responses.
- 3.2.3. If the options are not UUIDs, the script displays them to the user and prompts for a choice, which is then sent back to DeltaV using `send_user_message`.
-
- - If the `agent_json` does not contain options (indicating a request for confirmation or information):
-
- 1. The script prints the message and, if present, details (arguments) for user confirmation.
- 2. It then collects user input and sends it back to DeltaV, updating `last_response` with the user's input for continuity.
-
- ```python
- elif agent_resp_dict.get('type') == 'agent_message': #handling agent_message type response
- agent_message = agent_resp_dict.get('agent_message', '')
- print(agent_message)
- # If agent_message repeats the last question, reuse last response
- if normalize_question(agent_message.split('?')[0]) == last_question:
- print(f"Reusing your last response: {last_response}")
- send_user_message(session_id, last_response, token)
- else: # if question not repeated taking input from user
- user_response = input("Your answer: ")
- send_user_message(session_id, user_response, token)
- last_response = user_response # Update last response
- ```
-
- - Handling `agent_message` type response:
-
- 1. if the questions asked is same as the previous response in agent_json, it automatically sends previous response to deltav using `send_user_message` message.
- 2. else the input or is taken from user for the given question and sent to deltaV agent using `send_user_message` and `last_response` is stored.
-
- ```python
- # Stopping session in case of error.
- elif agent_resp_dict.get('type') == 'agent_error':
- agent_message = agent_resp_dict.get('agent_error')
- print(agent_message)
- stop_session(session_id, token)
- ```
-
- - This section of script handles `error` type response and stops the session in case of error with error message.
-
- ```python
- elif 'agent_info' in agent_resp_dict or agent_resp_dict.get('type') == 'stop': #handling agent_info and stop messages
- # Print agent_info or handle stop type
- info_message = agent_resp_dict.get('agent_info', '') if agent_resp_dict.get('type') == 'agent_info' else "Session stopping."
- print(f'Agent Info : {info_message}') # Print agent info
- if 'I have completed your task! Please reset your chat session before submitting your new request.' in info_message:
- stop_session(session_id, token)
- break # Exit loop if session is stopped
- if agent_resp_dict.get('type') == 'stop':
- stop_session(session_id, token)
- break # Exit loop if session is stopped
- ```
-
- - Handling `agent_info` and `stop` Type Responses:
-
- 1. If the response contains 'agent_info' or the type is 'stop', the script processes these specific messages.
- 2. For 'agent_info' type messages, it extracts and prints the information content provided by the agent. This could be feedback, status updates, or other informative messages relevant to the user's query or the chat session.
- 3. If the message type is 'stop', the script prints "Session stopping." to indicate that the DeltaV session is ending.
-
- - Session Complete and Reset:
-
- 1. If the agent's information message indicates that the user's task has been completed (identified by a specific message, "I have completed your task! Please reset your chat session before submitting your new request."), the script triggers the `stop_session` function to properly close the session on the server side.
- 2. Similarly, if the response type is 'stop', it also calls `stop_session` to end the session.
- 3. In both cases, after stopping the session, the script breaks out of the loop, effectively ending the script's execution.
-
- ```python
- else:
- print("Received an unhandled response type:", agent_resp_dict.get('type')) # Handling any other message type
-
- # Update last_question with current message text up to a question mark
- last_question = current_message_text.split('?')[0] if '?' in current_message_text else current_message_text
- ```
-
- This section of script handles any other agent response and also updates the last question. It removes the options and punctuation mark from the question to check it with the current question in `agent_json`.
-
-## Whole Script
-
-```py copy filename="chatAPI.py"
-# Importing required libraries
-import re
-import requests
-import time
-import json
-
-# OAuth and API Configuration
-FAUNA_URL = 'https://accounts.fetch.ai'
-TOKEN_URL = f'{FAUNA_URL}/v1/tokens'
-CLIENT_ID = 'agentverse' # Ensure this is your actual Client ID
-SCOPE = 'av'
-
-# Your encoded refresh token here
-refreshed_token = ""
-# Decode the refresh token
-token = f'Bearer ' # Placeholder for initial token
-
-def refresh_tokens(refresh_token):
- """Attempt to refresh the access and refresh tokens."""
- response = requests.post(
- TOKEN_URL,
- json={
- 'grant_type': 'refresh_token',
- 'refresh_token': refresh_token,
- 'client_id': CLIENT_ID,
- 'scope': SCOPE,
- }
- )
- if response.status_code == 200:
- print('New token generated.')
- response_data = response.json()
- return response_data['access_token'], response_data.get('refresh_token', refresh_token)
- else:
- print("Error refreshing tokens:", response.text)
- return None, None
-
-# Define function to normalize questions asked by AI-engine
-def normalize_question(question):
- question_lower = question.lower()
- question_normalized = re.sub(r'[^\w\s]', '', question_lower)
- return question_normalized
-
-# Define function to check if a string is a valid UUID
-def is_uuid(key):
- # Ensure the key is a string
- key_str = str(key)
- pattern = re.compile(r"^[0-9a-f]{8}-[0-9a-f]{4}-[1-4][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", re.IGNORECASE)
- return pattern.match(key_str)
-
-# Function to update and refresh the access token
-def update_token():
- global token, refreshed_token
- new_tokens = refresh_tokens(refreshed_token)
- fauna_token = new_tokens[0]
- refreshed_token = new_tokens[1]
- token = f'Bearer {fauna_token}'
-
-# Function to handle POST requests with automatic token refresh
-def post_request(url, json_data, headers):
- global token
- response = requests.post(url, json=json_data, headers=headers)
- if response.status_code != 200:
- update_token()
- headers["Authorization"] = token
- response = requests.post(url, json=json_data, headers=headers)
- return response
-
-# Function to handle GET requests with automatic token refresh
-def get_request(url, headers):
- global token
- response = requests.get(url, headers=headers)
- if response.status_code != 200:
- update_token()
- headers["Authorization"] = token
- response = requests.get(url, headers=headers)
- return response
-
-# Functions to interact with the AI-Engine
-def send_user_choice_as_uuid(session_id, user_choice, token):
- data = {
- "payload": {
- "type": "user_json",
- "user_json": {
- "type": "options",
- "selection": [user_choice]
- },
- "session_id": session_id
- }
- }
- return post_request(f"https://agentverse.ai/v1beta1/engine/chat/sessions/{session_id}/submit", data, {"Authorization": token})
-
-def send_user_message(session_id, user_message, token):
- data = {
- "payload": {
- "type": "user_message",
- "user_message": user_message
- },
- "session_id": session_id
- }
- return post_request(f"https://agentverse.ai/v1beta1/engine/chat/sessions/{session_id}/submit", data, {"Authorization": token})
-
-def stop_session(session_id, token):
- data = {"payload": {"type": "stop"}}
- response = post_request(f"https://agentverse.ai/v1beta1/engine/chat/sessions/{session_id}/submit", data, {"Authorization": token})
- print("Session stopped:", response.json())
-
-# User and model details
-data = {
- "email": "
- To test agents using **Dialogues or ChitChat** on DeltaV, users must select the **Next generation** personality type in [DeltaV ↗️](https://deltav.agentverse.ai/) when providing your query through the dedicated bar. The **Next Generation AI Engine** personality stands as a significant AI Engine personality type offering _enhanced scalability_, _reliability_, and _flexibility_. The major key features include advanced context understanding, improved function recommendations, and the ability to handle diverse dialogue formats.
-
-
-Please check out the example code in our [examples repo ↗️](https://github.com/fetchai/uAgent-Examples/tree/main/5-documentation/examples/advanced/deltaV-dialogues) to run this locally.
-
-## Guide
-
-- [How to use Dialogues ↗️](/guides/agents/dialogues)
-
-## Supporting documentation
-
-- [Creating an hosted agent on agentverse ↗️](/guides/agentverse/creating-agentverse-agents/creating-a-hosted-agent)
-- [Registering agentverse functions ↗️](/guides/agentverse/agentverse-functions/registering-agent-services)
-- [Field description for deltaV ↗️](/guides/agentverse/agentverse-functions/field-descriptions-for-deltav)
-
-## Step 1: Create agent and Import Required libraries
-
-Open [Agentverse ↗️](https://agentverse.ai/), create a new agent and include the below script.
-We need to import predefined AI engine dialogue and Dialogue Messages:
-
-
-
-
-
-
-
- ```py copy filename="deltav-dialogues.py"
-
- # Import required libraries
- import os
-
- import requests
- from ai_engine.chitchat import ChitChatDialogue
- from ai_engine.messages import DialogueMessage
- from uagents import Context, Model
-
- API_KEY = os.getenv("ALPHA_VANTAGE_API_KEY")
- ```
-
-
-
-
-
-
-## Step 2: Define dialogues message
-
-Each dialogue transition needs a separate message:
-
-
-
-
-
-
-
- ```py copy filename="deltav-dialogues.py"
-
-
- class InitiateChitChatDialogue(Model):
- """I initiate ChitChat dialogue request"""
-
- pass
-
-
- class AcceptChitChatDialogue(Model):
- """I accept ChitChat dialogue request"""
-
- pass
-
-
- class ChitChatDialogueMessage(DialogueMessage):
- """ChitChat dialogue message"""
-
- pass
-
-
- class ConcludeChitChatDialogue(Model):
- """I conclude ChitChat dialogue request"""
-
- pass
-
-
- class RejectChitChatDialogue(Model):
- """I reject ChitChat dialogue request"""
-
- pass
-
- ```
-
-
-
-
-
-
-## Step 3: Define functions to get symbol and stock price
-
-Set up the functions making API calls to get ticker symbol and stock price:
-
-
-
-
-
-
-
- ```py copy filename="deltav-dialogues.py"
-
- async def get_symbol(company_name):
- url = f"https://www.alphavantage.co/query?function=SYMBOL_SEARCH&keywords={company_name}&apikey={API_KEY}"
-
- response = requests.get(url)
- data = response.json()
-
- if "bestMatches" in data and data["bestMatches"]:
- first_match = data["bestMatches"][0]
- symbol = first_match["1. symbol"]
- return symbol
- else:
- return f"No symbol found for {company_name}."
-
-
- async def get_stock_price(symbol):
- url = f"https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol={symbol}&interval=1min&apikey={API_KEY}"
-
- response = requests.get(url)
- data = response.json()
- print(data)
-
- if "Time Series (1min)" in data:
- latest_time = sorted(data["Time Series (1min)"].keys())[0]
- latest_data = data["Time Series (1min)"][latest_time]
- current_price = latest_data["1. open"]
- return current_price
- else:
- return "Error: Unable to fetch stock price."
-
- ```
-
-
-
-
-
-
-## Step 4: instantiate the dialogues
-
-
-
-
-
-
-
- ```py copy filename="deltav-dialogues.py"
-
- chitchat_dialogue = ChitChatDialogue(
- version="", # example 0.11.1
- storage=agent.storage,
- )
-
-
- ```
-
-
-
-
-
-
-## Step 5: Define different event handlers for the dialogues
-
-
-
-
-
-
-
- ```py copy filename="deltav-dialogues.py"
-
-
- @chitchat_dialogue.on_initiate_session(InitiateChitChatDialogue)
- async def start_chitchat(
- ctx: Context,
- sender: str,
- msg: InitiateChitChatDialogue,
- ):
- ctx.logger.info(f"Received init message from {sender} Session: {ctx.session}")
- # do something when the dialogue is initiated
- await ctx.send(sender, AcceptChitChatDialogue())
-
-
- @chitchat_dialogue.on_start_dialogue(AcceptChitChatDialogue)
- async def accepted_chitchat(
- ctx: Context,
- sender: str,
- _msg: AcceptChitChatDialogue,
- ):
- ctx.logger.info(
- f"session with {sender} was accepted. This shouldn't be called as this agent is not the initiator."
- )
-
-
- @chitchat_dialogue.on_reject_session(RejectChitChatDialogue)
- async def reject_chitchat(
- ctx: Context,
- sender: str,
- _msg: RejectChitChatDialogue,
- ):
- # do something when the dialogue is rejected and nothing has been sent yet
- ctx.logger.info(f"Received conclude message from: {sender}")
-
-
- @chitchat_dialogue.on_continue_dialogue(ChitChatDialogueMessage)
- async def continue_chitchat(
- ctx: Context,
- sender: str,
- msg: ChitChatDialogueMessage,
- ):
- # do something when the dialogue continues
- ctx.logger.info(f"Received message: {msg.user_message} from: {sender}")
- symbol = await get_symbol(msg.user_message)
- stock_price = await get_stock_price(symbol)
- final_string = f"The price for your {msg.user_message} is $ {stock_price}"
- try:
- await ctx.send(
- sender,
- ChitChatDialogueMessage(type="agent_message", agent_message=final_string),
- )
- except EOFError:
- await ctx.send(sender, ConcludeChitChatDialogue())
-
-
- @chitchat_dialogue.on_end_session(ConcludeChitChatDialogue)
- async def conclude_chitchat(
- ctx: Context,
- sender: str,
- _msg: ConcludeChitChatDialogue,
- ):
- # do something when the dialogue is concluded after messages have been exchanged
- ctx.logger.info(f"Received conclude message from: {sender}; accessing history:")
- ctx.logger.info(chitchat_dialogue.get_conversation(ctx.session))
-
-
- agent.include(chitchat_dialogue, publish_manifest=True)
-
- ```
-
-
-
-
-
-
-## Step 6: Save the API key and Run the script in agentverse
-
-To get the API key visit [Alphavantage ↗️](https://www.alphavantage.co/) get the free API key and save new secret as `API_KEY`.
-
-## Step 7: Create a DeltaV function and fill in the required details
-
-The function details are as below:
-
- - **Name**: Stocks Price Dialogue.
- - **AI description**: This Function helps user to check stocks or share price for more than one company.
-
-Rest all details will be auto populated. Use DeltaV to perform Agentverse Agent chit chat.
-
-## Expected output
-
-
-
-
-
-
-
-
diff --git a/pages/examples/dialogues/open-dialogue-chitchat.mdx b/pages/examples/dialogues/open-dialogue-chitchat.mdx
deleted file mode 100644
index aa3624775..000000000
--- a/pages/examples/dialogues/open-dialogue-chitchat.mdx
+++ /dev/null
@@ -1,730 +0,0 @@
-import { Callout } from 'nextra/components'
-import { CodeGroup, DocsCode, CodeSegment, GithubCodeSegment } from "../../../components/code";
-
-# Open Dialogue Chit-Chat
-
-## Overview
-
-This example demonstrates how to set up and execute a simple agent-based dialogue using the ChitChat Dialogue system. Agent 2 will initiate a conversation with Agent 1, which will respond and continue the interaction. This interaction showcases basic dialogue initiation, message exchange, and dialogue conclusion. Each step and state transition within the ChitChat Dialogue is visible and interactive
-
-Please check out the example code in our [examples repo ↗️](https://github.com/fetchai/uAgent-Examples/tree/main/5-documentation/examples/advanced/open-dialogue-chitchat) to run this locally.
-
-### Guide
-
-- [How to use Dialogues ↗️](/guides/agents/dialogues)
-
-### Supporting documentation
-
-- [Creating an agent ↗️](/guides/agents/create-a-uagent)
-- [Communicating with other agents ↗️](/guides/agents/communicating-with-other-agents)
-- [Register in Almanac ↗️](/guides/agents/register-in-almanac)
-- [Almanac Contract ↗️](/references/contracts/uagents-almanac/almanac-overview)
-
-## Step 1: Define the Dialogue Structure
-
-This script sets up the `ChitChatDialogue` class, This system includes nodes representing different states of the dialogue and edges defining possible transitions between these states.
-
-- Open a terminal and create a directory using `mkdir Dialogues` and navigate into it with `cd Dialogues`.
-- Create a python file `chitchat.py` in `Dialogues` directory.
-
-
-
- ```py copy filename="mac"
- touch chitchat.py
- ```
-
-
- ```py copy filename="windows"
- echo. > chitchat.py
- ```
-
-
-
- ```py copy filename="ubuntu"
- touch chitchat.py
- ```
-
-
-
-
-- Import required libraries.
-
-
-
-
-
-
-
- ```py copy filename="chitchat.py"
-
- # Import required libraries
-
- from typing import Type
- from uagents import Model
- from uagents.experimental.dialogues import Dialogue, Edge, Node
-
-
- ```
-
-
-
-
-
-
-- Define `nodes` (state) of dialogues like default, initiate, chitchat and conclude state.
-
-
-
-
-
-
-
- ```py copy filename="chitchat.py"
-
- # Define node of dialogue
- default_state = Node(
- name="Default State",
- description=(
- "This is the default state of the dialogue. Every session starts in "
- "this state and is automatically updated once the dialogue starts."
- )
- )
- init_state = Node(
- name="Initiated",
- description=(
- "This is the initial state of the dialogue that is only available at "
- "the receiving agent."
- ),
- )
- chatting_state = Node(
- name="Chit Chatting",
- description="This is the state in which messages are exchanged.",
- )
- end_state = Node(
- name="Concluded",
- description="This is the state after the dialogue has been concluded.",
- )
-
-
- ```
-
-
-
-
-
-
-- Define `edges` (transition) of dialogues like initiate session, reject session, start dialogue, continue dialogue and end session.
-
-
-
-
-
-
-
- ```py copy filename="chitchat.py"
-
- # Edge definition for the dialogue transitions
- init_session = Edge(
- name="initiate_session",
- description="Every dialogue starts with this transition.",
- parent=None,
- child=init_state,
- )
- reject_session = Edge(
- name="reject_session",
- description=("This is the transition for when the dialogue is rejected"),
- parent=init_state,
- child=end_state,
- )
- start_dialogue = Edge(
- name="start_dialogue",
- description="This is the transition from initiated to chit chatting.",
- parent=init_state,
- child=chatting_state,
- )
- cont_dialogue = Edge(
- name="continue_dialogue",
- description=(
- "This is the transition from one dialogue message to the next, "
- "i.e. for when the dialogue continues."
- ),
- parent=chatting_state,
- child=chatting_state,
- )
- end_session = Edge(
- name="end_session",
- description="This is the transition for when the session is ended.",
- parent=chatting_state,
- child=end_state,
- )
-
-
- ```
-
-
-
-
-
-
-- Define `ChitChatDialogue` class and include nodes and edges into it. These acts as rule for chit chat dialogues.
-
-
-
-
-
-
-
- ```py copy filename="chitchat.py"
-
-
- class ChitChatDialogue(Dialogue):
- """
- This is the specific definition of the rules for the chit-chat dialogue
- The rules will be predefined and the actual messages will be passed into it
- """
-
- def __init__(
- self,
- version: str | None = None,
- agent_address: str | None = None,
- ) -> None:
- super().__init__(
- name="ChitChatDialogue",
- version=version,
- nodes=[
- default_state,
- init_state,
- chatting_state,
- end_state,
- ],
- edges=[
- init_session,
- reject_session,
- start_dialogue,
- cont_dialogue,
- end_session,
- ],
- )
-
- def on_initiate_session(self, model: Type[Model]):
- """
- This handler is triggered when the initial message of the
- dialogue is received. From here you can either accept or reject.
- Logic that is needed to complete any kind of handshake or considers
- global agent state should go here.
- """
- return super()._on_state_transition(init_session.name, model)
-
- def on_reject_session(self, model: Type[Model]):
- """
- This handler is triggered when a reject message is returned on
- the initial message.
- Implement this if you need to clean up session data.
- """
- return super()._on_state_transition(reject_session.name, model)
-
- def on_start_dialogue(self, model: Type[Model]):
- """
- This handler is triggered when an accept message is returned on
- the initial message.
- Include logic to complete any handshake on the sender side and
- prepare the actual message exchange.
- """
- return super()._on_state_transition(start_dialogue.name, model)
-
- def on_continue_dialogue(self, model: Type[Model]):
- """
- This handler is triggered for every incoming "chitchat" message
- once the session has been accepted.
- Any additional stateful information within a dialogue needs to be
- persisted explicitly to access it at a later point in the dialogue.
- """
- return super()._on_state_transition(cont_dialogue.name, model)
-
- def on_end_session(self, model: Type[Model]):
- """
- This handler is triggered once the other party has ended the dialogue.
- Any final conclusion or cleanup goes here.
- """
- return super()._on_state_transition(end_session.name, model)
-
- ```
-
-
-
-
-
-
-The contents of this script are to be shared between the agents that want to use this dialogue. This defines the structure of the specific dialogue and the messages that are expected to be exchanged.
-
-## Step 2: Setting up Agents
-
-- Setup `agent1` which receives initiate session from `agent2` and accepts the state.
-- `agent2` sends continues chit chat dialogue message to agent 1 and continues the chat.
-- if any of the agent sends `exit` message the dialogue is concluded.
-- Run `cd ..` to go out of `Dialogues` directory and create `agent1.py` Python script
-
-
-
- ```py copy filename="mac"
- touch agent1.py
- ```
-
-
- ```py copy filename="windows"
- echo. > agent1.py
- ```
-
-
-
- ```py copy filename="ubuntu"
- touch agent1.py
- ```
-
-
-
-
-
-
-
-
-
-
- ```py copy filename="agent1.py"
-
- # Import required libraries
- import json
-
- from uagents import Agent, Context, Model
- from uagents.setup import fund_agent_if_low
- from dialogues.chitchat import ChitChatDialogue
-
- CHAT_AGENT_ADDRESS = ""
-
- agent = Agent(
- name="chit_agent",
- seed="",
- port=8001,
- endpoint="http://127.0.0.1:8001/submit",
- )
-
- fund_agent_if_low(agent.wallet.address())
-
- # Define dialogue messages; each transition needs a separate message
- class InitiateChitChatDialogue(Model):
- pass
-
- class AcceptChitChatDialogue(Model):
- pass
-
- class ChitChatDialogueMessage(Model):
- text: str
-
- class ConcludeChitChatDialogue(Model):
- pass
-
- class RejectChitChatDialogue(Model):
- pass
-
- # Instantiate the dialogues
- chitchat_dialogue = ChitChatDialogue(
- version="0.1",
- agent_address=agent.address,
- )
-
- # Get an overview of the dialogue structure
- print("Dialogue overview:")
- print(json.dumps(chitchat_dialogue.get_overview(), indent=4))
- print("---")
-
- @chitchat_dialogue.on_initiate_session(InitiateChitChatDialogue)
- async def start_chitchat(
- ctx: Context,
- sender: str,
- _msg: InitiateChitChatDialogue,
- ):
- ctx.logger.info(f"Received init message from {sender}")
- # Do something when the dialogue is initiated
- await ctx.send(sender, AcceptChitChatDialogue())
-
- @chitchat_dialogue.on_start_dialogue(AcceptChitChatDialogue)
- async def accept_chitchat(
- ctx: Context,
- sender: str,
- _msg: AcceptChitChatDialogue,
- ):
- ctx.logger.info(
- f"session with {sender} was accepted. I'll say 'Hello!' to start the ChitChat"
- )
- # Do something after the dialogue is started; e.g. send a message
- await ctx.send(sender, ChitChatDialogueMessage(text="Hello!"))
-
- @chitchat_dialogue.on_reject_session(RejectChitChatDialogue)
- async def reject_chitchat(
- ctx: Context,
- sender: str,
- _msg: RejectChitChatDialogue,
- ):
- # Do something when the dialogue is rejected and nothing has been sent yet
- ctx.logger.info(f"Received reject message from: {sender}")
-
- @chitchat_dialogue.on_continue_dialogue(ChitChatDialogueMessage)
- async def continue_chitchat(
- ctx: Context,
- sender: str,
- msg: ChitChatDialogueMessage,
- ):
- # Do something when the dialogue continues
- ctx.logger.info(f"Received message: {msg.text}")
- try:
- my_msg = input("Please enter your message:\n> ")
- if my_msg != "exit":
- await ctx.send(sender, ChitChatDialogueMessage(text=my_msg))
- else:
- await ctx.send(sender, ConcludeChitChatDialogue())
- ctx.logger.info(
- f"Received conclude message from: {sender}; accessing history:"
- )
- ctx.logger.info(chitchat_dialogue.get_conversation(ctx.session))
- except EOFError:
- await ctx.send(sender, ConcludeChitChatDialogue())
-
- @chitchat_dialogue.on_end_session(ConcludeChitChatDialogue)
- async def conclude_chitchat(
- ctx: Context,
- sender: str,
- _msg: ConcludeChitChatDialogue,
- ):
- # Do something when the dialogue is concluded after messages have been exchanged
- ctx.logger.info(f"Received conclude message from: {sender}; accessing history:")
- ctx.logger.info(chitchat_dialogue.get_conversation(ctx.session))
-
- agent.include(chitchat_dialogue)
-
- if __name__ == "__main__":
- print(f"Agent address: {agent.address}")
- agent.run()
-
- ```
-
-
-
-
-
-
-- Create Python `agent2.py` script:
-
-
-
- ```py copy filename="mac"
- touch agent2.py
- ```
-
-
- ```py copy filename="windows"
- echo. > agent2.py
- ```
-
-
-
- ```py copy filename="ubuntu"
- touch agent2.py
- ```
-
-
-
-
-
-
-
-
-
-
- ```py copy filename="agent2.py"
-
- """Chit chat dialogue example"""
-
- from asyncio import sleep
-
- from uagents import Agent, Context, Model
- from uagents.setup import fund_agent_if_low
- from dialogues.chitchat import ChitChatDialogue
-
- CHIT_AGENT_ADDRESS = ""
-
- agent = Agent(
- name="chat_agent",
- seed="",
- port=8002,
- endpoint="http://127.0.0.1:8002/submit",
- )
-
- fund_agent_if_low(agent.wallet.address())
-
- # Define dialogue messages; each transition needs a separate message
- class InitiateChitChatDialogue(Model):
- pass
-
- class AcceptChitChatDialogue(Model):
- pass
-
- class ChitChatDialogueMessage(Model):
- text: str
-
- class ConcludeChitChatDialogue(Model):
- pass
-
- class RejectChitChatDialogue(Model):
- pass
-
- # Instantiate the dialogues
- chitchat_dialogue = ChitChatDialogue(
- version="0.1",
- agent_address=agent.address,
- )
-
- @chitchat_dialogue.on_initiate_session(InitiateChitChatDialogue)
- async def start_chitchat(
- ctx: Context,
- sender: str,
- _msg: InitiateChitChatDialogue,
- ):
- ctx.logger.info(f"Received init message from {sender}")
- # Do something when the dialogue is initiated
- await ctx.send(sender, AcceptChitChatDialogue())
-
- @chitchat_dialogue.on_start_dialogue(AcceptChitChatDialogue)
- async def accept_chitchat(
- ctx: Context,
- sender: str,
- _msg: AcceptChitChatDialogue,
- ):
- ctx.logger.info(
- f"session with {sender} was accepted. I'll say 'Hello!' to start the ChitChat"
- )
- # Do something after the dialogue is started; e.g. send a message
- await ctx.send(sender, ChitChatDialogueMessage(text="Hello!"))
-
- @chitchat_dialogue.on_reject_session(RejectChitChatDialogue)
- async def reject_chitchat(
- ctx: Context,
- sender: str,
- _msg: RejectChitChatDialogue,
- ):
- # Do something when the dialogue is rejected and nothing has been sent yet
- ctx.logger.info(f"Received reject message from: {sender}")
-
- @chitchat_dialogue.on_continue_dialogue(ChitChatDialogueMessage)
- async def continue_chitchat(
- ctx: Context,
- sender: str,
- msg: ChitChatDialogueMessage,
- ):
- ctx.logger.info(f"Received message: {msg.text}")
- try:
- my_msg = input("Please enter your message:\n> ")
- if my_msg != "exit":
- await ctx.send(sender, ChitChatDialogueMessage(text=my_msg))
- else:
- await ctx.send(sender, ConcludeChitChatDialogue())
- ctx.logger.info(
- f"Received conclude message from: {sender}; accessing history:"
- )
- ctx.logger.info(chitchat_dialogue.get_conversation(ctx.session))
- except EOFError:
- await ctx.send(sender, ConcludeChitChatDialogue())
-
- @chitchat_dialogue.on_end_session(ConcludeChitChatDialogue)
- async def conclude_chitchat(
- ctx: Context,
- sender: str,
- _msg: ConcludeChitChatDialogue,
- ):
- # Do something when the dialogue is concluded after messages have been exchanged
- ctx.logger.info(f"Received conclude message from: {sender}; accessing history:")
- ctx.logger.info(chitchat_dialogue.get_conversation(ctx.session))
-
- agent.include(chitchat_dialogue)
-
- # Initiate dialogue by sending message to agent1
- @agent.on_event("startup")
- async def start_cycle(ctx: Context):
- await sleep(5)
- await chitchat_dialogue.start_dialogue(
- ctx, CHIT_AGENT_ADDRESS, InitiateChitChatDialogue()
- )
-
- if __name__ == "__main__":
- print(f"Agent address: {agent.address}")
- agent.run()
-
- ```
-
-
-
-
-
-
-
- Remember to update the agent's address to communicate to each other and seed phrase of own choice.
-
-
-## Step 3: run the dialogue
-
-- Start `agent 1`:
-
- - Run `agent1` using `python agent1.py`
- - Agent 1 is set to accept the dialogue initiation and respond with a greeting.
-
-
-- Start `agent 2`:
-
- - Run `agent2.py` using `python agent2.py`.
- - This agent will automatically attempt to initiate a dialogue by sending an `InitiateChitChatDialogue` message to `agent1`.
-
-## Expected output
-
-- `agent1` logger/terminal output:
-
- ```
- abc@xyz-MacBook-Pro dialogues % python3 agent1.py
- Dialogue overview:
- {
- "nodes": [
- {
- "name": "Default State",
- "description": "This is the default state of the dialogue. Every session starts in this state and is automatically updated once the dialogue starts.",
- "initial": true,
- "final": false
- },
- {
- "name": "Initiated",
- "description": "This is the initial state of the dialogue that is only available at the receiving agent.",
- "initial": false,
- "final": false
- },
- {
- "name": "Chit Chatting",
- "description": "This is the state in which messages are exchanged.",
- "initial": false,
- "final": false
- },
- {
- "name": "Concluded",
- "description": "This is the state after the dialogue has been concluded.",
- "initial": false,
- "final": true
- }
- ],
- "edges": [
- {
- "name": "Initiate session",
- "description": "Every dialogue starts with this transition.",
- "parent": "Default State",
- "child": "Initiated",
- "model": null,
- "starter": true,
- "ender": false
- },
- {
- "name": "Reject session",
- "description": "This is the transition for when the dialogue is rejected",
- "parent": "Initiated",
- "child": "Concluded",
- "model": null,
- "starter": false,
- "ender": true
- },
- {
- "name": "Start dialogue",
- "description": "This is the transition from initiated to chit chatting.",
- "parent": "Initiated",
- "child": "Chit Chatting",
- "model": null,
- "starter": false,
- "ender": false
- },
- {
- "name": "Continue dialogue",
- "description": "This is the transition from one dialogue message to the next, i.e. for when the dialogue continues.",
- "parent": "Chit Chatting",
- "child": "Chit Chatting",
- "model": null,
- "starter": false,
- "ender": false
- },
- {
- "name": "End session",
- "description": "This is the transition for when the session is ended.",
- "parent": "Chit Chatting",
- "child": "Concluded",
- "model": null,
- "starter": false,
- "ender": true
- }
- ]
- }
- ---
- Agent address: agent1qvhlqy2a4lk9gge8ug7l65a6k07wc92hh2d5jhwtat0zakrtg08njmfn00j
- INFO: [chit_agent]: Almanac registration is up to date!
- INFO: [chit_agent]: Starting server on http://0.0.0.0:8001 (Press CTRL+C to quit)
- INFO: [chit_agent]: Received init message from agent1qgp7urkvx24a2gs8e7496fajzy78h4887vz7va4h7klzf7azzhthsz7zymu
- INFO: [chit_agent]: Received message: Hello!
- Please enter your message:
- > Hello Chat agent, It's nice meeting you sir.
- INFO: [chit_agent]: Received message: Do you know we are setting up example of how to use dialogues with agents.
- Please enter your message:
- > Ohh Really...!! That's amazing.
- INFO: [chit_agent]: Received message: We have done it, lets exit this conversation.
- Please enter your message:
- > exit
-
- ```
-
-- `agent2` logger/terminal output:
-
- ```
- abc@xyz-MacBook-Pro dialogues % python3 agent2.py
- Agent address: agent1qgp7urkvx24a2gs8e7496fajzy78h4887vz7va4h7klzf7azzhthsz7zymu
- INFO: [chat_agent]: Almanac registration is up to date!
- INFO: [chat_agent]: Starting server on http://0.0.0.0:8002 (Press CTRL+C to quit)
- INFO: [chat_agent]: session with agent1qvhlqy2a4lk9gge8ug7l65a6k07wc92hh2d5jhwtat0zakrtg08njmfn00j was accepted. I'll say 'Hello!' to start the ChitChat
- INFO: [chat_agent]: Received message: Hello Chat agent, It's nice meeting you sir.
- Please enter your message:
- > Do you know we are setting up example of how to use dialogues with agents.
- INFO: [chat_agent]: Received message: Ohh Really...!! That's amazing.
- Please enter your message:
- > We have done it, lets exit this conversation.
- INFO: [chat_agent]: Received conclude message from: agent1qvhlqy2a4lk9gge8ug7l65a6k07wc92hh2d5jhwtat0zakrtg08njmfn00j; accessing history:
- INFO: [chat_agent]: [{'message_type': 'InitiateChitChatDialogue', 'sender': 'agent1qgp7urkvx24a2gs8e7496fajzy78h4887vz7va4h7klzf7azzhthsz7zymu', 'receiver': 'agent1qvhlqy2a4lk9gge8ug7l65a6k07wc92hh2d5jhwtat0zakrtg08njmfn00j', 'message_content': '{}', 'timestamp': 1713352925.25236, 'timeout': 60}, {'message_type': 'AcceptChitChatDialogue', 'sender': 'agent1qvhlqy2a4lk9gge8ug7l65a6k07wc92hh2d5jhwtat0zakrtg08njmfn00j', 'receiver': 'agent1qgp7urkvx24a2gs8e7496fajzy78h4887vz7va4h7klzf7azzhthsz7zymu', 'message_content': '{}', 'timestamp': 1713352925.363479, 'timeout': 60}, {'message_type': 'ChitChatDialogueMessage', 'sender': 'agent1qgp7urkvx24a2gs8e7496fajzy78h4887vz7va4h7klzf7azzhthsz7zymu', 'receiver': 'agent1qvhlqy2a4lk9gge8ug7l65a6k07wc92hh2d5jhwtat0zakrtg08njmfn00j', 'message_content': '{"text": "Hello!"}', 'timestamp': 1713352925.364252, 'timeout': 60}, {'message_type': 'ChitChatDialogueMessage', 'sender': 'agent1qvhlqy2a4lk9gge8ug7l65a6k07wc92hh2d5jhwtat0zakrtg08njmfn00j', 'receiver': 'agent1qgp7urkvx24a2gs8e7496fajzy78h4887vz7va4h7klzf7azzhthsz7zymu', 'message_content': '{"text": "Hello Chat agent, It\'s nice meeting you sir."}', 'timestamp': 1713352940.489155, 'timeout': 60}, {'message_type': 'ChitChatDialogueMessage', 'sender': 'agent1qgp7urkvx24a2gs8e7496fajzy78h4887vz7va4h7klzf7azzhthsz7zymu', 'receiver': 'agent1qvhlqy2a4lk9gge8ug7l65a6k07wc92hh2d5jhwtat0zakrtg08njmfn00j', 'message_content': '{"text": "Do you now we are setting up example of how to use dialogues with agents."}', 'timestamp': 1713352978.223705, 'timeout': 60}, {'message_type': 'ChitChatDialogueMessage', 'sender': 'agent1qvhlqy2a4lk9gge8ug7l65a6k07wc92hh2d5jhwtat0zakrtg08njmfn00j', 'receiver': 'agent1qgp7urkvx24a2gs8e7496fajzy78h4887vz7va4h7klzf7azzhthsz7zymu', 'message_content': '{"text": "Ohh Really...!! That's amazing."}', 'timestamp': 1713353000.452756, 'timeout': 60}, {'message_type': 'ChitChatDialogueMessage', 'sender': 'agent1qgp7urkvx24a2gs8e7496fajzy78h4887vz7va4h7klzf7azzhthsz7zymu', 'receiver': 'agent1qvhlqy2a4lk9gge8ug7l65a6k07wc92hh2d5jhwtat0zakrtg08njmfn00j', 'message_content': '{"text": "We have done it, lets exit this conversation."}', 'timestamp': 1713353026.271922, 'timeout': 60}, {'message_type': 'ConcludeChitChatDialogue', 'sender': 'agent1qvhlqy2a4lk9gge8ug7l65a6k07wc92hh2d5jhwtat0zakrtg08njmfn00j', 'receiver': 'agent1qgp7urkvx24a2gs8e7496fajzy78h4887vz7va4h7klzf7azzhthsz7zymu', 'message_content': '{}', 'timestamp': 1713353031.887555, 'timeout': 60}]
- ```
diff --git a/pages/examples/dialogues/predefined-dialogue-chitchat.mdx b/pages/examples/dialogues/predefined-dialogue-chitchat.mdx
deleted file mode 100644
index 3404b0e34..000000000
--- a/pages/examples/dialogues/predefined-dialogue-chitchat.mdx
+++ /dev/null
@@ -1,642 +0,0 @@
-import { Callout } from 'nextra/components'
-import { CodeGroup, DocsCode, CodeSegment, GithubCodeSegment } from "../../../components/code";
-
-# Predefined Dialogue Chit-Chat
-
-## Overview
-
-This example illustrates an automated dialogue scenario using a hardcoded dialogue management system between two agents. The dialogue flow is predefined, minimizing the need for manual intervention or dynamic decision-making during the dialogue process.
-
-Please check out the example code in our [examples repo ↗️](https://github.com/fetchai/uAgent-Examples/tree/main/5-documentation/examples/advanced/predefined-dialogue-chitchat) to run this locally.
-
-### Guide
-
-- [How to use Dialogues ↗️](/guides/agents/dialogues)
-
-### Supporting documentation
-
-- [Creating an agent ↗️](/guides/agents/create-a-uagent)
-- [Communicating with other agents ↗️](/guides/agents/communicating-with-other-agents)
-- [Register in Almanac ↗️](/guides/agents/register-in-almanac)
-- [Almanac Contract ↗️](/references/contracts/uagents-almanac/almanac-overview)
-
-## Step 1: Define the Dialogue management
-
-`hardcoded_chitchat.py` sets up a structured dialogue system with predefined responses. This system includes nodes representing different states of the dialogue and edges defining possible transitions between these states.
-
-- Open a terminal and create a directory using `mkdir Dialogues` and navigate into it with `cd Dialogues`.
-- Create a python file `hardcoded_chitchat.py` in `Dialogues` directory:
-
-
-
- ```py copy filename="mac"
- touch chitchat.py
- ```
-
-
- ```py copy filename="windows"
- echo. > chitchat.py
- ```
-
-
-
- ```py copy filename="ubuntu"
- touch chitchat.py
- ```
-
-
-
-
-- Import required libraries.
-
-
-
-
-
-
-
- ```py copy filename="hardcoded_chitchat.py"
-
- from typing import Type
- from warnings import warn
- from uagents import Model
- from uagents.context import Context
- from uagents.experimental.dialogues import Dialogue, Edge, Node
-
-
- ```
-
-
-
-
-
-
-- Define dialogue message models, each transition needs a separate message.
-
-
-
-
-
-
-
- ```py copy filename="hardcoded_chitchat.py"
-
- # define dialogue messages; each transition needs a separate message
- class InitiateChitChatDialogue(Model):
- pass
-
- class AcceptChitChatDialogue(Model):
- pass
-
- class ChitChatDialogueMessage(Model):
- text: str
-
- class ConcludeChitChatDialogue(Model):
- pass
-
- class RejectChitChatDialogue(Model):
- pass
-
-
- ```
-
-
-
-
-
-
-- Define `nodes` (state) of dialogues like default, initiate, chitchat and end state.
-
-
-
-
-
-
-
- ```py copy filename="hardcoded_chitchat.py"
-
- # Node definition for the dialogue states
- default_state = Node(
- name="Default State",
- description=(
- "This is the default state of the dialogue. Every session starts in "
- "this state and is automatically updated once ."
- ),
- initial=True,
- )
-
- # Currently not used as states are measured by the edges
- init_state = Node(
- name="Initiated",
- description=(
- "This is the initial state of the dialogue that is only available at "
- "the receiving agent."
- )
- )
-
- chatting_state = Node(
- name="Chit Chatting",
- description="This is the state in which messages are exchanged.",
- )
-
- end_state = Node(
- name="Concluded",
- description="This is the state after the dialogue has been concluded.",
- )
-
-
- ```
-
-
-
-
-
-
-- Define `edges` (transition) of dialogues like initiate session, start dialogue, continue dialogue and end session.
-
-
-
-
-
-
-
- ```py copy filename="hardcoded_chitchat.py"
-
- # Edge definition for the dialogue transitions
- init_session = Edge(
- name="initiate_session",
- description="Every dialogue starts with this transition.",
- parent=None,
- child=init_state,
- )
-
- start_dialogue = Edge(
- name="start_dialogue",
- description="This is the transition from initiated to chit chatting.",
- parent=init_state,
- child=chatting_state,
- )
-
- cont_dialogue = Edge(
- name="continue_dialogue",
- description=(
- "This is the transition from one dialogue message to the next, "
- "i.e. for when the dialogue continues."
- ),
- parent=chatting_state,
- child=chatting_state,
- )
-
- end_session = Edge(
- name="end_session",
- description="This is the transition for when the session is ended.",
- parent=chatting_state,
- child=end_state,
- )
-
-
- ```
-
-
-
-
-
-
-- Define default behaviour for individual dialogue edges. Only the interaction that requires input from the user is exposed, making the other parts of the dialogue more robust and easier to maintain.
-
-
-
-
-
-
-
- ```py copy filename="hardcoded_chitchat.py"
-
-
- async def start_chitchat(ctx: Context,sender: str,_msg: Type[Model]):
- ctx.logger.info(f"Received init message from {sender}. Accepting Dialogue.")
- await ctx.send(sender, AcceptChitChatDialogue())
-
- async def accept_chitchat(ctx: Context,sender: str,_msg: Type[Model],):
- ctx.logger.info(
- f"Dialogue session with {sender} was accepted. "
- "I'll say 'Hello!' to start the ChitChat"
- )
- await ctx.send(sender, ChitChatDialogueMessage(text="Hello!"))
-
- async def conclude_chitchat(ctx: Context,sender: str,_msg: Type[Model],):
- ctx.logger.info(f"Received conclude message from: {sender}; accessing history:")
- ctx.logger.info(ctx.dialogue)
-
- async def default(_ctx: Context,_sender: str,_msg: Type[Model],):
- warn(
- "There is no handler for this message, please add your own logic by "
- "using the `on_continue_dialogue` decorator.",
- RuntimeWarning,
- stacklevel=2,
- )
-
- async def persisting_function(ctx: Context,_sender: str,_msg: Type[Model],):
- ctx.logger.info("I was not overwritten, hehe.")
-
-
- ```
-
-
-
-
-
-
-- In the provided code, specific message types associated with different dialogue states trigger predefined functions that manage the flow and actions of the dialogue, automating the transition between states and handling interactions within the dialogue system efficiently.
-
-
-
-
-
-
-
- ```py copy filename="hardcoded_chitchat.py"
-
-
-
- init_session.set_message_handler(InitiateChitChatDialogue, start_chitchat)
- start_dialogue.set_message_handler(AcceptChitChatDialogue, accept_chitchat)
- cont_dialogue.set_message_handler(ChitChatDialogueMessage, default)
- cont_dialogue.set_edge_handler(ChitChatDialogueMessage, persisting_function)
- end_session.set_message_handler(ConcludeChitChatDialogue, conclude_chitchat)
-
-
- ```
-
-
-
-
-
-
-- Define `ChitChatDialogue` class and include nodes and edges into it. These acts as rule for chit chat dialogues.
-
-
-
-
-
-
-
- ```py copy filename="hardcoded_chitchat.py"
-
-
- class ChitChatDialogue(Dialogue):
- """
- This is the specific definition of the rules for the chit-chat dialogue
- The rules will be predefined and the actual messages will be passed into it.
-
- In this specific instance of the ChitChatDialogue, some parts of the dialogue
- are hardcoded, such as the initial message and the response to it.
- This is done to demonstrate that the dialogue can be defined in a way for
- developers to only focus on the parts that are relevant to them.
- """
- def __init__(
- self,
- version: str | None = None,
- ) -> None:
- super().__init__(
- name="ChitChatDialogue",
- version=version,
- nodes=[
- init_state,
- chatting_state,
- end_state,
- ],
- edges=[
- init_session,
- start_dialogue,
- cont_dialogue,
- end_session,
- ],
- )
-
- def on_continue_dialogue(self):
- """
- This handler is triggered for every incoming "chitchat" message
- once the session has been accepted.
- Any additional stateful information within a dialogue needs to be
- persisted explicitly to access it at a later point in the dialogue.
- """
- return super()._on_state_transition(
- cont_dialogue.name,
- ChitChatDialogueMessage,
- )
-
- ```
-
-
-
-
-
-
-Include all the above mentioned script sections into a single script and save it as `hardcoded_chitchat.py`
-
-## Step 2: setting up the agents
-
-These two agents use the `hardcoded_chitchat` dialogue system to automate the interaction with minimal intervention. The dialogue is mostly automated, with `agent3` configured to respond to initiation and continue based on predefined rules, and `agent4` automatically initiating the conversation.
-
-### Setting up `agent1`
-
-`agent1` is designed to receive and respond to messages according to hardcoded rules within the ChitChatDialogue class.
-
- - Navigate to your working directory and create a Python script named `agent1.py`.
- - Copy the following script into `agent1.py`:
-
-
-
-
-
-
-
- ```py copy filename="agent1.py"
-
- # Import required libraries
- import json
-
- from uagents import Agent
- from uagents.context import Context
-
- from dialogues.hardcoded_chitchat import (ChitChatDialogue,
- ChitChatDialogueMessage,
- ConcludeChitChatDialogue)
-
- CHAT_AGENT_ADDRESS = ""
-
- agent = Agent(
- name="chit_agent",
- seed="",
- port=8001,
- endpoint="http://127.0.0.1:8001/submit",
- )
-
- # Instantiate the dialogues
- chitchat_dialogue = ChitChatDialogue(
- version="0.1",
- )
-
- # Get an overview of the dialogue structure
- print("Dialogue overview:")
- print(json.dumps(chitchat_dialogue.get_overview(), indent=4))
- print("---")
-
- # This is the only decorator that is needed to add to your agent with the
- # hardcoded dialogue example. If you omit this decorator, the dialogue will
- # emit a warning.
- @chitchat_dialogue.on_continue_dialogue()
- async def continue_chitchat(
- ctx: Context,
- sender: str,
- msg: ChitChatDialogueMessage,
- ):
- # Do something when the dialogue continues
- ctx.logger.info(f"Received message: {msg.text}")
- try:
- my_msg = input("Please enter your message:\n> ")
- await ctx.send(sender, ChitChatDialogueMessage(text=my_msg))
- except EOFError:
- await ctx.send(sender, ConcludeChitChatDialogue())
-
- agent.include(chitchat_dialogue) # Including dialogue in agent
-
- if __name__ == "__main__":
- print(f"Agent address: {agent.address}")
- agent.run() # Running agent
-
-
- ```
-
-
-
-
-
-
-### Setting up `agent2`
-
-`agent2` is configured to automatically initiate a dialogue with `agent1` using the predefined dialogue system.
-
- - Create a new Python script named `agent2.py` in the same directory.
- - Paste the following code into `agent2.py`:
-
-
-
-
-
-
-
- ```py copy filename="agent2.py"
-
- """Chit chat dialogue example"""
-
- from asyncio import sleep
-
- from uagents import Agent, Context
-
- from dialogues.hardcoded_chitchat import (ChitChatDialogue,
- ChitChatDialogueMessage,
- InitiateChitChatDialogue)
-
- CHIT_AGENT_ADDRESS = ""
-
- agent = Agent(
- name="chat_agent",
- seed="",
- port=8002,
- endpoint="http://127.0.0.1:8002/submit",
- )
-
- # Instantiate the dialogues
- chitchat_dialogue = ChitChatDialogue(
- version="0.1",
- )
-
- @chitchat_dialogue.on_continue_dialogue()
- async def continue_chitchat(
- ctx: Context,
- sender: str,
- msg: ChitChatDialogueMessage,
- ):
- ctx.logger.info(f"Returning: {msg.text}")
- await ctx.send(sender, ChitChatDialogueMessage(text=msg.text))
-
- # Initiate dialogue after 5 seconds
- @agent.on_event("startup")
- async def start_cycle(ctx: Context):
- await sleep(5)
- await chitchat_dialogue.start_dialogue(
- ctx, CHIT_AGENT_ADDRESS, InitiateChitChatDialogue()
- )
-
- agent.include(chitchat_dialogue)
-
- if __name__ == "__main__":
- print(f"Agent address: {agent.address}")
- agent.run()
-
- ```
-
-
-
-
-
-
-
- Remember to update the agent's address to communicate to each other and seed phrase of own choice.
-
-
-## Step 3: Run the Dialogue
-
- - Start `agent1`:
- - Run `agent1` using `python agent1.py`
- - `agent1` will respond based on the hardcoded rules within the `ChitChatDialogue`. The interaction will continue until a predefined conclusion condition is met, such as an "exit" message or similar.
-
- - Start `agent2`:
- - Run `agent2.py` using `python agent2.py`.
- - `Agent4` will automatically initiate the conversation with `Agent3` after a five-second delay.
-
-## Expected output
-
-- `agent1` logger/terminal output:
-
- ```
- abc@xyz-MacBook-Pro dialogues % python3 agent1.py
- Dialogue overview:
- {
- "nodes": [
- {
- "name": "Initiated",
- "description": "This is the initial state of the dialogue that is only available at the receiving agent.",
- "initial": false,
- "final": false
- },
- {
- "name": "Chit Chatting",
- "description": "This is the state in which messages are exchanged.",
- "initial": false,
- "final": false
- },
- {
- "name": "Concluded",
- "description": "This is the state after the dialogue has been concluded.",
- "initial": false,
- "final": true
- }
- ],
- "edges": [
- {
- "name": "initiate_session",
- "description": "Every dialogue starts with this transition.",
- "parent": null,
- "child": "Initiated",
- "model": "InitiateChitChatDialogue",
- "starter": true,
- "ender": false
- },
- {
- "name": "start_dialogue",
- "description": "This is the transition from initiated to chit chatting.",
- "parent": "Initiated",
- "child": "Chit Chatting",
- "model": "AcceptChitChatDialogue",
- "starter": false,
- "ender": false
- },
- {
- "name": "continue_dialogue",
- "description": "This is the transition from one dialogue message to the next, i.e. for when the dialogue continues.",
- "parent": "Chit Chatting",
- "child": "Chit Chatting",
- "model": "ChitChatDialogueMessage",
- "starter": false,
- "ender": false
- },
- {
- "name": "end_session",
- "description": "This is the transition for when the session is ended.",
- "parent": "Chit Chatting",
- "child": "Concluded",
- "model": "ConcludeChitChatDialogue",
- "starter": false,
- "ender": true
- }
- ]
- }
- ---
- Agent address: agent1qfjvt60h0kh573fzy9mvmlsr50vff8xmdfeclfgy3g9g6qq6jxkuxh4cu3w
- INFO: [chit_agent]: Almanac registration is up to date!
- INFO: [chit_agent]: Starting server on http://0.0.0.0:8001 (Press CTRL+C to quit)
- INFO: [chit_agent]: Received init message from agent1qwvecfwc255pfqqwtjznh9qqk6skl77xc6fzw8mr3ppfex32sr0kcad62n4. Accepting Dialogue.
- INFO: [chit_agent]: I was not overwritten, hehe.
- INFO: [chit_agent]: Received message: Hello!
- Please enter your message:
- > we are providing example for predefined dialogue
- INFO: [chit_agent]: I was not overwritten, hehe.
- INFO: [chit_agent]: Received message: we are providing example for predefined dialogue
- Please enter your message:
- > The message is sent but there is no functionality to get back
- INFO: [chit_agent]: I was not overwritten, hehe.
- INFO: [chit_agent]: Received message: The message is sent but there is no functionality to get back
- Please enter your message:
- ```
-
-- `agent2` logger/terminal output:
-
- ```
- abc@xyz dialogues % python3 agent2.py
- Agent address: agent1qwvecfwc255pfqqwtjznh9qqk6skl77xc6fzw8mr3ppfex32sr0kcad62n4
- INFO: [chat_agent]: Almanac registration is up to date!
- INFO: [chat_agent]: Starting server on http://0.0.0.0:8002 (Press CTRL+C to quit)
- INFO: [chat_agent]: Dialogue session with agent1qfjvt60h0kh573fzy9mvmlsr50vff8xmdfeclfgy3g9g6qq6jxkuxh4cu3w was accepted. I'll say 'Hello!' to start the ChitChat
- INFO: [chat_agent]: I was not overwritten, hehe.
- INFO: [chat_agent]: Returning: we are providing example for predefined dialogue
- INFO: [chat_agent]: I was not overwritten, hehe.
- INFO: [chat_agent]: Returning: The message is sent but there is no functionality to get back
- ```
diff --git a/pages/examples/examplestech/_meta.json b/pages/examples/examplestech/_meta.json
deleted file mode 100644
index b1cf6ec15..000000000
--- a/pages/examples/examplestech/_meta.json
+++ /dev/null
@@ -1,5 +0,0 @@
-{
- "jupyter-agent": "Jupyter Notebook Agent",
- "hugging-face-agent": "Hugging Face Agent",
- "react-example": "React web app Agent"
-}
diff --git a/pages/examples/examplestech/hugging-face-agent.mdx b/pages/examples/examplestech/hugging-face-agent.mdx
deleted file mode 100644
index 1f41ca200..000000000
--- a/pages/examples/examplestech/hugging-face-agent.mdx
+++ /dev/null
@@ -1,388 +0,0 @@
-import { CodeGroup, DocsCode } from "../../../components/code"
-
-# Hugging face API agent as a Function
-
-## Introduction
-
-This system shows how to integrate the Hugging Face API with an Agentverse Agent. The example consists of multiple layers of Primary and Secondary functions, with the Hugging Face system as the main Primary function and Hugging Face request and model list as Secondary function.
-
-### Supporting documentation
-
-- [Creating an agent ↗️](/guides/agents/create-a-uagent)
-
-- [Register in Almanac ↗️](/guides/agents/register-in-almanac)
-
-- [Almanac Contract ↗️](/references/contracts/uagents-almanac/almanac-overview)
-
-- [Protocols ↗️](/references/uagents/uagents-protocols/agent-protocols)
-
-- [Agentverse Functions ↗️](/guides/agents/intermediate/agent-functions)
-
-- [Register an Agent Function on the Agentverse ↗️](/guides/agentverse/registering-agent-services)
-
-### The agents
-#### Hugging Face System Agent
-
-
-
-
- ```python copy filename="agent.py"
- # Here we demonstrate how we can create a hugging face system agent that is compatible with DeltaV.
-
- # Importing required libraries.
- import requests
- from uagents import Agent, Context, Model, Field, Protocol
- from uagents.setup import fund_agent_if_low
- from ai_engine import UAgentResponse, UAgentResponseType
-
- # Define a model class for the Hugging Face agent's expected message format.
- class HF(Model):
- response : str # This class has a single attribute 'response' that holds the string response from the subtask.
-
- # 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!
- hf_agent = Agent(
- name="hf_agent",
- seed=SEED_PHRASE,
- mailbox=True
- )
-
- fund_agent_if_low(hf_agent.wallet.address())
-
- # Copy the address shown below
- print(f"Your agent's address is: {hf_agent.address}")
-
- # Create a protocol for the Hugging Face (HF) agent, specifying its communication protocol.
- hf_protocol = Protocol("Hugging Face")
-
- # Define a handler for the Hugging face protocol.
- @hf_protocol.on_message(model=HF, replies = UAgentResponse)
- async def on_hf_request(ctx: Context, sender: str, msg: HF):
-
- # Log the receipt of a response, including the sender and the message prompt.
- ctx.logger.info(f"Received hugging face request from {sender} with prompt: {msg.response}")
-
- # Format a response message incorporating the received message.
- message = f'Response to your query from model is \n {msg.response}'
- # Asynchronously send a response back to the sender with the processed message.
- await ctx.send(sender, UAgentResponse(message = message, type = UAgentResponseType.FINAL))
-
- # Include the Hugging Face protocol in your agent.
- hf_agent.include(hf_protocol)
-
- hf_agent.run()
- ```
-
-
-
-
-
- ```python copy filename="agent.py"
- # Here we demonstrate how we can create a hugging face system agent that is compatible with DeltaV.
-
- # After running this agent, it can be registered to DeltaV on Agentverse. For registration you will have to use the agent's address.
-
- # Importing required libraries.
- import requests
- from ai_engine import UAgentResponse, UAgentResponseType
-
- # Define a model class for the Hugging Face agent's expected message format.
- class HF(Model):
- response : str # This class has a single attribute 'response' that holds the string response from the subtask.
-
- # Create a protocol for the Hugging Face (HF) agent, specifying its communication protocol.
- hf_protocol = Protocol("Hugging Face")
-
- # Define a handler for the Hugging face protocol.
- @hf_protocol.on_message(model=HF, replies = UAgentResponse)
- async def on_hf_request(ctx: Context, sender: str, msg: HF):
-
- # Log the receipt of a response, including the sender and the message prompt.
- ctx.logger.info(f"Received hugging face request from {sender} with prompt: {msg.response}")
-
- # Format a response message incorporating the received message.
- message = f'Response to your query from model is \n {msg.response}'
- # Asynchronously send a response back to the sender with the processed message.
- await ctx.send(sender, UAgentResponse(message = message, type = UAgentResponseType.FINAL))
-
- # Include the Hugging Face protocol in your agent.
- agent.include(hf_protocol)
- ```
-
-
-
-#### Hugging Face Request Agent
-
-
-
-
-
- ```python copy filename="agent.py"
- # Here we demonstrate how we can create a hugging face request agent that is compatible with DeltaV.
-
- # After running this agent, it can be registered to DeltaV on Agentverse. For registration you will have to use the agent's address.
-
- # Importing required libraries.
- import requests
- import json
- from uagents import Agent, Context, Model, Field, Protocol
- from uagents.setup import fund_agent_if_low
- from ai_engine import UAgentResponse, UAgentResponseType
-
- # Define a model class for the Hugging Face Request agent's expected message format.
- class Search(Model):
- model_id : str
- query : str
-
- # Define a function to handle query from user using model_id and query provided by user.
- async def handle_query(model_id, query):
- Model_ID = model_id
- API_URL = f'https://api-inference.huggingface.co/models/{Model_ID}' # hugging face url
- API_TOKEN = 'YOUR TOKEN HERE' # hugging face API token
-
- headers = {"Authorization": f"Bearer {API_TOKEN}"}
-
- # Make request to hugging face API with model_id and query.
- response = requests.post(API_URL, headers=headers, json=query).json()
- return response
-
- # 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!
- hf_request_agent = Agent(
- name="hf_request_agent",
- seed=SEED_PHRASE,
- mailbox=True
- )
-
- fund_agent_if_low(hf_request_agent.wallet.address())
-
- # Copy the address shown below
- print(f"Your agent's address is: {hf_request_agent.address}")
-
- # Create a protocol for the Hugging Face Request(HF) agent, specifying its communication protocol.
- hfprotocol = Protocol(name = 'Hugging Face protocol')
-
- # Define a handler for the Hugging face request protocol.
- @hfprotocol.on_message(model = Search, replies = UAgentResponse)
- async def handle_message(ctx: Context, sender: str, msg: Search):
-
- # Log the model_id and query provided by user.
- ctx.logger.info(f'Message sent from {sender} : {msg.model_id}')
- ctx.logger.info(f'Message sent from subtask : {msg.query}')
-
- # Calling handle_query function to get response from API.
- response = await handle_query(msg.model_id, msg.query)
- # sending response to hugging face agent
- await ctx.send(sender, UAgentResponse(message = str(response), type = UAgentResponseType.FINAL))
-
- # Include the Hugging Face protocol in your agent.
- hf_request_agent.include(hfprotocol, publish_manifest = True)
-
- hf_request_agent.run()
- ```
-
-
-
-
- ```python copy filename="agent.py"
- # Here we demonstrate how we can create a hugging face request agent that is compatible with DeltaV.
-
- # After running this agent, it can be registered to DeltaV on Agentverse. For registration you will have to use the agent's address.
-
- # Importing required libraries.
- import requests
- import json
- from ai_engine import UAgentResponse, UAgentResponseType
-
- # Define a model class for the Hugging Face Request agent's expected message format.
- class Search(Model):
- model_id : str
- query : str
-
- # Define a function to handle query from user using model_id and query provided by user.
- async def handle_query(model_id, query):
- Model_ID = model_id
- API_URL = f'https://api-inference.huggingface.co/models/{Model_ID}' # hugging face url
- API_TOKEN = 'YOUR TOKEN HERE' # hugging face API token
-
- headers = {"Authorization": f"Bearer {API_TOKEN}"}
-
- # Make request to hugging face API with model_id and query.
- response = requests.post(API_URL, headers=headers, json=query).json()
- return response
-
- # Create a protocol for the Hugging Face Request(HF) agent, specifying its communication protocol.
- hfprotocol = Protocol(name = 'Hugging Face protocol')
-
- # Define a handler for the Hugging face request protocol.
- @hfprotocol.on_message(model = Search, replies = UAgentResponse)
- async def handle_message(ctx: Context, sender: str, msg: Search):
-
- # Log the model_id and query provided by user.
- ctx.logger.info(f'Message sent from {sender} : {msg.model_id}')
- ctx.logger.info(f'Message sent from subtask : {msg.query}')
-
- # Calling handle_query function to get response from API.
- response = await handle_query(msg.model_id, msg.query)
- # sending response to hugging face agent
- await ctx.send(sender, UAgentResponse(message = str(response), type = UAgentResponseType.FINAL))
-
- # Include the Hugging Face protocol in your agent.
- agent.include(hfprotocol, publish_manifest = True)
- ```
-
-
-#### Model List Agent
-
-
-
-
-
- ```python copy filename="agent.py"
- # Here we demonstrate how we can create a model list agent that is compatible with DeltaV.
-
- # Importing required libraries.
- import requests
- from ai_engine import UAgentResponse, UAgentResponseType
- import json
-
- # Define a model class for the Model List agent's expected message format.
- class Search(Model):
- search : str # This is a keyword for which user wants to search model
-
- # 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!
- model_list_agent = Agent(
- name="model_list_agent",
- seed=SEED_PHRASE,
- mailbox=True
- )
-
- fund_agent_if_low(model_list_agent.wallet.address())
-
- # Copy the address shown below
- print(f"Your agent's address is: {model_list_agent.address}")
-
- # Create a protocol for the Model List agent, specifying its communication protocol.
- model_list_protocol = Protocol(name = 'Model List protocol')
-
- # Define a function to handle query from user using search keyword provided by user.
- async def handle_query(search):
- url = "https://huggingface.co/api/models"
-
- params = {
- "search": search,
- "filter": "text-classification",
- "sort": "downloads",
- "direction": -1,
- "limit": 5
- } # Search parameters.
-
- models = [] # List of models.
-
- # Make the GET request.
- response = requests.get(url, params = params)
-
- # Append models in list.
- for model in response.json():
- models.append(model['id'])
-
- return models
-
- # Define a handler for the Model list protocol.
- @model_list_protocol.on_message(model = Search, replies = UAgentResponse)
- async def handle_message(ctx: Context, sender: str, msg: Search):
- # Log search keyword provided by user.
- ctx.logger.info(f'Message sent from {sender} : {msg.search}')
-
- # Call handle_query to get list of models.
- options = handle_query(msg.search)
- # Log model list responded by hugging face request.
- ctx.logger.info(f'Message sent from {sender} : {options}')
-
- # Format options in dictionary format to provide options to user.
- formatted_options = [{'key': i + 1, 'value': value} for i, value in enumerate(options)]
-
- # Send message to the user.
- await ctx.send(sender, UAgentResponse(message = str(formatted_options), type=UAgentResponseType.FINAL))
-
- # Include model_list protocol in agent.
- model_list_agent.include(model_list_protocol, publish_manifest = True)
-
- model_list_agent.run()
- ```
-
-
-
-
- ```python copy filename="agent.py"
- # Here we demonstrate how we can create a model list agent that is compatible with DeltaV.
-
- # After running this agent, it can be registered to DeltaV on Agentverse. For registration you will have to use the agent's address.
-
- # Importing required libraries.
- import requests
- from ai_engine import UAgentResponse, UAgentResponseType
- import json
-
- # Define a model class for the Model List agent's expected message format.
- class Search(Model):
- search : str # This is a keyword for which user wants to search model
-
- # Create a protocol for the Model List agent, specifying its communication protocol.
- model_list_protocol = Protocol(name = 'Model List protocol')
-
- # Define a function to handle query from user using search keyword provided by user.
- async def handle_query(search):
- url = "https://huggingface.co/api/models"
-
- params = {
- "search": search,
- "filter": "text-classification",
- "sort": "downloads",
- "direction": -1,
- "limit": 5
- } # Search parameters.
-
- models = [] # List of models.
-
- # Make the GET request.
- response = requests.get(url, params = params)
-
- # Append models in list.
- for model in response.json():
- models.append(model['id'])
-
- return models
-
- # Define a handler for the Model list protocol.
- @model_list_protocol.on_message(model = Search, replies = UAgentResponse)
- async def handle_message(ctx: Context, sender: str, msg: Search):
- # Log search keyword provided by user.
- ctx.logger.info(f'Message sent from {sender} : {msg.search}')
-
- # Call handle_query to get list of models.
- options = handle_query(msg.search)
- # Log model list responded by hugging face request.
- ctx.logger.info(f'Message sent from {sender} : {options}')
-
- # Format options in dictionary format to provide options to user.
- formatted_options = [{'key': i + 1, 'value': value} for i, value in enumerate(options)]
-
- # Send message to the user.
- await ctx.send(sender, UAgentResponse(message = str(formatted_options), type=UAgentResponseType.FINAL))
-
- # Include model_list protocol in agent.
- agent.include(model_list_protocol, publish_manifest = True)
- ```
-
-
\ No newline at end of file
diff --git a/pages/examples/examplestech/jupyter-agent.mdx b/pages/examples/examplestech/jupyter-agent.mdx
deleted file mode 100644
index 65a0af596..000000000
--- a/pages/examples/examplestech/jupyter-agent.mdx
+++ /dev/null
@@ -1,312 +0,0 @@
-import { CodeGroup, CodeSegment, DocsCode, GithubCodeSegment } from "../../../components/code";
-
-# Using Jupyter notebook to build an Agent
-
-**Jupyter notebook** natively supports asyncio, and as [Agents ↗️](/guides/agents/getting-started/whats-an-agent) are asynchronous by design, Jupyter and Agents work together with ease.
-
-Please check out the example code in our [examples repo ↗️](https://github.com/fetchai/uAgent-Examples/tree/main/3-applications/jupyter-notebook) to run this locally.
-
-## Installation
-
-We're using [poetry ↗️](https://python-poetry.org/) to manage our application, but it is not super essential for you. Just be sure to have the following libraries installed on your system:
-
- ```bash
- python = "3.11"
- uagents = "^0.17.1"
- notebook = "^7.2.2"
- jupyter = "^1.1.1"
- ```
-
-Are you new to Agents? To understand the agent in this example, please read [communicating with agents ↗️](/guides/agents/intermediate/communicating-with-other-agents)
-
-## Notebook
-
-
-
-
-
-
-
- ```py copy filename="agent_in_notebook.ipynb?short_path=9c85396"
-
- {
- "cells": [
- {
- "cell_type": "code",
- "execution_count": 34,
- "id": "790cab08-020a-4903-80f5-10392785944a",
- "metadata": {},
- "outputs": [],
- "source": [
- "from uagents import Agent, Context, Model\n",
- "from uagents.setup import fund_agent_if_low\n",
- "import os\n",
- "import asyncio\n",
- "import contextlib"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 35,
- "id": "ff526b8f-5e08-47c9-af87-80cdd6eba972",
- "metadata": {},
- "outputs": [],
- "source": [
- "# comment "
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 36,
- "id": "85aae090-2724-4bde-9f7c-e593135a410f",
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "<_UnixSelectorEventLoop running=True closed=False debug=False>\n"
- ]
- }
- ],
- "source": [
- "loop = asyncio.get_event_loop()\n",
- "print (loop)"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 37,
- "id": "a09b9f72-5b41-486f-95df-900233a2742a",
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "agent1qdwgulp6q2jw93u3yhh9teectdjaxvrmmwl900cs33vz4skkawstg3q74n4\n"
- ]
- }
- ],
- "source": [
- "agent = Agent(\n",
- " name=\"first_agent\",\n",
- " seed=\"AGENT_1_SEED\",\n",
- " endpoint=[\"http://127.0.0.1:8005/submit\"],\n",
- " port=8005)\n",
- "\n",
- "SECOND_AGENT_ADDRESS = (\n",
- " \"agent1qdceynp4t0lel3cfdlvlezjva8tf6fww8jd97vs9ym2h3g678e65vjj8vjh\"\n",
- ")\n",
- "\n",
- "print (agent.address)\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 38,
- "id": "15182730-93b4-41a5-878b-674be50c240e",
- "metadata": {},
- "outputs": [],
- "source": [
- "class ResponseMessage(Model):\n",
- " text: str\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 39,
- "id": "e83d7f83-58a5-4e54-995d-30aca419128f",
- "metadata": {},
- "outputs": [],
- "source": [
- "@agent.on_event(\"startup\")\n",
- "async def on_startup(ctx: Context):\n",
- " message = ResponseMessage(text=\"Hello from first agent\")\n",
- " await ctx.send(SECOND_AGENT_ADDRESS, message)\n",
- "\n",
- "\n",
- "@agent.on_message(model=ResponseMessage)\n",
- "async def handle_message(ctx: Context, sender: str, msg: ResponseMessage):\n",
- " ctx.logger.info(f\"Received message from {sender}: {msg.text}\")\n",
- " "
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 40,
- "id": "a685d22f-f8b0-4026-812c-855ecdcf87ea",
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "\n"
- ]
- }
- ],
- "source": [
- "print(agent)"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 41,
- "id": "ba14c679-f6a5-4ccf-9023-62e1de12b806",
- "metadata": {},
- "outputs": [
- {
- "data": {
- "text/plain": [
- ">"
- ]
- },
- "execution_count": 41,
- "metadata": {},
- "output_type": "execute_result"
- },
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "INFO: [first_agent]: Registration on Almanac API successful\n",
- "INFO: [first_agent]: Registration on Almanac API successful\n",
- "INFO: [first_agent]: Registration on Almanac API successful\n",
- "INFO: [first_agent]: Registration on Almanac API successful\n",
- "INFO: [first_agent]: Registration on Almanac API successful\n",
- "INFO: [first_agent]: Registration on Almanac API successful\n",
- "INFO: [first_agent]: Almanac contract registration is up to date!\n",
- "INFO: [first_agent]: Almanac contract registration is up to date!\n",
- "INFO: [first_agent]: Almanac contract registration is up to date!\n",
- "INFO: [first_agent]: Almanac contract registration is up to date!\n",
- "INFO: [first_agent]: Almanac contract registration is up to date!\n",
- "INFO: [first_agent]: Almanac contract registration is up to date!\n",
- "ERROR: [first_agent]: Unable to resolve destination endpoint\n",
- "ERROR: [first_agent]: Unable to resolve destination endpoint\n",
- "ERROR: [first_agent]: Unable to resolve destination endpoint\n",
- "ERROR: [first_agent]: Unable to resolve destination endpoint\n",
- "ERROR: [first_agent]: Unable to resolve destination endpoint\n",
- "ERROR: [first_agent]: Unable to resolve destination endpoint\n",
- "INFO: [first_agent]: Agent inspector available at https://agentverse.ai/inspect/?uri=http%3A//127.0.0.1%3A8005&address=agent1qdwgulp6q2jw93u3yhh9teectdjaxvrmmwl900cs33vz4skkawstg3q74n4\n",
- "INFO: [first_agent]: Agent inspector available at https://agentverse.ai/inspect/?uri=http%3A//127.0.0.1%3A8005&address=agent1qdwgulp6q2jw93u3yhh9teectdjaxvrmmwl900cs33vz4skkawstg3q74n4\n",
- "INFO: [first_agent]: Agent inspector available at https://agentverse.ai/inspect/?uri=http%3A//127.0.0.1%3A8005&address=agent1qdwgulp6q2jw93u3yhh9teectdjaxvrmmwl900cs33vz4skkawstg3q74n4\n",
- "INFO: [first_agent]: Agent inspector available at https://agentverse.ai/inspect/?uri=http%3A//127.0.0.1%3A8005&address=agent1qdwgulp6q2jw93u3yhh9teectdjaxvrmmwl900cs33vz4skkawstg3q74n4\n",
- "INFO: [first_agent]: Agent inspector available at https://agentverse.ai/inspect/?uri=http%3A//127.0.0.1%3A8005&address=agent1qdwgulp6q2jw93u3yhh9teectdjaxvrmmwl900cs33vz4skkawstg3q74n4\n",
- "INFO: [first_agent]: Agent inspector available at https://agentverse.ai/inspect/?uri=http%3A//127.0.0.1%3A8005&address=agent1qdwgulp6q2jw93u3yhh9teectdjaxvrmmwl900cs33vz4skkawstg3q74n4\n",
- "INFO: [first_agent]: Starting server on http://0.0.0.0:8005 (Press CTRL+C to quit)\n",
- "INFO: [first_agent]: Starting server on http://0.0.0.0:8005 (Press CTRL+C to quit)\n",
- "INFO: [first_agent]: Starting server on http://0.0.0.0:8005 (Press CTRL+C to quit)\n",
- "INFO: [first_agent]: Starting server on http://0.0.0.0:8005 (Press CTRL+C to quit)\n",
- "INFO: [first_agent]: Starting server on http://0.0.0.0:8005 (Press CTRL+C to quit)\n",
- "INFO: [first_agent]: Starting server on http://0.0.0.0:8005 (Press CTRL+C to quit)\n",
- "INFO: [first_agent]: Received message from agent1qgdefk0mewtn88dj5nu05lkwtxd3jedn9g8lw7jttrkz9c09l37lqnhs5zt: Hello from first agent\n",
- "INFO: [first_agent]: Received message from agent1qgdefk0mewtn88dj5nu05lkwtxd3jedn9g8lw7jttrkz9c09l37lqnhs5zt: Hello from first agent\n",
- "INFO: [first_agent]: Received message from agent1qgdefk0mewtn88dj5nu05lkwtxd3jedn9g8lw7jttrkz9c09l37lqnhs5zt: Hello from first agent\n",
- "INFO: [first_agent]: Received message from agent1qgdefk0mewtn88dj5nu05lkwtxd3jedn9g8lw7jttrkz9c09l37lqnhs5zt: Hello from first agent\n",
- "INFO: [first_agent]: Received message from agent1qgdefk0mewtn88dj5nu05lkwtxd3jedn9g8lw7jttrkz9c09l37lqnhs5zt: Hello from first agent\n",
- "INFO: [first_agent]: Received message from agent1qgdefk0mewtn88dj5nu05lkwtxd3jedn9g8lw7jttrkz9c09l37lqnhs5zt: Hello from first agent\n"
- ]
- }
- ],
- "source": [
- "loop.create_task(agent.run_async())"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "id": "7a62d5e8-71f4-4a11-9e7c-f37ee6777891",
- "metadata": {},
- "outputs": [],
- "source": []
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "id": "a483bc10-4861-4472-abc8-197db30a4b02",
- "metadata": {},
- "outputs": [],
- "source": []
- }
- ],
- "metadata": {
- "kernelspec": {
- "display_name": "Python 3 (ipykernel)",
- "language": "python",
- "name": "python3"
- },
- "language_info": {
- "codemirror_mode": {
- "name": "ipython",
- "version": 3
- },
- "file_extension": ".py",
- "mimetype": "text/x-python",
- "name": "python",
- "nbconvert_exporter": "python",
- "pygments_lexer": "ipython3",
- "version": "3.11.0"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 5
- }
-
-```
-
-
-
-
-
-
-## Run this file
-
-If you are using Poetry, then run:
-
-```
-poetry run jupyter notebook
-```
-
-Else, from Pip:
-
-```
-jupyter notebook
-```
-
-## Testing
-
-To test your Agent running in a Jupyter notebook, let's run the second Agent:
-
-```
-python agent.py
-```
-
-### Expected output
-
-In Jupyter:
-
-```
-INFO: [first_agent]: Registration on Almanac API successful
-INFO: [first_agent]: Registering on almanac contract...
-INFO: [first_agent]: Registering on almanac contract...complete
-ERROR: [first_agent]: Unable to resolve destination endpoint
-INFO: [first_agent]: Agent inspector available at https://agentverse.ai/inspect/?uri=http%3A//127.0.0.1%3A8005&address=agent1qdwgulp6q2jw93u3yhh9teectdjaxvrmmwl900cs33vz4skkawstg3q74n4
-INFO: [first_agent]: Starting server on http://0.0.0.0:8005 (Press CTRL+C to quit)
-INFO: [first_agent]: Received message from agent1qgdefk0mewtn88dj5nu05lkwtxd3jedn9g8lw7jttrkz9c09l37lqnhs5zt: Hello from first agent
-```
-
-From Command Line Python Agent:
-
-```
-INFO: [jupyter_test_agent]: Registration on Almanac API successful
-INFO: [jupyter_test_agent]: Registering on almanac contract...
-INFO: [jupyter_test_agent]: Registering on almanac contract...complete
-INFO: [jupyter_test_agent]: Agent inspector available at https://agentverse.ai/inspect/?uri=http%3A//127.0.0.1%3A8009&address=agent1qgdefk0mewtn88dj5nu05lkwtxd3jedn9g8lw7jttrkz9c09l37lqnhs5zt
-INFO: [jupyter_test_agent]: Starting server on http://0.0.0.0:8009 (Press CTRL+C to quit)
-```
diff --git a/pages/examples/examplestech/local-agent-langchain.mdx b/pages/examples/examplestech/local-agent-langchain.mdx
deleted file mode 100644
index ba611e09d..000000000
--- a/pages/examples/examplestech/local-agent-langchain.mdx
+++ /dev/null
@@ -1,93 +0,0 @@
-import { CodeGroup, DocsCode, GithubCodeSegment, CodeSegment } from "../../../components/code"
-
-# Locally Hosted Agent with LangChain Integration
-
-## Introduction
-
-This guide demonstrates how to run an agent on your own hardware or infrastructure, making it accessible over Agentverse and DeltaV using the Agentverse Mailroom. The example uses a locally hosted agent that utilizes LangChain's Wikipedia integration to process requests related to Wikipedia search.
-
-Please check out the example code in our [examples repo ↗️](https://github.com/fetchai/uAgent-Examples/tree/main/5-documentation/examples/intermediate/local-agent-langchain) to run this locally.
-
-### Supporting documentation
-
-- [Creating an agent ↗️](/guides/agents/create-a-uagent)
-
-- [Register in Almanac ↗️](/guides/agents/register-in-almanac)
-
-- [Almanac Contract ↗️](/references/contracts/uagents-almanac/almanac-overview)
-
-- [Protocols ↗️](/references/uagents/uagents-protocols/agent-protocols)
-
-- [Agentverse Functions ↗️](/guides/agents/intermediate/agent-functions)
-
-- [Register an Agent Function on the Agentverse ↗️](/guides/agentverse/agentverse-functions/registering-agent-services)
-
-- [Options for running your local agents ↗️](/guides/agents/intermediate/options-for-running-local-agents)
-
-### The agent
-
-
-
-
-
-
-
- ```py copy filename="agent.py"
-
- from langchain_community.tools import WikipediaQueryRun
- from langchain_community.utilities import WikipediaAPIWrapper
- from uagents.setup import fund_agent_if_low
- from uagents import Agent, Context, Protocol, Model
- from uagents import Field
- from ai_engine import UAgentResponse, UAgentResponseType
-
- # Extend your protocol with Wikipedia data fetching
- class WikiReq(Model):
- search_keyword: str = Field(description="This describes the keyword you want to search on wiki")
-
- SEED_PHRASE = ""
-
- # Copy the address shown below
- print(f"Your agent's address is: {Agent(seed=SEED_PHRASE).address}")
-
- # Now your agent is ready to join the agentverse!
- WikiAgent = Agent(
- name="Wiki Agent",
- seed=SEED_PHRASE,
- mailbox=True
- )
-
- fund_agent_if_low(WikiAgent.wallet.address()) #funding agent.
- wiki_protocol = Protocol("Wiki Protocol")
-
- @wiki_protocol.on_message(model=WikiReq, replies={UAgentResponse})
- async def load_dalle(ctx: Context, sender: str, msg: WikiReq):
- wikipedia = WikipediaQueryRun(api_wrapper=WikipediaAPIWrapper())
- ctx.logger.info(msg.search_keyword)
- try:
- result = wikipedia.run(msg.search_keyword)
- except Exception as e:
- ctx.logger.info(f"Error generating response: {e}")
- # Send an error response back to the user
- await ctx.send(
- sender, UAgentResponse(message=str(result), type=UAgentResponseType.FINAL)
- )
-
- WikiAgent.include(wiki_protocol, publish_manifest=True)
- WikiAgent.run()
-
- ```
-
-
-
-
-
-
-### Register Agent Function
-
-Head to this [guide ↗️](/guides/agentverse/agentverse-functions/registering-agent-services) for a detailed overview of the registration process of Agent Functions on the Agentverse.
diff --git a/pages/examples/examplestech/postgres-database-with-an-agent.mdx b/pages/examples/examplestech/postgres-database-with-an-agent.mdx
deleted file mode 100644
index b8ca165e4..000000000
--- a/pages/examples/examplestech/postgres-database-with-an-agent.mdx
+++ /dev/null
@@ -1,422 +0,0 @@
-import { CodeGroup, DocsCode } from "../../../components/code"
-
-# Utilize the PostgreSQL database with the Agent
-
-## Introduction
-
-In this documentation example, we demonstrate how to use the uAgent library to create agents that interact with PostgreSQL data within a Docker Compose setup. In this scenario, one agent handles the insertion of employee data into the PostgreSQL database, while another agent retrieves this data. This example illustrates the seamless integration between agents, PostgreSQL, and Docker, showcasing how to manage data flow and communication in a distributed system.
-
-Please check out the example code in our [examples repo ↗️](https://github.com/fetchai/uAgent-Examples/tree/main/3-applications/postgres-database) to run this locally.
-
-### Supporting Documents
-
- - [Almanac contract overview ↗️](../../references/contracts/uagents-almanac/almanac-overview).
- - [How to create an agent ↗️](../../guides/agents/create-a-uagent).
- - [Registering in the Almanac Contract ↗️](../../guides/agents/register-in-almanac).
- - [Creating an interval task ↗️](/guides/agents/interval-task)
- - [Communicating with other agents ↗️](/guides/agents/communicating-with-other-agents)
-
-## Pre-requisites
-
-- **Python:** Download and install from [Python official website ↗️](https://www.python.org/downloads/).
-- **Poetry:** Install by following the instructions on [Poetry's official website ↗️](https://python-poetry.org/docs/#installation).
-- **Docker:** Download and install from [Docker official website ↗️](https://docs.docker.com/get-docker/).
-- **Docker Compose:** Download and install from [Docker Compose official documentation ↗️](https://docs.docker.com/compose/).
-
-## Project Structure
-
-```
-.postgres-database-with-an-agent
-├── docker-compose.yml
-├── Dockerfile
-├── README.md
-└── src
- ├── constants.py
- ├── db
- │ ├── db_connection.py
- │ ├── __init__.py
- │ ├── models
- │ │ └── models.py
- │ └── schemas
- │ └── employees.sql
- └── main.py
-```
-
-## Agent with PostgreSQL database
-
-### Set up the PostgreSQL connection with Docker using Docker Compose
-
-This section details the files involved in setting up the PostgreSQL connection within your project.
-
-**`db_connection.py`**: Contains the functions to establish and close the connection to the PostgreSQL database using the psycopg2 library. The `create_connection` function connects to the database with provided credentials, while the `close_connection` function ensures the connection is safely terminated.
-
-```py copy filename="db_connection.py"
-import psycopg2
-from psycopg2 import OperationalError
-
-def create_connection(dbname, user, password, host="localhost", port="5432"):
- """
- Create a connection to the PostgreSQL database.
-
- :param dbname: Name of the database
- :param user: Database user
- :param password: User's password
- :param host: Database host
- :param port: Database port
- :return: Connection object or None if connection fails
- """
- try:
- conn = psycopg2.connect(
- dbname=dbname, user=user, password=password, host=host, port=port
- )
- print("Connection successful")
- return conn
- except OperationalError as error:
- print(f"Error connecting to PostgreSQL database: {error}")
- return None
-
-def close_connection(conn):
- if conn:
- conn.close()
- print("Connection closed")
-```
-
-**`docker-compose.yml`**: Configures the Docker services, including the PostgreSQL database and the application. It defines the environment variables for the database connection and maps the database schema from the host to the container.
-
-```yml copy
-version: "3.8"
-services:
- db:
- container_name: postgres_container
- image: postgres
- restart: always
- environment:
- POSTGRES_USER: ${DB_USER}
- POSTGRES_PASSWORD: ${DB_PASSWORD}
- POSTGRES_DB: ${DB_NAME}
- volumes:
- - "postgres:/var/lib/postgresql/data"
- - ./src/db/schemas/employees.sql:/docker-entrypoint-initdb.d/employees.sql
- ports:
- - "5432:5432"
- networks:
- - agent_network
- app:
- build: .
- container_name: poetry_app
- volumes:
- - .:/app
- ports:
- - "8000:8000"
- depends_on:
- - db
- networks:
- - agent_network
- environment:
- DB_USER: ${DB_USER}
- DB_PASSWORD: ${DB_PASSWORD}
- DB_NAME: ${DB_NAME}
- command: poetry run python ./src/main.py
-
-volumes:
- postgres:
-
-networks:
- agent_network:
- driver: bridge
-```
-
-**`Dockerfile`**: Builds the application container, installing dependencies via Poetry and setting up the environment to run the application. The container exposes port 8000 for the application service.
-
-```docker copy
-FROM python:3.12-slim
-ENV PATH="$PATH:/root/.local/bin"
-
-RUN apt-get update && \
- apt-get install -y curl gcc && \
- curl -sSL https://install.python-poetry.org/ | python3 -
-
-WORKDIR /app
-ADD pyproject.toml poetry.lock /app/
-RUN poetry install
-ADD . /app
-EXPOSE 8000
-
-ENTRYPOINT ["poetry", "run"]
-CMD ["python", "main.py"]
-```
-
-### Defining the Employees Database Schema and Model
-
-The `Employees` class defines a model representing employee data as a dictionary. The `GetEmployees` class represents a model used to request employee information, with a flag indicating whether a response is expected.
-
-The `employees.sql` script defines a schema for an Employees table in a PostgreSQL database, if it doesn't already exist. This table includes columns for employee ID, first name, last name, birth date, and salary.
-
-```py copy filename="models.py"
-from uagents import Model
-
-class Employees(Model):
- employees_data: dict
-
-class GetEmployees(Model):
- reply_back: bool
-```
-
-```query copy filename="employees.sql"
-CREATE TABLE IF NOT EXISTS Employees (
- EmployeeID INT PRIMARY KEY,
- FirstName VARCHAR(50),
- LastName VARCHAR(50),
- BirthDate DATE,
- Salary DECIMAL(10, 2)
-);
-```
-
-### Postgres data with agent
-
-This script sets up and runs two agents, `db_insert_agent` and `db_fetch_agent`, which interact with a PostgreSQL database to manage employee data. The agents use asynchronous event handling to fetch and insert employee information into the database.
-
-#### Database Connection
-
-- The `create_connection` function is used to establish a connection to the PostgreSQL database using parameters defined in `db_params`.
-
-#### Agents
-
-- **`db_insert_agent`**: Responsible for inserting employee data into the database.
-- **`db_fetch_agent`**: Responsible for fetching and reporting employee data from the database.
-
-#### Event Handlers
-
-- **`on_startup` (db_fetch_agent)**:
- - Triggered when `db_fetch_agent` starts.
- - Retrieves and logs the PostgreSQL database version.
- - Sends employee data to `db_insert_agent` if the version retrieval is successful.
-
-- **`handle_employee_data` (db_insert_agent)**:
- - Handles messages with employee data.
- - Inserts the received employee data into the `Employees` table in the database.
-
-- **`fetch_all_employee_details` (db_fetch_agent)**:
- - Handles messages requesting all employee details.
- - Retrieves all employee records from the `Employees` table and logs the data.
-
-#### Database Operations
-
-- **Fetching Database Version**: Uses the query `SELECT version();` to get the PostgreSQL version.
-- **Inserting Employee Data**: Executes an `INSERT` query to add employee records to the `Employees` table.
-- **Fetching Employee Details**: Executes a `SELECT * FROM Employees` query to retrieve all employee records.
-
-#### Execution
-
-- Initializes a `Bureau` instance.
-- Adds both agents (`db_insert_agent` and `db_fetch_agent`) to the bureau.
-- Runs the bureau, which starts the agents and their event handlers.
-
-#### Usage
-
-1. **Startup**: On startup, `db_fetch_agent` will log the database version and send employee data to `db_insert_agent`.
-2. **Inserting Data**: `db_insert_agent` will insert received employee data into the database.
-3. **Fetching Data**: `db_fetch_agent` will fetch and log all employee details upon request.
-
-
-
-
-```py copy filename="main.py"
-from db.db_connection import create_connection
-from uagents import Agent, Context, Bureau
-from db.models.models import Employees, GetEmployees
-from constants import employees_data
-from constants import db_params, DB_FETCH_AGENT_ADDRESS
-
-def get_db_version():
- """
- Retrieves the PostgreSQL database version.
-
- :return: Database version string or None if retrieval fails
- """
- conn = create_connection(**db_params)
- if conn:
- try:
- cursor = conn.cursor()
- cursor.execute("SELECT version();")
- db_version = cursor.fetchone()
- cursor.close()
- return db_version
- except Exception as error:
- print(f"Error executing query: {error}")
- return None
-
-db_insert_agent = Agent(name="db_inserter", seed="db_inserter_seed_phrase")
-db_fetch_agent = Agent(name="db_fetcher", seed="db_fetcher_seed_phrase")
-
-DB_FETCH_AGENT_ADDRESS = DB_FETCH_AGENT_ADDRESS
-
-@db_fetch_agent.on_event("startup")
-async def on_startup(ctx: Context):
- """
- Event handler triggered on agent startup to fetch database version and send employee data.
-
- :param ctx: Context object for handling agent events
- """
- db_version = get_db_version()
- if db_version:
- ctx.logger.info(
- f"Hello, I'm agent {db_insert_agent.name} and my address is {db_insert_agent.address}. PostgreSQL database version: {db_version[0]}"
- )
- await ctx.send(DB_FETCH_AGENT_ADDRESS, Employees(employees_data=employees_data))
- else:
- ctx.logger.info(
- f"Hello, I'm agent {db_insert_agent.name} and my address is {db_insert_agent.address}. Could not retrieve the database version."
- )
-
-@db_insert_agent.on_message(model=Employees, replies=GetEmployees)
-async def handle_employee_data(ctx: Context, sender: str, msg: Employees):
- """
- Handler for inserting employee data into the database.
-
- :param ctx: Context object for handling agent events
- :param sender: Sender of the message
- :param msg: Message containing employee data
- """
- ctx.logger.info(f"Received request from {sender} {msg.dict()}")
- employee_data = msg.employees_data
- conn = create_connection(**db_params)
- if conn:
- try:
- cursor = conn.cursor()
- insert_query = """
- INSERT INTO Employees (EmployeeID, FirstName, LastName, BirthDate, Salary)
- VALUES (%s, %s, %s, TO_DATE(%s, 'DD-MM-YYYY'), %s)
- """
- cursor.execute(
- insert_query,
- (
- employee_data["EmployeeID"],
- employee_data["FirstName"],
- employee_data["LastName"],
- employee_data["BirthDate"],
- employee_data["Salary"],
- ),
- )
- REPLY_BACK = True
- conn.commit()
- cursor.close()
- ctx.logger.info(f"Inserted employee data: {employee_data}")
- await ctx.send(sender, GetEmployees(reply_back=REPLY_BACK))
- except Exception as error:
- ctx.logger.error(f"Error inserting employee data: {error}")
- else:
- ctx.logger.error("Could not connect to the database.")
-
-@db_fetch_agent.on_message(model=GetEmployees)
-async def fetch_all_employee_details(ctx: Context, sender: str, msg: GetEmployees):
- """
- Handler for fetching all employee details from the database.
-
- :param ctx: Context object for handling agent events
- :param sender: Sender of the message
- :param msg: Message triggering the fetch operation
- """
- if msg.reply_back:
- conn = create_connection(**db_params)
- if conn:
- try:
- cursor = conn.cursor()
- query = "SELECT * FROM Employees"
- cursor.execute(query)
- all_employees = cursor.fetchall()
- cursor.close()
-
- employees_list = []
- for employee in all_employees:
- employee_info = {
- "EmployeeID": employee[0],
- "FirstName": employee[1],
- "LastName": employee[2],
- "BirthDate": employee[3].strftime("%d-%m-%Y"),
- "Salary": employee[4],
- }
- employees_list.append(employee_info)
- ctx.logger.info(f"Retrieved all employee data: {employees_list}")
- except Exception as error:
- ctx.logger.error(f"Error retrieving employee data: {error}")
- else:
- ctx.logger.error("Could not connect to the database.")
-
-bureau = Bureau()
-bureau.add(db_insert_agent)
-bureau.add(db_fetch_agent)
-
-if __name__ == "__main__":
- bureau.run()
-
-```
-
-
-
-This constant file initializes a dictionary for storing employee data and configures the database connection parameters using environment variables. It also defines a constant for the address of the database fetch agent.
-
-```py copy filename="constants.py"
-import os
-
-employees_data = {
- "EmployeeID": "",
- "FirstName": "",
- "LastName": "",
- "BirthDate": "",
- "Salary": 0,
-}
-
-db_params = {
- "dbname": os.getenv("DB_NAME"),
- "user": os.getenv("DB_USER"),
- "password": os.getenv("DB_PASSWORD"),
- "host": "db",
- "port": "5432",
-}
-
-DB_FETCH_AGENT_ADDRESS = (
- "agent1qwg0h3gx2kvqmwadlg0j4r258r7amcfskx2mudz92ztjmtfdclygxrh5esu"
-)
-
-```
-
-## Poetry Dependencies
-
-```pyproject.toml copy filename="pyproject.toml"
-[tool.poetry.dependencies]
-python = "^3.10"
-psycopg2-binary = "^2.9.9"
-uagents = { version = "^0.13.0", python = ">=3.10,<3.13" }
-```
-
-## How to Run This Example
-
-#### Update the Required environment variables
-
-```env copy filename=".env.example"
-DB_USER=
-DB_PASSWORD=
-DB_NAME=
-```
-
-#### Instructions to execute the example.
-
-- Navigate to the root Folder of Example.
-- Update the constant file with new entries to store in the database
-- Run `docker-compose build`
-- Run `docker-compose up`
-
-## Expected Output
-
-```
-poetry_app | Connection successful
-poetry_app | INFO: [db_fetcher]: Hello, I'm agent db_inserter and my address is agent1qwg0h3gx2kvqmwadlg0j4r258r7amcfskx2mudz92ztjmtfdclygxrh5esu. PostgreSQL database version: PostgreSQL 16.3 (Debian 16.3-1.pgdg120+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 12.2.0-14) 12.2.0, 64-bit
-poetry_app | INFO: [db_inserter]: Received request from agent1qv470qn3vfgn3dwe5z90m8u6qvtn6chrgm4urfzdg2v9qyagln6sgnh4wwg {'employees_data': {'EmployeeID': '0', 'FirstName': 'john', 'LastName': 'wick', 'BirthDate': '29-08-1999', 'Salary': 50000}}
-poetry_app | Connection successful
-poetry_app | INFO: [db_inserter]: Inserted employee data: {'EmployeeID': '0', 'FirstName': 'john', 'LastName': 'wick', 'BirthDate': '29-08-1999', 'Salary': 50000}
-poetry_app | Connection successful
-poetry_app | INFO: [db_fetcher]: Retrieved all employee data: [{'EmployeeID': 0, 'FirstName': 'john', 'LastName': 'wick', 'BirthDate': '29-08-1999', 'Salary': Decimal('50000.00')}]
-poetry_app | INFO: [bureau]: Starting server on http://0.0.0.0:8000 (Press CTRL+C to quit)
-```
-
diff --git a/pages/examples/examplestech/react-example.mdx b/pages/examples/examplestech/react-example.mdx
deleted file mode 100644
index 5893aa0e5..000000000
--- a/pages/examples/examplestech/react-example.mdx
+++ /dev/null
@@ -1,944 +0,0 @@
-import { Callout } from 'nextra/components'
-import { CodeGroup, DocsCode } from "../../../components/code"
-
-# React app with agents 'on_query' decorator
-
-## Introduction
-
-This example shows how to build a React application integrated with a flask backend, using various Agents to perform tasks such as fetching news, scrapping webpage data and also getting the sentiment of news using hugging face FinBERT model of [HF inference API ↗️](https://huggingface.co/docs/api-inference/en/index).
-
-Please check out the example code in our [examples repo ↗️](https://github.com/fetchai/uAgent-Examples/tree/main/3-applications/react-web-with-flask-and-agents) to run this locally.
-
-### Supporting Documents
-
- - [How to use on_query decorator ↗️](../../guides/agents/intermediate/handlers).
- - [How to create an Agent ↗️](../../guides/agents/create-a-uagent).
- - [Registering in the Almanac Contract ↗️](../../guides/agents/register-in-almanac).
- - [Almanac contract overview ↗️](../../references/contracts/uagents-almanac/almanac-overview).
-
-## Pre-requisites
-
- - **Node.js :** Download and install from [Node.js official website ↗️](https://nodejs.org/en).
- - **Python :** Download and install from [Python official website ↗️](https://www.python.org/downloads/).
- - **Flask :** Install via pip
-
- ```
- pip install Flask flask-cors
- ```
-
- - **React :** Setup a news project
-
- ```
- npx create-react-app finbert-news-sentiment-analysis
- cd finbert-news-sentiment-analysis
- npm start
- ```
-
-## Project Structure
-
-Outline of basic structure of the project:
-
- ```
- finbert-news-sentiment-analysis/
- ├── frontend/
- │ ├── public/
- │ │ └── index.html
- │ ├── src/
- │ │ ├── components/
- │ │ │ ├── NewsFeed.jsx
- │ │ │ ├── SearchComponent.jsx
- │ │ │ └── SearchComponent.css
- │ │ ├── app.css
- │ │ └── index.js
- │ ├── package.json
- │ └── package-lock.json
- │
- ├── backend/
- │ ├── app.py # Flask application
- │ ├── requirements.txt
- │ └── agents/
- │ ├── news_agent.py # Handles fetching news
- │ ├── scraper_agent.py # Handles URL extraction
- │ └── sentiment_agent.py # Handles sentiment analysis
- │
- └── README.md # Project documentation
-
- ```
-
-## Backend Setup
-
-In this section we will set up Agents and as well as flask app which will respond to different endpoints.
-
-1. Flask Application ('app.py'):
-
- - Define routes for fetching news_urls, scrapping news content and get FinBERT sentiments.
- - Utilize Agents to handle specific tasks.
-
- ```python copy filename="app.py"
- from flask import Flask
- from flask_cors import CORS
- from uagents.query import query
- from uagents import Model
- import json
-
- # Define Request Data Model classes for interacting with different agents
- class NewsRequest(Model):
- company_name: str
-
- class UrlRequest(Model):
- company_name: str
-
- class wrapRequest(Model):
- url : str
-
- class SentimentRequest(Model):
- news : str
-
- # Initialize Flask application
- app = Flask(__name__)
- CORS(app) # Enables CORS for all domains on all routes
-
- # Define agent addresses
- news_agent_address = "agent1q2e9kfdrxfa5dxn6zeyw47287ca36cdur9xevhmdzzfmf4cwlmahv73mpev"
- news_content_agent_address = "agent1qvumqq9xju7musr82l6ulqsvgka7d7z77jvvdrkyyr7n5s0u0lfdvse6k4t"
- sentiment_agent_address = "agent1q2pm392d2uux3wjsydatd4zhagrtq0lrwfgw4s8pv4x0090sfzk9qpgztaz"
-
- @app.route('/')
- def home():
- return "Welcome to the Company Analyzer API!"
-
- # Define an asynchronous endpoint to get news for a given company
- @app.route('/api/news/', methods=['GET'])
- async def get_news(company_name):
- response = await query(destination=news_agent_address, message=NewsRequest(company_name=company_name), timeout=15.0)
- data = json.loads(response.decode_payload())
- print(data)
- return data["news_list"]
-
- # Define an asynchronous endpoint to analyse sentiment for a given company
- @app.route('/api/sentiment/', methods=['GET'])
- async def get_sentiment(company_name):
- urls = await query(destination=news_agent_address, message=UrlRequest(company_name=company_name), timeout=15.0)
- data = json.loads(urls.decode_payload())
- sentiments = []
- content_list = []
- sentiment_scores = {}
- url_list = data.get("url_list", [])
-
- # For each URL, query for content and perform sentiment analysis
- for url in url_list:
- content = await query(destination=news_content_agent_address, message=wrapRequest(url=url), timeout=15.0)
- news_summary = json.loads(content.decode_payload())
- summary_text = news_summary.get('summary', '')
- cleaned_text = summary_text.replace('\u00a0', ' ')
- if len(cleaned_text) > 100:
- content_list.append(cleaned_text)
- for content in content_list:
- sentiment = await query(destination=sentiment_agent_address, message=SentimentRequest(news=content), timeout=15.0)
- data = json.loads(sentiment.decode_payload())
- sentiment = data.get("sentiment", [])
- sentiments.append(sentiment)
- for sentiment in sentiments:
- label,score = sentiment.split(',')
- score = float(score)
- if label in sentiment_scores:
- sentiment_scores[label].append(score)
- else:
- sentiment_scores[label] = [score]
- sentiment_means = {label: sum(scores) / len(scores) for label, scores in sentiment_scores.items() if scores}
-
- # Calculate average sentiment scores and determine the predominant sentiment
- if sentiment_means:
- max_sentiment = max(sentiment_means, key=sentiment_means.get)
- final_sentiment = str(max_sentiment) + ' : ' +str(round(sentiment_means[max_sentiment],2))
- return final_sentiment
- else:
- return None, None
-
- # Start the Flask application in debug mode
- if __name__ == '__main__':
- app.run(debug=True)
- ```
-
-2. Agents:
-
- - **News and URL agent:** Fetches news articles titles and url for them as well.
-
-
-
-
-
- ```python copy filename="news_agent.py"
- # Import Required libraries
- import requests
- import os
- from uagents import Agent, Context, Model
- from uagents.setup import fund_agent_if_low
-
- # Define Request and Response Models
- class NewsRequest(Model):
- company_name: str
-
- class UrlRequest(Model):
- company_name: str
-
- class NewsResponse(Model):
- news_list : list
-
- class UrlResponse(Model):
- url_list: list
-
- class ErrorResponse(Model):
- error : str
-
- ALPHA_VANTAGE_API_KEY = os.getenv('ALPHA_VANTAGE_API_KEY')
- GNEWS_API_KEY = os.getenv('GNEWS_API_KEY')
-
- # Define function to get ticker symbol for given company name
- async def fetch_symbol(company_name):
- url = f"https://www.alphavantage.co/query?function=SYMBOL_SEARCH&keywords={company_name}&apikey={ALPHA_VANTAGE_API_KEY}"
- response = requests.get(url)
- if response.status_code == 200:
- data = response.json()
- # Typically, the best match will be the first item in the bestMatches list
- if data.get('bestMatches') and len(data['bestMatches']) > 0:
- Symbol = data['bestMatches'][0]['1. symbol'] # Return the symbol of the best match
- return Symbol
- else:
- return 'No Symbol found'
- else:
- return 'No Symbol found'
-
- async def fetch_news(company_name): # get news urls and description for the given news company or ticker
- url = f"https://gnews.io/api/v4/search?q={company_name}&token={GNEWS_API_KEY}&lang=en"
- response = requests.get(url)
- articles = response.json().get('articles', [])
- # Return a list of titles and descriptions with hyperlinks
- news_list = []
- for article in articles:
- article_url = article.get('url', 'No url')
- description = article.get("description", "No Description")
- # Create a hyperlink using HTML anchor tag
- hyperlink = {"url": article_url,
- "title": description}
- news_list.append(hyperlink)
- return news_list
-
- async def fetch_url(company_name): # Get the news url's for given company name or symbol
- url = f"https://gnews.io/api/v4/search?q={company_name}&token={GNEWS_API_KEY}&lang=en"
- response = requests.get(url)
- articles = response.json().get('articles', [])
- # Return a list of titles and descriptions with hyperlinks
- url_list = []
- for article in articles:
- article_url = article.get('url', 'No url')
- url_list.append(article_url)
- return url_list
-
- # Define News Agent
- NewsAgent = Agent(
- name="NewsAgent",
- port=8000,
- seed="News Agent secret phrase",
- endpoint=["http://127.0.0.1:8000/submit"],
- )
-
- # Registering agent on Almanac and funding it.
- fund_agent_if_low(NewsAgent.wallet.address())
-
- # On agent startup printing address
- @NewsAgent.on_event('startup')
- async def agent_details(ctx: Context):
- ctx.logger.info(f'Search Agent Address is {NewsAgent.address}')
-
- # On_query handler for news request
- @NewsAgent.on_query(model=NewsRequest, replies={NewsResponse})
- async def query_handler(ctx: Context, sender: str, msg: NewsRequest):
- try:
- ctx.logger.info(f'Fetching news details for company_name: {msg.company_name}')
- symbol = await fetch_symbol(msg.company_name)
- ctx.logger.info(f' Symbol for company provided is {symbol}')
- if symbol != None: #if company symbol fetch successfully getting news using ticker symbol else using the company name itself.
- news_list = await fetch_news(symbol)
- else:
- news_list = await fetch_news(msg.company_name)
- ctx.logger.info(str(news_list))
- await ctx.send(sender, NewsResponse(news_list=news_list))
-
- except Exception as e:
- error_message = f"Error fetching job details: {str(e)}"
- ctx.logger.error(error_message)
- # Ensure the error message is sent as a string
- await ctx.send(sender, ErrorResponse(error=str(error_message)))
-
- # On_query handler for news_url request
- @NewsAgent.on_query(model=UrlRequest, replies={UrlResponse})
- async def query_handler(ctx: Context, sender: str, msg: UrlRequest):
- try:
- ctx.logger.info(f'Fetching news url details for company_name: {msg.company_name}')
- symbol = await fetch_symbol(msg.company_name)
- ctx.logger.info(f' Symbol for company provided is {symbol}')
- if symbol != None:
- url_list = await fetch_url(symbol)
- else:
- url_list = await fetch_url(msg.company_name)
- ctx.logger.info(str(url_list))
- await ctx.send(sender, UrlResponse(url_list=url_list))
- except Exception as e:
- error_message = f"Error fetching job details: {str(e)}"
- ctx.logger.error(error_message)
- # Ensure the error message is sent as a string
- await ctx.send(sender, ErrorResponse(error=str(error_message)))
-
- if __name__ == "__main__":
- NewsAgent.run()
- ```
-
-
-
- ```python copy filename="news_agent.py"
- # Import Required libraries
- import requests
- from uagents import Agent, Context, Model
-
- # Define Request and Response Models
- class NewsRequest(Model):
- company_name: str
-
- class UrlRequest(Model):
- company_name: str
-
- class NewsResponse(Model):
- news_list : list
-
- class UrlResponse(Model):
- url_list: list
-
- class ErrorResponse(Model):
- error : str
-
- ALPHA_VANTAGE_API_KEY = "YOUR_ALPHA_VANTAGE_API_KEY"
- GNEWS_API_KEY = "YOUR_GNEWS_API_KEY"
-
- # Define function to get ticker symbol for given company name
- async def fetch_symbol(company_name):
- url = f"https://www.alphavantage.co/query?function=SYMBOL_SEARCH&keywords={company_name}&apikey={ALPHA_VANTAGE_API_KEY}"
- response = requests.get(url)
- if response.status_code == 200:
- data = response.json()
- # Typically, the best match will be the first item in the bestMatches list
- if data.get('bestMatches') and len(data['bestMatches']) > 0:
- Symbol = data['bestMatches'][0]['1. symbol'] # Return the symbol of the best match
- return Symbol
- else:
- return 'No Symbol found'
- else:
- return 'No Symbol found'
-
- async def fetch_news(company_name): # get news urls and description for the given news company or ticker
- url = f"https://gnews.io/api/v4/search?q={company_name}&token={GNEWS_API_KEY}&lang=en"
- response = requests.get(url)
- articles = response.json().get('articles', [])
- # Return a list of titles and descriptions with hyperlinks
- news_list = []
- for article in articles:
- article_url = article.get('url', 'No url')
- description = article.get("description", "No Description")
- # Create a hyperlink using HTML anchor tag
- hyperlink = {"url": article_url,
- "title": description}
- news_list.append(hyperlink)
- return news_list
-
- async def fetch_url(company_name): # Get the news url's for given company name or symbol
- url = f"https://gnews.io/api/v4/search?q={company_name}&token={GNEWS_API_KEY}&lang=en"
- response = requests.get(url)
- articles = response.json().get('articles', [])
- # Return a list of titles and descriptions with hyperlinks
- url_list = []
- for article in articles:
- article_url = article.get('url', 'No url')
- url_list.append(article_url)
- return url_list
-
- # On agent startup printing address
- @agent.on_event('startup')
- async def agent_details(ctx: Context):
- ctx.logger.info(f'Search Agent Address is {NewsAgent.address}')
-
- # On_query handler for news request
- @agent.on_query(model=NewsRequest, replies={NewsResponse})
- async def query_handler(ctx: Context, sender: str, msg: NewsRequest):
- try:
- ctx.logger.info(f'Fetching news details for company_name: {msg.company_name}')
- symbol = await fetch_symbol(msg.company_name)
- ctx.logger.info(f' Symbol for company provided is {symbol}')
- if symbol != None: #if company symbol fetch successfully getting news using ticker symbol else using the company name itself.
- news_list = await fetch_news(symbol)
- else:
- news_list = await fetch_news(msg.company_name)
- ctx.logger.info(str(news_list))
- await ctx.send(sender, NewsResponse(news_list=news_list))
-
- except Exception as e:
- error_message = f"Error fetching job details: {str(e)}"
- ctx.logger.error(error_message)
- # Ensure the error message is sent as a string
- await ctx.send(sender, ErrorResponse(error=str(error_message)))
-
- # On_query handler for news_url request
- @agent.on_query(model=UrlRequest, replies={UrlResponse})
- async def query_handler(ctx: Context, sender: str, msg: UrlRequest):
- try:
- ctx.logger.info(f'Fetching news url details for company_name: {msg.company_name}')
- symbol = await fetch_symbol(msg.company_name)
- ctx.logger.info(f' Symbol for company provided is {symbol}')
- if symbol != None:
- url_list = await fetch_url(symbol)
- else:
- url_list = await fetch_url(msg.company_name)
- ctx.logger.info(str(url_list))
- await ctx.send(sender, UrlResponse(url_list=url_list))
- except Exception as e:
- error_message = f"Error fetching job details: {str(e)}"
- ctx.logger.error(error_message)
- # Ensure the error message is sent as a string
- await ctx.send(sender, ErrorResponse(error=str(error_message)))
- ```
-
-
-
-
- Get your [Alphavantage ↗️](https://www.alphavantage.co/) and [Gnews ↗️](https://gnews.io/) API keys and update it in the virtual environment.
-
-
- - **WebScraper Agent:** Scraps the webpage content for the given URL.
-
-
-
- ```python copy filename="webscraper_agent.py"
- # Import Required libraries
- import requests
- import aiohttp
- from uagents import Agent, Context, Model
- from uagents.setup import fund_agent_if_low
- from bs4 import BeautifulSoup
- import time
-
- # Define data Models to handle request
- class wrapRequest(Model):
- url : str
-
- class Message(Model):
- message : str
-
- class wrapResponse(Model):
- summary : str
-
- class ErrorResponse(Model):
- error : str
-
- # Define webscraper Agent
- webScraperAgent = Agent(
- name="Web Scraper Agent",
- port=8001,
- seed="Web Scraper Agent secret phrase",
- endpoint=["http://127.0.0.1:8001/submit"],
- )
-
- # Define function to scrap webpage and get paragraph content.
- async def get_webpage_content(url):
- try:
- async with aiohttp.ClientSession() as session:
- async with session.get(url) as response:
- if response.status == 200:
- response_text = await response.text()
- soup = BeautifulSoup(response_text, 'html.parser')
-
- for script_or_style in soup(["script", "style", "header", "footer", "nav", "aside"]):
- script_or_style.decompose()
-
- text_blocks = soup.find_all('p')
- text_content = ' '.join(block.get_text(strip=True) for block in text_blocks if block.get_text(strip=True))
-
- words = text_content.split()
- limited_text = ' '.join(words[:500]) # Limit to first 500 words for faster response of sentiment agent.
- return limited_text
- else:
- return "Error: Unable to fetch content."
- except Exception as e:
- return f"Error encountered: {str(e)}"
-
- # On agent startup printing address
- @webScraperAgent.on_event('startup')
- async def agent_details(ctx: Context):
- ctx.logger.info(f'Search Agent Address is {webScraperAgent.address}')
-
- # On_query handler to handle webpage wrapping
- @webScraperAgent.on_query(model=wrapRequest, replies={wrapResponse})
- async def query_handler(ctx: Context, sender: str, msg: wrapRequest):
- try:
- ctx.logger.info(f'URL wrapper for request : {msg.url}')
- news_content = await get_webpage_content(msg.url)
- ctx.logger.info(news_content)
- if "Error" not in news_content:
- await ctx.send(sender, wrapResponse(summary = news_content))
- else:
- await ctx.send(sender, ErrorResponse(error = "ERROR" + news_content))
- except Exception as e:
- error_message = f"Error fetching job details: {str(e)}"
- ctx.logger.error(error_message)
- # Ensure the error message is sent as a string
- await ctx.send(sender, ErrorResponse(error=str(error_message)))
-
- if __name__ == "__main__":
- webScraperAgent.run()
- ```
-
-
-
- - **Sentiment Agent:** Provides sentiment of news content provided using HF API and FinBERT model.
-
-
-
- ```python copy filename="sentiment_agent.py"
- # Import Required libraries
- import requests
- from uagents import Agent, Context, Model
- from uagents.setup import fund_agent_if_low
- import time
- import asyncio
- import aiohttp
- import json
-
- # Define Request and Response Data Models
- class SentimentRequest(Model):
- news : str
-
- class SentimentResponse(Model):
- sentiment : str
-
- class ErrorResponse(Model):
- error : str
-
- # Define Sentiment analysis Agent
- SentimentAgent = Agent(
- name="Sentiment Agent",
- port=8002,
- seed="Sentiment Agent secret phrase",
- endpoint=["http://127.0.0.1:8002/submit"],
- )
-
- # Registering agent on Almanac and funding it.
- fund_agent_if_low(SentimentAgent.wallet.address())
-
- # Define function to provide sentiment for given content
- async def sentiment_analysis(news):
- API_URL = "https://api-inference.huggingface.co/models/ProsusAI/finbert"
- headers = {"Authorization": "Bearer "}
-
- payload = {"inputs": news}
-
- async with aiohttp.ClientSession() as session:
- async with session.post(API_URL, headers=headers, json=payload) as response:
- if response.status == 200:
- sentiments = await response.json()
- await asyncio.sleep(5) # Proper async sleep
- # Flatten the list of dicts to a single list
- flattened_sentiments = [item for sublist in sentiments for item in sublist]
- max_sentiment = max(flattened_sentiments, key=lambda s: s['score'])
- max_label = str(max_sentiment['label'])
- max_score = str(round(max_sentiment['score'], 3))
- return f"{max_label},{max_score}"
- else:
- return "Error: Failed to fetch data from API"
-
- # On agent startup printing address
- @SentimentAgent.on_event('startup')
- async def agent_details(ctx: Context):
- ctx.logger.info(f'Search Agent Address is {SentimentAgent.address}')
-
- # On_query handler for processing sentiment request
- @SentimentAgent.on_query(model=SentimentRequest, replies={SentimentResponse})
- async def query_handler(ctx: Context, sender: str, msg: SentimentRequest):
- try:
- sentiment = await sentiment_analysis(msg.news)
- if sentiment == "Error: Failed to fetch data from API":
- sentiment = await sentiment_analysis(msg.news[:500]) # if model is not ale to perform sentiment request we will just take string with 500 characters
- ctx.logger.info(msg.news[:300])
- ctx.logger.info(sentiment)
- await ctx.send(sender, SentimentResponse(sentiment = sentiment))
- except Exception as e:
- error_message = f"Error fetching job details: {str(e)}"
- ctx.logger.error(error_message)
- # Ensure the error message is sent as a string
- await ctx.send(sender, ErrorResponse(error=str(error_message)))
-
- if __name__ == "__main__":
- SentimentAgent.run()
- ```
-
-
-
-
- Get your [Hugging Face Inference API ↗️](https://huggingface.co/docs/api-inference/en/index).
-
-
-3. requirements.txt:
-
- ```
- aiohttp==3.9.5
- aiosignal==1.3.1
- beautifulsoup4==4.12.3
- bs4==0.0.2
- cosmpy==0.9.2
- grpcio==1.63.0
- jsonschema==4.22.0
- msgpack==1.0.8
- multidict==6.0.5
- packaging==24.0
- requests==2.31.0
- uagents==0.11.1
- urllib3==2.2.1
- uvicorn==0.20.0
- websockets==10.4
- yarl==1.9.4
- ```
-
- - Activate virtual environment using `source venv/bin/activate`.
- - Install libraries using `pip install -r requirements.txt` in your terminal.
-
-## Frontend Setup
-
-1. Components:
-
- - `NewsFeed.jsx`:
-
- ```py copy
- import React from 'react';
-
- function NewsFeed({ news }) {
- return (
-
- );
- }
- export default NewsFeed;
- ```
-
- - `SearchComponent.jsx`:
-
- ```
- import React, { useState } from 'react';
- import './SearchComponent.css'; // Importing CSS for styling
-
- function SearchComponent({ onSearch }) {
- const [searchTerm, setSearchTerm] = useState('');
- const handleSubmit = (event) => {
- event.preventDefault();
- onSearch(searchTerm); // This function would be passed down from the parent component or defined here to handle the search logic
- };
-
- return (
-
-
-
- );
- }
- export default SearchComponent;
-
- ```
-
- - `SearchComponent.css`:
-
- ```
- .search-area {
- display: flex;
- justify-content: center;
- align-items: center;
- height: 100px; /* Approx 1 inch */
- background-color: #007BFF; /* Blue background */
- }
-
- .search-area form {
- display: flex;
- gap: 20px;
- }
-
- .search-area input {
- padding: 8px;
- border-radius: 4px;
- border: 1px solid #ccc;
- }
-
- .search-area button {
- background-color: #0056b3;
- color: white;
- border: none;
- border-radius: 4px;
- padding: 8px 16px;
- cursor: pointer;
- }
-
- .search-area button:hover {
- background-color: #004494;
- }
- ```
-
-2. `app.css`:
-
- ```
- .App {
- text-align: center;
- }
-
- .search-container, .news-feed, .stock-info {
- margin: 20px;
- padding: 10px;
- }
-
- input[type="text"] {
- margin-right: 10px;
- }
-
- .news-feed div {
- margin: 5px;
- }
-
- button {
- background-color: red;
- color: white;
- border: none;
- padding: 10px 20px;
- cursor: pointer;
- }
-
- button:hover {
- opacity: 0.8;
- }
-
- .news-feed {
- margin-top: 20px;
- padding: 10px;
- background-color: #f4f4f4;
- border-radius: 5px;
- color: black;
- text-decoration: none;
- }
-
- .news-feed a:hover {
- color: black;
- text-decoration: underline;
- }
-
- .news-feed ul {
- list-style-type: none;
- padding: 0;
- }
-
- .news-feed li {
- margin-bottom: 10px;
- padding: 5px;
- background-color: #fff;
- border-radius: 4px;
- color: black; /* Black color for text */
- text-align: left;
- }
-
- .sentiment-block {
- margin-top: 30px;
- padding: 10px;
- background-color: #dff0d8;
- color: #3c763d;
- border-radius: 5px;
- font-size: 20px;
- text-align: center;
- }
-
- .sentiment-block.neutral {
- background-color: #fcf8e3;
- color: #8a6d3b;
- }
-
- .sentiment-block.negative {
- background-color: #f2dede;
- color: #a94442;
- }
-
- .title-bar {
- background-color: #007BFF;
- color: white;
- padding: 10px 0;
- font-size: 24px;
- }
- ```
-
-3. `app.js`:
-
- ```
- // Import necessary React libraries and components
- import React, { useState } from 'react';
- import SearchComponent from './components/SearchComponent';
- import NewsFeed from './components/NewsFeed';
- import './App.css'; // Import CSS for styling
-
- // Define the main React functional component
- function App() {
- // State hooks to manage news data, sentiment, and type of sentiment
- const [news, setNews] = useState([]);
- const [sentiment, setSentiment] = useState('');
- const [sentimentType, setSentimentType] = useState('');
-
- // Function to handle search operations
- const handleSearch = async (searchTerm) => {
- try {
- // API request to fetch news based on a search term
- const newsResponse = await fetch(`http://127.0.0.1:5000/api/news/${searchTerm}`);
- const newsData = await newsResponse.json(); // Convert response to JSON
- setNews(newsData); // Update the news state
- console.log('Fetched news:', newsData); // Log the fetched news data
-
- // API request to fetch sentiment analysis for the search term
- const sentimentResponse = await fetch(`http://127.0.0.1:5000/api/sentiment/${searchTerm}`);
- const sentimentData = await sentimentResponse.text(); // Get response as text
- console.log('Fetched sentiment:', sentimentData); // Log the fetched sentiment
- processSentiment(sentimentData); // Process the fetched sentiment text
- } catch (error) {
- console.error('Failed to fetch data:', error); // Log any errors
- setNews([]); // Reset news state on error
- setSentiment(''); // Reset sentiment state on error
- setSentimentType(''); // Reset sentiment type state on error
- }
- };
-
- // Helper function to process the sentiment text and update state
- const processSentiment = (sentimentText) => {
- const parts = sentimentText.split(':'); // Split sentiment text by colon
- const sentimentValue = parts[0].trim().toLowerCase(); // Extract sentiment label and normalize it
- setSentiment(sentimentText); // Update sentiment state
- setSentimentType(sentimentValue); // Update sentiment type state
- };
-
- // Render the application UI
- return (
-
- // Search component with search handler
- // News feed component to display news
- {sentiment &&
{sentiment}
} // Conditionally render sentiment block
-
- );
- }
-
- export default App; // Export the App component for use in other parts of the application
- ```
-
-## Setup and Running the application
-### Backend Setup (Flask and Agents)
-
-1. Setup virtual environment:
-
- - Navigate to your project's backend directory:
-
- ```
- cd path/to/your/backend
- ```
-
- - Create a virtual environment:
-
- ```
- python -m venv venv
- ```
-
- - Activate the virtual environment:
-
- ```
- # For Windows
- venv\Scripts\activate
- # For MacOS/Linux
- source venv/bin/activate
- ```
-
-2. Install Dependencies:
-
- - Ensure `requirements.txt` is in the backend directory and contains all the necessary packages.
- - Install the required packages:
-
- ```
- pip install -r requirements.txt
- ```
-
-3. Start the Flask Application:
-
- - Make sure the Flask app (`app.py`) is configured correctly with routes and agent interactions.
- - Run the Flask app:
-
- ```
- python app.py
- ```
-
-4. Run the Agents:
- - Ensure each agent script (e.g., `news_agent.py`, `scraper_agent.py`, `sentiment_agent.py`) is ready and configured.
- - Start each agent in a separate terminal or command prompt to handle specific tasks:
-
- ```
- python news_agent.py
- python scraper_agent.py
- python sentiment_agent.py
- ```
-
-### Frontend Setup (React)
-
-1. Navigate to the Frontend Directory:
-
- - Change into your project's frontend directory where the React app is located.
-
- ```
- cd path/to/your/Frontend
- ```
-
-2. Install Dependencies:
-
- - Install the required node modules specified in `package.json`:
-
- ```
- npm install
- ```
-
-3. Start the React Development Server:
-
- - Run the following command to start the React development server:
-
- ```
- npm start
- ```
-
- - This typically starts the React application on `http://localhost:3000`.
-
-### Accessing the Application
-
-- Open your web browser and go to `http://localhost:3000`. You should see your React application's interface.
-- Use the search component to input a company name and fetch news and sentiment data, which will be displayed accordingly.
-
-## Expected Output
-
-
diff --git a/pages/examples/rag/_meta.json b/pages/examples/rag/_meta.json
deleted file mode 100644
index ac96b0708..000000000
--- a/pages/examples/rag/_meta.json
+++ /dev/null
@@ -1,24 +0,0 @@
-{
- "langchain-rag": {
- "title": "Langchain RAG Agent [intermediate]",
- "tags": [
- "Intermediate",
- "Python",
- "Functions",
- "LangChain",
- "DeltaV",
- "RAG"
- ],
- "timestamp": true
- },
- "vectara-uagents-rag": {
- "title": "Vectara RAG Agent [intermediate]",
- "tags": ["Intermediate", "Python", "Vectara", "RAG"],
- "timestamp": true
- },
- "premai-uagents-rag": {
- "title": "PremAI RAG Agent [intermediate]",
- "tags": ["Intermediate", "Python", "PremAI", "RAG"],
- "timestamp": true
- }
-}
diff --git a/pages/examples/rag/langchain-rag.mdx b/pages/examples/rag/langchain-rag.mdx
deleted file mode 100644
index 97d0d399d..000000000
--- a/pages/examples/rag/langchain-rag.mdx
+++ /dev/null
@@ -1,461 +0,0 @@
-import { CodeGroup, DocsCode, GithubCodeSegment, CodeSegment } from "../../../components/code"
-
-# Langchain RAG Agent
-
-## Introduction
-
-This example demonstrates how LangChain's RAG (Retrieval-Augmented Generation) technology integrates with uAgents. It shows how to create a RAG application that can answer questions based on a document.
-
-Please check out the example code in our [examples repo ↗️](https://github.com/fetchai/uAgent-Examples/tree/main/5-documentation/examples/intermediate/langchain-rag/src) to run this locally.
-
-### Supporting documentation
-
-- [Creating an agent↗️](/guides/agents/create-a-uagent)
-- [Creating an interval task ↗️](/guides/agents/interval-task)
-- [Communicating with other agents ↗️](/guides/agents/communicating-with-other-agents)
-- [Register in Almanac ↗️](/guides/agents/register-in-almanac)
-- [Almanac Contract ↗️](/references/contracts/uagents-almanac/almanac-overview)
-- [Utilising the Agentverse Mailroom service ↗️](/guides/agentverse/utilising-the-mailbox)
-- [Protocols ↗️](/references/uagents/uagents-protocols/agent-protocols)
-- [Agentverse Functions ↗️](/guides/agents/intermediate/agent-functions)
-- [Register an Agent Function on the Agentverse ↗️](/guides/agentverse/agentverse-functions/registering-agent-services)
-
-## Pre-requisites
-
-- **Python :** Download and install from [Python official website ↗️](https://www.python.org/downloads/).
-
-## Steps to Obtain API Keys
-
-To run this example, you will need two API keys: one from OpenAI and one from Cohere. Follow the steps below to obtain these keys.
-
-### OpenAI API Key
-
-1. Visit the [OpenAI website ↗️](https://openai.com/).
-2. Sign up or log in to your account.
-3. Navigate to the **API** section.
-4. Generate or retrieve your API key.
-
-### Cohere API Key
-
-1. Visit the [Cohere website ↗️](https://dashboard.cohere.com/).
-2. Sign up or log in to your account.
-3. Go to the **API Keys** section.
-4. Copy an existing key or create a new one.
-
-## Project Structure
-
-Outline of basic structure of the project:
-
-```
-langchain-rag/
-.
-├── poetry.lock
-├── pyproject.toml
-└── src
- ├── agents
- │ ├── langchain_rag_agent.py
- │ └── langchain_rag_user.py
- ├── main.py
- └── messages
- └── requests.py
-```
-
-## Setting Up Environment Variables
-
-To load the environment variables, use the following command:
-
-- Navigate to the `src` directory and source the `.env` file:
-
- ```bash
- cd src
- source .env
- ```
-
-### Example `.env` File
-
-Here is an example of what your `.env` file might look like:
-
-```bash
-export COHERE_API_KEY="YOUR_COHERE_API_KEY"
-export OPENAI_API_KEY="YOUR_OPENAI_API_KEY"
-```
-
-## Langchain RAG Setup
-
-### Poetry Dependencies:
-
-```
-[tool.poetry.dependencies]
-python = ">=3.10,<3.12"
-uagents = "^0.17.1"
-requests = "^2.31.0"
-langchain = "^0.3.7"
-openai = "^1.54.5"
-langchain-openai = "^0.2.9"
-tiktoken = "^0.8.0"
-cohere = "^5.11.4"
-faiss-cpu = "^1.9.0.post1"
-validators = "^0.34.0"
-uagents-ai-engine = "^0.6.0"
-unstructured = "^0.16.5"
-langchain-community = "^0.3.7"
-```
-
-### RagRequest Model
-
-The `RagRequest` model represents a request for retrieving an answer to a user's question from a specified document URL. It includes an optional parameter to determine if nested pages should also be read.
-
-
-
-
-
-
-
- ```py copy filename="requests.py"
-
- from typing import Optional
- from uagents import Model, Field
-
-
- class RagRequest(Model):
- question: str = Field(
- description="The question that the user wants to have an answer for."
- )
- url: str = Field(description="The url of the docs where the answer is.")
- deep_read: Optional[str] = Field(
- description="Specifies weather all nested pages referenced from the starting URL should be read or not. The value should be yes or no.",
- default="no",
- )
-
-
- ```
-
-
-
-
-
-
-### Langchain RAG agent
-
-This agent answers questions by fetching and summarizing information from a given website. It checks and scrapes URLs, uses LangChain to find important documents, and generates answers with OpenAI's GPT-40-mini model.
-
-
-
-
-
-
-
- ```py copy filename="langchain_rag_agent.py"
-
- import traceback
- from uagents import Agent, Context, Protocol
- import validators
- from messages.requests import RagRequest
- import os
- from langchain_openai import ChatOpenAI
- from langchain.prompts import ChatPromptTemplate
- from langchain_community.document_loaders import UnstructuredURLLoader
- import requests
- from bs4 import BeautifulSoup
- from urllib.parse import urlparse
- from langchain_openai import OpenAIEmbeddings
- from langchain_community.vectorstores import FAISS
- from langchain.retrievers import ContextualCompressionRetriever
- from langchain.retrievers.document_compressors import CohereRerank
- from ai_engine import UAgentResponse, UAgentResponseType
- import nltk
- from uagents.setup import fund_agent_if_low
-
- nltk.download("punkt")
- nltk.download("averaged_perceptron_tagger")
-
-
- LANGCHAIN_RAG_SEED = "YOUR_LANGCHAIN_RAG_SEED"
-
- agent = Agent(
- name="langchain_rag_agent",
- seed=LANGCHAIN_RAG_SEED,
- mailbox=True
- )
-
- fund_agent_if_low(agent.wallet.address())
-
- docs_bot_protocol = Protocol("DocsBot")
-
-
- PROMPT_TEMPLATE = """
- Answer the question based only on the following context:
-
- {context}
-
- ---
-
- Answer the question based on the above context: {question}
- """
-
-
- def create_retriever(
- ctx: Context, url: str, deep_read: bool
- ) -> ContextualCompressionRetriever:
- def scrape(site: str):
- if not validators.url(site):
- ctx.logger.info(f"Url {site} is not valid")
- return
-
- r = requests.get(site)
- soup = BeautifulSoup(r.text, "html.parser")
-
- parsed_url = urlparse(url)
- base_domain = parsed_url.scheme + "://" + parsed_url.netloc
-
- link_array = soup.find_all("a")
- for link in link_array:
- href: str = link.get("href", "")
- if len(href) == 0:
- continue
- current_site = f"{base_domain}{href}" if href.startswith("/") else href
- if (
- ".php" in current_site
- or "#" in current_site
- or not current_site.startswith(url)
- or current_site in urls
- ):
- continue
- urls.append(current_site)
- scrape(current_site)
-
- urls = [url]
- if deep_read:
- scrape(url)
- ctx.logger.info(f"After deep scraping - urls to parse: {urls}")
-
- try:
- loader = UnstructuredURLLoader(urls=urls)
- docs = loader.load_and_split()
- db = FAISS.from_documents(docs, OpenAIEmbeddings())
- compression_retriever = ContextualCompressionRetriever(
- base_compressor=CohereRerank(), base_retriever=db.as_retriever()
- )
- return compression_retriever
- except Exception as exc:
- ctx.logger.error(f"Error happened: {exc}")
- traceback.format_exception(exc)
-
-
- @docs_bot_protocol.on_message(model=RagRequest, replies={UAgentResponse})
- async def answer_question(ctx: Context, sender: str, msg: RagRequest):
- ctx.logger.info(f"Received message from {sender}, session: {ctx.session}")
- ctx.logger.info(
- f"input url: {msg.url}, question: {msg.question}, is deep scraping: {msg.deep_read}"
- )
-
- parsed_url = urlparse(msg.url)
- if not parsed_url.scheme or not parsed_url.netloc:
- ctx.logger.error("invalid input url")
- await ctx.send(
- sender,
- UAgentResponse(
- message="Input url is not valid",
- type=UAgentResponseType.FINAL,
- ),
- )
- return
- base_domain = parsed_url.scheme + "://" + parsed_url.netloc
- ctx.logger.info(f"Base domain: {base_domain}")
-
- retriever = create_retriever(ctx, url=msg.url, deep_read=msg.deep_read == "yes")
-
- compressed_docs = retriever.get_relevant_documents(msg.question)
- context_text = "\n\n---\n\n".join([doc.page_content for doc in compressed_docs])
- prompt_template = ChatPromptTemplate.from_template(PROMPT_TEMPLATE)
- prompt = prompt_template.format(context=context_text, question=msg.question)
-
- model = ChatOpenAI(model="gpt-4o-mini")
- response = model.predict(prompt)
- ctx.logger.info(f"Response: {response}")
- await ctx.send(
- sender, UAgentResponse(message=response, type=UAgentResponseType.FINAL)
- )
-
-
- agent.include(docs_bot_protocol, publish_manifest=True)
-
-
- if __name__ == "__main__":
- agent.run()
-
-
- ```
-
-
-
-
-
-
-### Langchain user agent
-
-The agent is designed to ask a predefined question to a RAG agent at regular intervals and handle the responses.
-
-
-
-
-
-
-
-
- ```py copy filename="langchain_rag_user.py"
-
- from uagents import Agent, Context, Protocol
- from messages.requests import RagRequest
- from ai_engine import UAgentResponse
- from uagents.setup import fund_agent_if_low
-
-
- QUESTION = "How to install uagents using pip"
- URL = "https://fetch.ai/docs/guides/agents/installing-uagent"
- DEEP_READ = (
- "no"
- )
-
- RAG_AGENT_ADDRESS = "YOUR_LANGCHAIN_RAG_AGENT_ADDRESS"
-
- user = Agent(
- name="langchain_rag_user",
- port=8000,
- endpoint=["http://127.0.0.1:8000/submit"],
- )
- fund_agent_if_low(user.wallet.address())
- rag_user = Protocol("LangChain RAG user")
-
-
- @rag_user.on_interval(60, messages=RagRequest)
- async def ask_question(ctx: Context):
- ctx.logger.info(
- f"Asking RAG agent to answer {QUESTION} based on document located at {URL}, reading nested pages too: {DEEP_READ}"
- )
- await ctx.send(
- RAG_AGENT_ADDRESS, RagRequest(question=QUESTION, url=URL, deep_read=DEEP_READ)
- )
-
-
- @rag_user.on_message(model=UAgentResponse)
- async def handle_data(ctx: Context, sender: str, data: UAgentResponse):
- ctx.logger.info(f"Got response from RAG agent: {data.message}")
-
-
- user.include(rag_user)
-
- if __name__ == "__main__":
- rag_user.run()
-
-
- ```
-
-
- ```py copy filename="langchain_rag_user.py"
-
- from typing import Optional
-
- from ai_engine import UAgentResponse
- from uagents import Context, Field, Model, Protocol
-
- QUESTION = "How to install uagents using pip"
- URL = "https://fetch.ai/docs/guides/agents/installing-uagent"
- DEEP_READ = "no"
-
-
- class RagRequest(Model):
- question: str = Field(
- description="The question that the user wants to have an answer for."
- )
- url: str = Field(description="The url of the docs where the answer is.")
- deep_read: Optional[str] = Field(
- description="Specifies weather all nested pages referenced from the starting URL should be read or not. The value should be yes or no.",
- default="no",
- )
-
-
- RAG_AGENT_ADDRESS = "YOUR_LANGCHAIN_RAG_AGENT_ADDRESS"
-
- rag_user = Protocol("LangChain RAG user")
-
-
- @agent.on_interval(60, messages=RagRequest)
- async def ask_question(ctx: Context):
- ctx.logger.info(
- f"Asking RAG agent to answer {QUESTION} based on document located at {URL}, reading nested pages too: {DEEP_READ}"
- )
- await ctx.send(
- RAG_AGENT_ADDRESS, RagRequest(question=QUESTION, url=URL, deep_read=DEEP_READ)
- )
-
-
- @agent.on_message(model=UAgentResponse)
- async def handle_data(ctx: Context, sender: str, data: UAgentResponse):
- ctx.logger.info(f"Got response from RAG agent: {data.message}")
-
-
- agent.include(rag_user)
-
- ```
-
-
-
-
-
-
-
-
-
-
-
- ```py copy filename="main.py"
-
- from uagents import Bureau
- from agents.langchain_rag_agent import agent
- from agents.langchain_rag_user import user
-
-
- if __name__ == "__main__":
- bureau = Bureau(endpoint="http://127.0.0.1:8000/submit", port=8000)
- print(f"Adding RAG agent to Bureau: {agent.address}")
- bureau.add(agent)
- print(f"Adding user agent to Bureau: {user.address}")
- bureau.add(user)
- bureau.run()
-
- ```
-
-
-
-
-
-
-## Expected output
-
-
diff --git a/pages/examples/rag/premai-uagents-rag.mdx b/pages/examples/rag/premai-uagents-rag.mdx
deleted file mode 100644
index a7c136a3f..000000000
--- a/pages/examples/rag/premai-uagents-rag.mdx
+++ /dev/null
@@ -1,317 +0,0 @@
-import { Callout } from 'nextra/components'
-
-# PremAI RAG Agent
-
-This example demonstrates the use of uAgents with Prem.ai to build a Retrieval-Augmented Generation (RAG) system, The agent handles health and wellness queries, providing informative responses. It integrates intelligent query handling with dynamic knowledge retrieval capabilities, making it a robust solution.
-
-Please check out the example code in our [examples repo ↗️](https://github.com/fetchai/uAgent-Examples/tree/main/5-documentation/examples/intermediate/premai-rag-agent) to run this locally.
-
-
-### Supporting documentation
-
-- [Creating an agent↗️](/guides/agents/create-a-uagent)
-- [Creating an interval task ↗️](/guides/agents/interval-task)
-- [Communicating with other agents ↗️](/guides/agents/communicating-with-other-agents)
-- [Register in Almanac ↗️](/guides/agents/register-in-almanac)
-- [Almanac Contract ↗️](/references/contracts/uagents-almanac/almanac-overview)
-
-## Prerequisites
-
-Before proceeding, ensure you have the following:
-
- 1. **Python Development Environment**:
-
- - **Python:** Download and install from [Python official website ↗️](https://www.python.org/downloads/).
- - **Poetry:** Install by following the instructions on [Poetry's official website ↗️](https://python-poetry.org/docs/#installation).
- - Dependencies installed via `poetry add uagents` and other required libraries.
-
- 2. **PremAI Account**:
-
- - Sign up at [PremAI ↗️](https://app.premai.io/accounts/signup/)
- - Access the PremAI dashboard.
-
-
-## Steps to Obtain API Keys
-
-To get the required API key and other details, you need to follow these steps:
-
- 1. **Sign In and Generate an API Key**:
-
- - Log in to your Prem account.
- - Navigate to the API Keys section in your account settings.
- - Generate a new `API key` and securely store it for future use.
-
- 2. **Create a New Project**:
-
- - In the Prem dashboard, go to the Projects section.
- - Click on `Create New Project`.
- - Provide a name and description for your project.
- - After creation, note the `Project ID` associated with your new project.
-
- 3. **Set Up a Repository**:
-
- - Within your project, navigate to the Repositories section.
- - Click on Create New Repository.
- - Provide a name and description for your repository.
- - Add the required document for your use case by clicking on the `Add document` button.
- - After creation, note the `Repository ID` associated with your new repository.
-
-
- You can obtain the `API_KEY`, `REPO_KEY` and `PROJECT_ID` from the [PremAI dashboard ↗️](https://app.premai.io/projects/).
-
-
-## Project Structure
-
-```
-premai-rag-agent/
-.
-├── poetry.lock
-├── premai-rag-agent.py
-├── pyproject.toml
-└── README.md
-```
-## Setting Up Environment Variables
-
-To load the environment variables, use the following command:
-
-- Navigate to the root directory and source the `.env` file by run `source .env`
-
-### Example `.env` File
-
-Here is an example of what your `.env` file might look like:
-
-```bash
-export API_KEY="YOUR_API_KEY"
-export PROJECT_ID="YOUR_PROJECT_ID"
-export REPO_ID="YOUR_REPO_ID"
-```
-
-## PremAI RAG Agent Setup
-
-### Overview of `query_prem_ai` function.
-
-The `query_prem_ai` function is responsible for querying the Prem.ai API with a user's health-related question. It formats the user's input as a message, then sends the query to the API, which searches a specific repository for relevant responses. The function then processes the API's response, extracting and cleaning the content by removing unnecessary references (like citation numbers). In case of an error, it raises a runtime exception with a descriptive error message. This function enables the system to retrieve tailored health advice based on the user's input.
-
-
-```py copy
-prem_client = Prem(api_key=API_KEY)
-
-def query_prem_ai(user_query):
- """
- Handles both initial and follow-up queries by calling Prem.ai API.
- """
- try:
- messages = [{"role": "user", "content": user_query}]
- repositories = dict(ids=[REPO_ID], similarity_threshold=0.25, limit=5)
- response = prem_client.chat.completions.create(
- project_id=PROJECT_ID,
- messages=messages,
- repositories=repositories,
- stream=False,
- model="gpt-4o",
- )
- final_response = response.choices[0].message.content
- cleaned_response = re.sub(r'\[\d+\]', '', final_response)
- return cleaned_response
- except Exception as e:
- raise RuntimeError(f"Error querying Prem.ai: {e}")
-
-```
-
-### PremAI agent mechanism
-
-#### 1. User Agent (`user_agent`)
-
-The `user_agent` is responsible for initiating the conversation and receiving the user's queries. It sends the query to the `prem_agent` for processing and displays the response back to the user. It also handles follow-up queries and the exit condition.
-
-```py copy
-user_agent = Agent(name="health_user_agent", seed="health_user_recovery")
-
-@user_agent.on_event("startup")
-async def send_health_query(ctx: Context):
- ctx.logger.info("[health_user_agent]: Sending initial query.")
- await ctx.send(prem_agent.address, HealthQuery(user_query=initial_query))
-
-@user_agent.on_message(model=HealthResponse, replies={HealthQuery, ExitMessage})
-async def handle_health_response(ctx: Context, sender: str, msg: HealthResponse):
- ctx.logger.info(f"[health_user_agent]: Received response: {msg.response}")
- follow_up_query = input("Ask your next question (or type 'exit' to quit): ").strip()
- if follow_up_query.lower() in {"exit", "quit"}:
- await ctx.send(sender, ExitMessage(message="Exiting chat. Goodbye!"))
- else:
- await ctx.send(sender, HealthQuery(user_query=follow_up_query))
-```
-
-#### Explanation of `user_agent`
-
-- The agent listens for a startup event, where it sends the first health query to the `prem_agent`.
-- When it receives a response from `prem_agent`, it presents the answer to the user and asks if they have a follow-up question.
-- If the user chooses to exit, it sends an exit message to end the conversation.
-
-#### 2. Prem Agent (`prem_agent`)
-
-The `prem_agent` processes the queries by interacting with the Prem.ai API. It retrieves the response from the API and sends it back to the `user_agent`. It also handles errors and exit messages.
-
-```py copy
-prem_agent = Agent(name="health_prem_agent", seed="health_prem_recovery")
-
-@prem_agent.on_message(model=HealthQuery, replies={HealthResponse, ExitMessage})
-async def process_health_query(ctx: Context, sender: str, msg: HealthQuery):
- ctx.logger.info(f"[health_prem_agent]: Processing query: {msg.user_query}")
- try:
- response = query_prem_ai(msg.user_query)
- await ctx.send(sender, HealthResponse(response=response))
- except RuntimeError as e:
- await ctx.send(sender, ExitMessage(message="Failed to process query."))
-
-@prem_agent.on_message(model=ExitMessage)
-async def handle_exit_message(ctx: Context, sender: str, msg: ExitMessage):
- ctx.logger.info(f"[health_prem_agent]: {msg.message}")
-
-```
-
-#### Explanation of `prem_agent`
-
-- The `prem_agent` listens for `HealthQuery` messages from the `user_agent`. Upon receiving a query, it sends the query to the Prem.ai API for processing.
-- After getting the response, the `prem_agent` sends the answer back to the `user_agent`.
-- If an error occurs, the agent sends an exit message with the error notification.
-
-### Whole Script
-
-This section presents the entire script, allowing users to easily copy and paste it for testing or deployment.
-
-```py copy
-import re
-import os
-from uagents import Field, Model, Context, Agent, Bureau
-from premai import Prem
-
-REPO_ID = os.getenv("REPO_ID")
-PROJECT_ID = os.getenv("PROJECT_ID")
-API_KEY = os.getenv("API_KEY")
-
-prem_client = Prem(api_key=API_KEY)
-
-def query_prem_ai(user_query):
- """
- Handles both initial and follow-up queries by calling Prem.ai API.
- """
- try:
- messages = [{"role": "user", "content": user_query}]
- repositories = dict(ids=[REPO_ID], similarity_threshold=0.25, limit=5)
- response = prem_client.chat.completions.create(
- project_id=PROJECT_ID,
- messages=messages,
- repositories=repositories,
- stream=False,
- model="gpt-4o",
- )
- final_response = response.choices[0].message.content
- cleaned_response = re.sub(r'\[\d+\]', '', final_response)
- return cleaned_response
- except Exception as e:
- raise RuntimeError(f"Error querying Prem.ai: {e}")
-
-
-class HealthQuery(Model):
- user_query: str = Field(description="The user's initial or follow-up query about health and wellness.")
-
-class HealthResponse(Model):
- response: str = Field(description="The response text returned by the Prem.ai API.")
-
-class ExitMessage(Model):
- message: str = Field(description="The exit message sent to the user when the chat session ends.")
-
-user_agent = Agent(name="health_user_agent", seed="health_user_recovery")
-prem_agent = Agent(name="health_prem_agent", seed="health_prem_recovery")
-
-initial_query = input("Ask your health and wellness question: ").strip()
-
-@user_agent.on_event("startup")
-async def send_health_query(ctx: Context):
- ctx.logger.info("[health_user_agent]: Sending initial query.")
- await ctx.send(prem_agent.address, HealthQuery(user_query=initial_query))
-
-@user_agent.on_message(model=HealthResponse, replies={HealthQuery, ExitMessage})
-async def handle_health_response(ctx: Context, sender: str, msg: HealthResponse):
- ctx.logger.info(f"[health_user_agent]: Received response: {msg.response}")
- follow_up_query = input("Ask your next question (or type 'exit' to quit): ").strip()
- if follow_up_query.lower() in {"exit", "quit"}:
- await ctx.send(sender, ExitMessage(message="Exiting chat. Goodbye!"))
- else:
- await ctx.send(sender, HealthQuery(user_query=follow_up_query))
-
-
-@prem_agent.on_message(model=HealthQuery, replies={HealthResponse, ExitMessage})
-async def process_health_query(ctx: Context, sender: str, msg: HealthQuery):
- ctx.logger.info(f"[health_prem_agent]: Processing query: {msg.user_query}")
- try:
- response = query_prem_ai(msg.user_query)
- await ctx.send(sender, HealthResponse(response=response))
- except RuntimeError as e:
- await ctx.send(sender, ExitMessage(message="Failed to process query."))
-
-@prem_agent.on_message(model=ExitMessage)
-async def handle_exit_message(ctx: Context, sender: str, msg: ExitMessage):
- ctx.logger.info(f"[health_prem_agent]: {msg.message}")
-
-bureau = Bureau(port=8000, endpoint="http://localhost:8000/submit")
-bureau.add(user_agent)
-bureau.add(prem_agent)
-
-if __name__ == "__main__":
- bureau.run()
-
-```
-
-### Poetry Dependencies:
-
-```py
-[tool.poetry.dependencies]
-python = ">=3.9,<3.13"
-uagents = "^0.18.1"
-python-dotenv = "^1.0.1"
-premai = "^0.3.79"
-```
-
-### Instructions to execute the example.
-
-- Navigate to the root folder of the example.
-- Update the `.env` file with require variables.
-- Install dependencies by running `poetry install`.
-- Execute the script with `python premai-rag-agent.py`.
-
-
-## Expected Output
-
-```
-Ask your health and wellness question: How does sleep affect overall wellness?
-INFO: [health_user_agent]: Starting agent with address: agent1q02chts3w84vfa83t2egvt8tfg33h84na6mmut8rvmq5v5n9fyppjkx89yd
-INFO: [health_user_agent]: [health_user_agent]: Sending initial query.
-INFO: [health_prem_agent]: Starting agent with address: agent1qtpx9u4phc5vnt9mpt26x6p397wx89ymadkq2w9hrmtxse609g8py3k4e3y
-INFO: [health_user_agent]: Registering on almanac contract...
-INFO: [health_prem_agent]: Registering on almanac contract...
-INFO: [health_prem_agent]: [health_prem_agent]: Processing query: How does sleep affect overall wellness?
-INFO:httpx:HTTP Request: POST https://app.premai.io/v1/chat/completions "HTTP/1.1 200 OK"
-INFO: [bureau]: Starting server on http://0.0.0.0:8000 (Press CTRL+C to quit)
-INFO: [health_user_agent]: [health_user_agent]: Received response: Sleep plays a crucial role in overall wellness, influencing various aspects of physical and mental health. Here are some key ways in which sleep affects wellness:
-
-1. **Physical Health**: Sleep is vital for maintaining physical health. It supports bodily functions such as tissue repair, muscle growth, and immune function. Lack of sleep has been linked to a higher risk of chronic conditions such as obesity, heart disease, and diabetes.
-
-2. **Cognitive Function**: Adequate sleep is essential for optimal brain function. It affects concentration, productivity, and performance. Sleep is also crucial for memory consolidation, allowing the brain to process and retain information.
-
-Overall, prioritizing good sleep hygiene and establishing a consistent sleep routine are foundational to maintaining overall wellness and enhancing quality of life.
-Ask your next question (or type 'exit' to quit): How can hydration improve overall health?
-INFO: [health_prem_agent]: [health_prem_agent]: Processing query: How can hydration improve overall health?
-INFO:httpx:HTTP Request: POST https://app.premai.io/v1/chat/completions "HTTP/1.1 200 OK"
-INFO: [health_user_agent]: Registering on almanac contract...complete
-INFO: [health_prem_agent]: Registering on almanac contract...complete
-INFO: [health_user_agent]: [health_user_agent]: Received response: Hydration significantly impacts overall health and well-being in various ways. Here are some key benefits:
-
-1. **Physical Performance**: Proper hydration is crucial for maintaining physical performance. It helps regulate body temperature, lubricates joints, and delivers nutrients to cells, which is essential for physical activities, both in everyday life and during exercise.
-
-2. **Cognitive Function**: Dehydration can affect cognitive functions such as attention, memory, and mood. Staying hydrated helps maintain cognitive performance and may reduce feelings of fatigue and confusion.
-
-Overall, maintaining proper hydration is a simple yet powerful way to promote health and prevent various physical and cognitive issues. It is generally recommended to drink an adequate amount of water daily, which can vary based on factors like age, climate, activity level, and individual health needs.
-Ask your next question (or type 'exit' to quit):
-```
diff --git a/pages/examples/rag/vectara-uagents-rag.mdx b/pages/examples/rag/vectara-uagents-rag.mdx
deleted file mode 100644
index 9613968f3..000000000
--- a/pages/examples/rag/vectara-uagents-rag.mdx
+++ /dev/null
@@ -1,334 +0,0 @@
-import { Callout } from 'nextra/components'
-
-# Vectara RAG Agent
-
-## Introduction
-
-This example demonstrates the use of uAgents with Vectara to build a Retrieval-Augmented Generation (RAG) system, enabling intelligent query handling and dynamic knowledge retrieval. The guide walks through the process of setting up a Vectara corpus, configuring agents for conversational AI, and utilizing helper functions to manage API interactions effectively. By following this example, you will gain insights into creating a seamless and scalable RAG solution using Vectara’s powerful capabilities.
-
-Please check out the example code in our [examples repo ↗️](https://github.com/fetchai/uAgent-Examples/tree/main/5-documentation/examples/intermediate/vectara-rag-agent) to run this locally.
-
-### Supporting documentation
-
-- [Creating an agent↗️](/guides/agents/create-a-uagent)
-- [Creating an interval task ↗️](/guides/agents/interval-task)
-- [Communicating with other agents ↗️](/guides/agents/communicating-with-other-agents)
-- [Register in Almanac ↗️](/guides/agents/register-in-almanac)
-- [Almanac Contract ↗️](/references/contracts/uagents-almanac/almanac-overview)
-
-## Pre-requisites
-
-Creating an Account on Vectara and Setting Up a Corpus
-
- 1. **Vectara Account**:
-
- - Sign up at [Vectara](https://www.vectara.com/)
- - Access the Vectara console.
-
- 2. **Python Development Environment**:
-
- - **Python:** Download and install from [Python official website ↗️](https://www.python.org/downloads/).
- - **Poetry:** Install by following the instructions on [Poetry's official website ↗️](https://python-poetry.org/docs/#installation).
- - Dependencies installed via `poetry add uagents` and other required libraries.
-
- 3. **API Keys and Corpus Details**:
-
- - Create a new corpus in the Vectara console.
- - Goto your corpus and click data tab.
- - Click on `Load data into corpus` and add data by clicking on `upload files` button.
- - Retrieve the `API key` from the Authorization section.
- - Make a note that `Corpus key` is the name of the corpus.
-
-## Project Structure
-
-Outline of basic structure of the project:
-
-```
-vectara-rag-agent/
-.
-├── poetry.lock
-├── pyproject.toml
-├── rag-functions.py
-├── README.md
-└── vectara-agent.py
-```
-
-## Setting Up Environment Variables
-
-To load the environment variables, use the following command:
-
-- Navigate to the root directory and source the `.env` file by run `source .env`
-
-### Example `.env` File
-
-Here is an example of what your `.env` file might look like:
-
-```bash
-export CORPUS_KEY="YOUR_CORPUS_KEY"
-export API_KEY="YOUR_API_KEY"
-```
-
-## Vectara RAG Agent Setup
-
-### Overview of `create_chat_session` and `add_chat_turn` functions
-
-The `create_chat_session` function is responsible for initiating a new chat session with the Vectara API. It takes the user's query and sends a POST request to the `/v2/chats` endpoint. The payload includes the query, corpus details such as `corpus_key` and semantics, and pagination parameters like offset and limit. On successful execution, it retrieves a unique `chat_id` and the API's response, which are then used to manage the chat session. If an error occurs during the process, it logs the issue and returns None values.
-
-```py copy
-async def create_chat_session(query, ctx):
- url = "https://api.vectara.io/v2/chats"
- payload = {
- "query": query,
- "search": {
- "corpora": [
- {
- "corpus_key": CORPUS_KEY,
- "semantics": "default"
- }
- ],
- "offset": 0,
- "limit": 5
- },
- "chat": {"store": True}
- }
-
- headers = {
- 'Content-Type': 'application/json',
- 'Accept': 'application/json',
- 'x-api-key': API_KEY
- }
-
- try:
- response = requests.post(url, headers=headers, json=payload)
- if response.status_code == 200:
- chat_data = response.json()
- return chat_data['chat_id'], chat_data['answer']
- else:
- ctx.logger.error(f"Failed to create chat session: {response.status_code}, {response.text}")
- return None, None
- except Exception as e:
- ctx.logger.error(f"Error creating chat session: {e}")
- return None, None
-```
-
-The `add_chat_turn` function extends an existing chat session by adding a follow-up query. It sends a POST request to the `/v2/chats/{chat_id}/turns` endpoint with the `chat_id` of the ongoing session and the follow-up query as part of the payload. This function ensures continuity in the conversation by maintaining context through the chat ID. It retrieves and returns the response to the follow-up query, or logs and handles any errors that arise. Together, these two functions enable seamless multi-turn interactions with the Vectara API while providing robust error handling.
-
-```py copy
-async def add_chat_turn(chat_id, query, ctx):
- url = f"https://api.vectara.io/v2/chats/{chat_id}/turns"
- payload = {
- "query": query,
- "search": {
- "corpora": [
- {
- "corpus_key": CORPUS_KEY,
- "semantics": "default"
- }
- ],
- "offset": 0,
- "limit": 5
- }
- }
-
- headers = {
- 'Content-Type': 'application/json',
- 'Accept': 'application/json',
- 'x-api-key': API_KEY
- }
-
- try:
- response = requests.post(url, headers=headers, json=payload)
- if response.status_code == 200:
- turn_data = response.json()
- return turn_data['chat_id'], turn_data.get('answer', "No answer returned")
- else:
- ctx.logger.error(f"Failed to add chat turn: {response.status_code}, {response.text}")
- return None, "Error"
- except Exception as e:
- ctx.logger.error(f"Error adding chat turn: {e}")
- return None, "Error"
-```
-
-
- You can obtain the `CORPUS_KEY` and `API_KEY` from the [vectara console ↗️](https://console.vectara.com/console). and also add these two functions in the `rag-functions.py` file
-
-
-
-### Vectara agent mechanism
-
-The code uses two agents (`user_agent` and `vectara_agent`) to facilitate a structured chatbot mechanism. Here's how the important parts of the agent mechanism are implemented:
-
-## `user_agent`
-
-The `user_agent` handles user interactions, captures input, and forwards it to `vectara_agent`.
-
-- Startup Event
-
-The `initiate_query` function is triggered on application startup. It sends the user's initial query to the `vectara_agent`.
-
-```py copy
-@user_agent.on_event("startup")
-async def initiate_query(ctx: Context):
- ctx.logger.info("[user_agent] : Sending initial query.")
- await ctx.send(vectara_agent.address, QueryRequest(user_query=initial_query))
-```
-
-- Handling Responses
-
-When `vectara_agent` sends a response, it prompts the user for a follow-up query or exits the conversation.
-
-```py copy
-@user_agent.on_message(model=ResponseData, replies={FollowUpQuery, ExitHandlerMessage})
-async def handle_response(ctx: Context, sender: str, msg: ResponseData):
- ctx.logger.info(f"[user_agent] : Received response: {msg.response}")
- follow_up_query = input("Ask your question: ").strip()
- if follow_up_query.lower() in {"exit", "quit"}:
- await ctx.send(sender, ExitHandlerMessage(message="Exiting chat. Goodbye!"))
- else:
- await ctx.send(sender, FollowUpQuery(follow_up_query=follow_up_query, chat_id=msg.chat_id))
-
-```
-
-## `vectara_agent`
-
-The `vectara_agent` processes user queries and communicates with the Vectara API.
-
-- Processing Initial Queries:
-
-When it receives a `QueryRequest`, it uses the `create_chat_session` function to initiate a chat session and sends the response back to `user_agent`.
-
-```py copy
-@vectara_agent.on_message(model=QueryRequest, replies=ResponseData)
-async def process_initial_query(ctx: Context, sender: str, msg: QueryRequest):
- ctx.logger.info(f"[vectara_agent] : Processing initial query: {msg.user_query}")
- chat_id, response = await create_chat_session(msg.user_query, ctx)
- if chat_id and response:
- await ctx.send(sender, ResponseData(response=response, chat_id=chat_id))
- else:
- ctx.logger.error("Failed to process initial query.")
-
-```
-
-- Handling Follow-Up Queries:
-
-For follow-up questions, it uses `add_chat_turn` to continue the conversation in the same chat session and cleans the response before sending it back.
-
-```py copy
-@vectara_agent.on_message(model=FollowUpQuery, replies={ResponseData, ExitHandlerMessage})
-async def process_follow_up_query(ctx: Context, sender: str, msg: FollowUpQuery):
- ctx.logger.info(f"[vectara_agent]: Processing follow-up query for chat_id {msg.chat_id}: {msg.follow_up_query}")
- chat_id, response = await add_chat_turn(msg.chat_id, msg.follow_up_query, ctx)
- if chat_id and response:
- cleaned_response = re.sub(r'\[\d+\]', '', response)
- await ctx.send(sender, ResponseData(response=cleaned_response, chat_id=chat_id))
- else:
- await ctx.send(sender, ExitHandlerMessage(message="Failed to process follow-up query."))
-
-```
-
-### Whole Script
-
-This section presents the entire script, allowing users to easily copy and paste it for testing or deployment.
-
-```py copy filename="vectara-agent.py"
-import re
-from uagents import Field, Model, Context, Agent, Bureau
-from ragfunctions import create_chat_session, add_chat_turn
-
-class QueryRequest(Model):
- user_query: str = Field(description="The user's initial query to start the chat session.")
-
-class ResponseData(Model):
- response: str = Field(description="The response text returned by the Vectara API.")
- chat_id: str = Field(description="The unique identifier for the chat session.")
-
-class FollowUpQuery(Model):
- chat_id: str = Field(description="The unique identifier for the ongoing chat session.")
- follow_up_query: str = Field(description="The user's follow-up question for the ongoing chat.")
-
-class ExitHandlerMessage(Model):
- message: str = Field(description="The exit message sent to the user when the chat session ends.")
-
-
-user_agent = Agent(name="user_agent", seed="user_agent_recovery")
-vectara_agent = Agent(name="vectara_agent", seed="vectara_agent_recovery")
-
-initial_query = input("Ask your question: ").strip()
-
-@user_agent.on_event("startup")
-async def initiate_query(ctx: Context):
- ctx.logger.info("[user_agent] : Sending initial query.")
- await ctx.send(vectara_agent.address, QueryRequest(user_query=initial_query))
-
-@user_agent.on_message(model=ResponseData, replies={FollowUpQuery, ExitHandlerMessage})
-async def handle_response(ctx: Context, sender: str, msg: ResponseData):
- ctx.logger.info(f"[user_agent] : Received response: {msg.response}")
- follow_up_query = input("Ask your question: ").strip()
- if follow_up_query.lower() in {"exit", "quit"}:
- await ctx.send(sender, ExitHandlerMessage(message="Exiting chat. Goodbye!"))
- else:
- await ctx.send(sender, FollowUpQuery(follow_up_query=follow_up_query, chat_id=msg.chat_id))
-
-@vectara_agent.on_message(model=QueryRequest, replies=ResponseData)
-async def process_initial_query(ctx: Context, sender: str, msg: QueryRequest):
- ctx.logger.info(f"[vectara_agent] : Processing initial query: {msg.user_query}")
- chat_id, response = await create_chat_session(msg.user_query, ctx)
- if chat_id and response:
- await ctx.send(sender, ResponseData(response=response, chat_id=chat_id))
- else:
- ctx.logger.error("Failed to process initial query.")
-
-@vectara_agent.on_message(model=FollowUpQuery, replies={ResponseData, ExitHandlerMessage})
-async def process_follow_up_query(ctx: Context, sender: str, msg: FollowUpQuery):
- ctx.logger.info(f"[vectara_agent]: Processing follow-up query for chat_id {msg.chat_id}: {msg.follow_up_query}")
- chat_id, response = await add_chat_turn(msg.chat_id, msg.follow_up_query, ctx)
- if chat_id and response:
- cleaned_response = re.sub(r'\[\d+\]', '', response)
- await ctx.send(sender, ResponseData(response=cleaned_response, chat_id=chat_id))
- else:
- await ctx.send(sender, ExitHandlerMessage(message="Failed to process follow-up query."))
-
-@vectara_agent.on_message(model=ExitHandlerMessage)
-async def handle_exit_message(ctx: Context, sender: str, msg: ExitHandlerMessage):
- ctx.logger.info(f"[vectara_agent] : {msg.message}")
-
-bureau = Bureau(endpoint=["http://localhost:8000/submit"])
-bureau.add(user_agent)
-bureau.add(vectara_agent)
-
-if __name__ == "__main__":
- bureau.run()
-
-```
-
-### Poetry Dependencies:
-
-```py
-[tool.poetry.dependencies]
-python = ">=3.9,<3.13"
-uagents = "^0.18.1"
-python-dotenv = "^1.0.1"
-```
-
-## Instructions to execute the example.
-
-- Navigate to the root folder of the example.
-- Update the `.env` file with require variables.
-- Install dependencies by running `poetry install`.
-- Execute the script with `python vectara-agent.py`.
-
-## Expected output
-
-```
-Ask your question: what is uagents?
-INFO: [user_agent]: Starting agent with address: agent1qf4gycjj5vxdsgt4svl72mtu2cy5js8jay0857arfuxm676h2eeq52v2vwg
-INFO: [user_agent]: [user_agent] : Sending initial query.
-INFO: [vectara_agent]: Starting agent with address: agent1qtv9gdupwpz4t6e4fklvzhkcwxfemgky76wxwtskgj43ecqtrzcw2wq6gkf
-INFO: [vectara_agent]: [vectara_agent] : Processing initial query: what is uagents?
-INFO: [bureau]: Starting server on http://0.0.0.0:8000 (Press CTRL+C to quit)
-INFO: [user_agent]: [user_agent] : Received response: The uAgents framework is a lightweight Python library designed for developing decentralized agents. It simplifies the process of creating agents and is meant to be used within a Python environment. To use the uAgents library, Python must be installed on your system. Installing the uagents framework on a Windows machine is a straightforward process. This library serves as a tool to aid in building decentralized agents efficiently and effectively.
-Ask your question: what is agent address?
-INFO: [vectara_agent]: [vectara_agent]: Processing follow-up query for chat_id cht_ebd5dd8a-9168-4aeb-96e0-90680dbdc27a: what is agent address?
-INFO: [user_agent]: [user_agent] : Received response: The agent address is a unique identifier in the form of "agent1" . It is obtained from the attribute "address" and can be retrieved using the agent.address() method . This address is crucial for registering an agent to the Almanac contract . Additionally, the agent's address can be accessed through methods like .wallet.address() using the agent object .
-Ask your question:
-```
\ No newline at end of file
diff --git a/pages/guides.mdx b/pages/guides.mdx
deleted file mode 100644
index 32f6e5a6b..000000000
--- a/pages/guides.mdx
+++ /dev/null
@@ -1,561 +0,0 @@
-# Guides
-
-
- The place where you can find all tutorials and guides needed to familiarise with the concepts and code in a practical way to develop your ideas autonomously.
-
-
-import GuidesMdx from "../components/guide-mdx"
-import {FeaturedGuides} from "../components/feature-guide-tabs"
-import { AgentsIcon, AgentverseIcon, CliIcon,FetchNetwork, AsiIcon, LedgerIcon } from "src/icons/main-page-icons";
-
-
- }
- }
- mainHeading={"Explore all guides"}
- content={ [
- {
- type: "Agents",
- icon: AgentsIcon,
- description:
-
- "A list of guides showing the process to get started and develop use cases using agents technology.",
- data: [
- {
- title: "Quickstart",
- path: "/guides/agents/quickstart",
- },
- {
- title: "Whats an Agent",
- path: "/guides/agents/getting-started/whats-an-agent",
- },
- {
- title: "Installing the uAgents Framework",
- path: "/guides/agents/getting-started/installing-uagent",
- },
- {
- title: "Creating your first agent",
- path: "/guides/agents/getting-started/create-a-uagent",
- },
- {
- title: "Agent address",
- path: "/guides/agents/getting-started/getting-uagent-address",
- },
- {
- title: "Communicating with other agents",
- path: "/guides/agents/intermediate/communicating-with-other-agents",
- },
- {
- title: "Agent Handlers",
- path: "/guides/agents/intermediate/handlers",
- },
- {
- title: "Using agents storage function",
- path: "/guides/agents/intermediate/storage-function",
- },
- {
- title: "Hosted, Local, and Mailbox Agents",
- path: "/guides/agents/intermediate/agent-types",
- },
- {
- title: "Bureau",
- path: "/guides/agents/intermediate/bureau",
- },
- {
- title: "Broadcast",
- path: "/guides/agents/intermediate/broadcast",
- },
- {
- title: "Agent Mailboxes",
- path: "/guides/agents/intermediate/mailbox",
- },
- {
- title: "Local Agent Inspector",
- path: "/guides/agents/intermediate/local-agent-inspector",
- },
- {
- title: "Agent Functions",
- path: "/guides/agents/intermediate/agent-functions",
- },
- {
- title: "Make your agents AI Engine compatible",
- path: "/guides/agents/intermediate/ai-engine-compatible-agent",
- },
- {
- title: "Options for running your Agents",
- path: "/guides/agents/intermediate/options-for-running-local-agents",
- },
- {
- title: "Agents running on agentverse",
- path: "/guides/agents/intermediate/hosted-agent",
- },
- {
- title: "Build a LangChain RAG Agent",
- path: "/guides/agents/intermediate/langchain-rag-agent",
- },
- {
- title: "Rest Endpoints",
- path: "/guides/agents/intermediate/rest-endpoints",
- },
- {
- title: "Public and private agents",
- path: "/guides/agents/intermediate/public-private-agents",
- },
- {
- title: "How to use agents to send tokens",
- path: "/guides/agents/intermediate/send-tokens",
- },
- {
- title: "Primary secondary functions",
- path: "/guides/agents/intermediate/primary-secondary-functions",
- },
- {
- title: "Dialogues",
- path: "/guides/agents/advanced/dialogues",
- },
- {
- title: "Registering in Almanac Contract",
- path: "/guides/agents/advanced/register-in-almanac",
- },
- {
- title: "Agent Asynchronous Loops",
- path: "/guides/agents/advanced/agents-async-loops",
- },
- {
- title: "Agent Envelopes",
- path: "/guides/agents/advanced/agent-envelopes",
- },
- {
- title: "How to use agents to verify messages",
- path: "/guides/agents/advanced/message-verification",
- },
- {
- title: "Utilizing api to build network of task and subtask",
- path: "/guides/agents/advanced/utilizing-api-to-build-network-of-task-and-subtask",
- },
- {
- title: "Local Wallet",
- path: "/guides/agents/advanced/localwallet",
- },
- {
- title: "Agents Name Service",
- path: "/guides/agents/advanced/name-service",
- },
- ],
- },
- {
- type: "Agentverse",
- icon: AgentverseIcon,
- description:
- "A list of guides representing the various features offered within the Agentverse platform.",
- data: [
- {
- title: "Creating an Agentverse hosted Agent",
- path: "/guides/agentverse/creating-a-hosted-agent",
- },
- {
- title: "Simple dice roll Agent",
- path: "/guides/agentverse/creating-a-hosted-agent",
- },
- {
- title: "Allowed Imports",
- path: "/guides/agentverse/creating-agentverse-agents/allowed-imports",
- },
- {
- title: "Agentverse Teams",
- path: "/guides/agentverse/creating-agentverse-agents/agentverse-teams",
- },
- {
- title: "Utilising the Mailbox",
- path: "/guides/agentverse/creating-agentverse-agents/agentverse-teams",
- },
- {
- title: "Registering Agent services",
- path: "/guides/agentverse/agentverse-functions/registering-agent-services",
- },
- {
- title: "Registering Agent coin toss",
- path: "/guides/agentverse/agentverse-functions/registering-agent-coin-toss",
- },
- {
- title: "Field descriptions for DeltaV",
- path: "/guides/agentverse/agentverse-functions/field-descriptions-for-deltav",
- },
- {
- title: "Hyperlinks and rich text Deltav",
- path: "/guides/agentverse/agentverse-functions/hyperlinks-and-rich-text-deltav",
- },
- {
- title: "AVCTL - Agentverse Command Line Interface",
- path: "/guides/agentverse/avctl/avctl",
- },
- {
- title: "AVCTL Hosting",
- path: "/guides/agentverse/avctl/avctl-hosting",
- },
- {
- title: "CI with AVCTL and Github Actions",
- path: "/guides/agentverse/avctl/avctl-ci-github",
- },
- ],
- },
- {
- type: "API's",
- icon: FetchNetwork,
- data: [
- {
- title: "Agents and Functions Creation using APIs",
- path: "/guides/apis/agent-function-creation-apis"
- },
- {
- title: "Adding Secret to Agents using Agentverse APIs",
- path: "/guides/apis/secret-management-apis"
- },
- ]
- },
- {
- type: "Fetch network",
- icon: FetchNetwork,
- description: "A list of guides related to operations and tools executable on the ASI Network.",
- data: [
- {
- title: "How to convert Native FET to and from ERC-20 FET",
- path: "/guides/fetch-network/how-to-convert-fet-to-and-from-erc20"
- },
- {
- title: "How to stake FET tokens",
- path: "/guides/fetch-network/how-to-stake"
- },
- {
- title: "Different ways of staking FET",
- path: "/guides/fetch-network/different-ways-to-stake-the-fet-token"
- },
- {
- title: "Re-delegating staked FET token",
- path: "/guides/fetch-network/re-delegating-staked-fet-token"
- },
- {
- title: "Reconciliation service",
- path: "/guides/fetch-network/reconciliation-service"
- },
- {
- title: "Setting up a Multisig Account",
- path: "/guides/fetch-network/setting-up-a-multisig"
- }
- ]
- },
- {
- type: "ASI Alliance Wallet",
- icon: AsiIcon,
- subSection: true,
- data: [
- {
- title: "ASI Alliance Wallet",
- path: "/guides/fetch-network/asi-wallet/web-wallet/get-started"
- },
- {
- title: "Home Screen",
- path: "/guides/fetch-network/asi-wallet/web-wallet/home-screen"
- },
- {
- title: "Stake",
- path: "/guides/fetch-network/asi-wallet/web-wallet/stake"
- },
- {
- title: "Send Receive",
- path: "/guides/fetch-network/asi-wallet/web-wallet/send-receive"
- },
- {
- title: "Activity",
- path: "/guides/fetch-network/asi-wallet/web-wallet/activity"
- },
- {
- title: "More Options",
- path: "/guides/fetch-network/asi-wallet/web-wallet/more"
- },
- {
- title: "Gov Proposal",
- path: "/guides/fetch-network/asi-wallet/web-wallet/gov-proposal"
- },
- {
- title: "ASI Alliance Wallet : Mobile",
- path: "/guides/fetch-network/asi-wallet/mobile-wallet/get-started"
- },
- {
- title: "Home Screen : Mobile",
- path: "/guides/fetch-network/asi-wallet/mobile-wallet/home-screen"
- },
- {
- title: "Stake : Mobile",
- path: "/guides/fetch-network/asi-wallet/mobile-wallet/stake"
- },
- {
- title: "Send Receive: Mobile",
- path: "/guides/fetch-network/asi-wallet/mobile-wallet/send-receive"
- },
- {
- title: "Activity: Mobile",
- path: "/guides/fetch-network/asi-wallet/mobile-wallet/activity"
- },
- {
- title: "More Options: Mobile",
- path: "/guides/fetch-network/asi-wallet/mobile-wallet/more"
- },
- {
- title: "Gov Proposal: Mobile",
- path: "/guides/fetch-network/asi-wallet/mobile-wallet/gov-proposal"
- },
- {
- title: "ASI Alliance Wallet Hardware Connection Guide",
- path: "/guides/fetch-network/asi-wallet/asi-wallet-hardware-connection-guide"
- }
- ]
- },
- {
- type: "Cosmpy",
- icon: AsiIcon,
- subSection: true,
- data: [
- {
- title: "Cosmpy: Installation",
- path: "/guides/fetch-network/cosmpy/install"
- },
- {
- title: "Connecting to a blockchain",
- path: "/guides/fetch-network/cosmpy/establishing-node-connection"
- },
- {
- title: "Querying balances",
- path: "/guides/fetch-network/cosmpy/querying-address-balances"
- },
- {
- title: "Wallets and private keys",
- path: "/guides/fetch-network/cosmpy/creating-wallet"
- },
- {
- title: "Sending funds",
- path: "/guides/fetch-network/cosmpy/transaction-broadcast"
- },
- {
- title: "Staking with CosmPy",
- path: "/guides/fetch-network/cosmpy/staking"
- },
- {
- title: "Smart contracts",
- path: "/guides/fetch-network/cosmpy/smart-contracts"
- },
- ]
- },
- {
- type: "Cosmpy: use cases",
- icon: AsiIcon,
- subSection: true,
- data: [
- {
- title: "Stake auto-compounder",
- path: "/guides/fetch-network/cosmpy/use-cases/stake-auto-compounder"
- },
- {
- title: "Stake optimizer",
- path: "/guides/fetch-network/cosmpy/use-cases/stake-optimizer"
- },
- {
- title: "Oracles",
- path: "/guides/fetch-network/cosmpy/use-cases/oracles"
- },
- {
- title: "Wallet top-up",
- path: "/guides/fetch-network/cosmpy/use-cases/wallet-top-up"
- },
- {
- title: "Liquidity pool",
- path: "/guides/fetch-network/cosmpy/use-cases/liquidity-pool"
- },
- {
- title: "Swap automation",
- path: "/guides/fetch-network/cosmpy/use-cases/swap_automation"
- }
- ]
- },
- {
- type: "Jenesis",
- icon: AsiIcon,
- data: [
- {
- title: "Jenesis: Installation",
- path: "/guides/fetch-network/jenesis/install"
- },
- {
- title: "Getting started",
- path: "/guides/fetch-network/jenesis/getting-started"
- },
- {
- title: "Keys",
- path: "/guides/fetch-network/jenesis/keys"
- },
- {
- title: "How to add profiles",
- path: "/guides/fetch-network/jenesis/contracts/add-contracts"
- },
- {
- title: "How to add contract templates",
- path: "/guides/fetch-network/jenesis/contracts/add-contracts"
- },
- {
- title: "How to compile contracts",
- path: "/guides/fetch-network/jenesis/keys"
- },
- {
- title: "How to deploy contracts",
- path: "/guides/fetch-network/jenesis/contracts/deploy-contracts"
- },
- {
- title: "Contract interaction",
- path: "/guides/fetch-network/jenesis/contracts/contracts-interaction"
- }
- ]
- },
- {
- type: "Ledger",
- icon: LedgerIcon,
- subSection: true,
- description: "A list of guides related to operations executable on the Fetch Ledger.",
- data: [
- {
- title: "Installation",
- path: "/guides/fetch-network/ledger/installation"
- },
- {
- title: "How to use chain state snapshots",
- path: "/guides/fetch-network/ledger/snapshots"
- },
- {
- title: "State-sync",
- path: "/guides/fetch-network/ledger/state-sync"
- },
- {
- title: "Setting up a validator node",
- path: "/guides/fetch-network/ledger/setup-validator-node"
- },
- {
- title: "How to join a testnet",
- path: "/guides/fetch-network/ledger/joining-testnet"
- },
- {
- title: "How to run a single node test network",
- path: "/guides/fetch-network/ledger/single-node-testnet"
- },
- {
- title: "Governance",
- path: "/guides/fetch-network/ledger/governance"
- },
- {
- title: "How to get testnet tokens via the Token Faucet",
- path: "/guides/fetch-network/ledger/faucet"
- }
- ]
- },
- {
- type: "CLI - Command Line Interface",
- icon: CliIcon,
- subSection: true,
- data: [
- {
- title: "CLI - Introduction",
- path: "/guides/fetch-network/ledger/cli/intro"
- },
- {
- title: "CLI - Managing keys",
- path: "/guides/fetch-network/ledger/cli/keys"
- },
- {
- title: "CLI - Managing tokens",
- path: "/guides/fetch-network/ledger/cli/tokens"
- },
- {
- title: "CLI - Multisig keys",
- path: "/guides/fetch-network/ledger/cli/multisig-keys"
- },
- {
- title: "CLI - Delegation",
- path: "/guides/fetch-network/ledger/cli/delegator"
- },
- {
- title: "Governance proposals",
- path: "/guides/fetch-network/ledger/cli/governance-proposals"
- }
- ]
- },
- {
- type: "Courses",
- icon: AgentsIcon,
- data: [
- {
- title: "Agents 101",
- path: "/guides/agent-courses/introductory-course"
- },
- {
- title: "Agents 101 for AI Engine",
- path: "/guides/agent-courses/agents-for-ai"
- }
- ]
- },
- {
- type: "AI-Engine SDk",
- icon: AgentsIcon,
- data: [
- {
- title: "AI-Engine Python SDk",
- path: "/guides/ai-engine-sdk/python"
- },
- {
- title: "AI-Engine Javascript SDk",
- path: "/guides/ai-engine-sdk/javascript"
- }
- ]
- }
-]} />
-
-
\ No newline at end of file
diff --git a/pages/guides/_meta.json b/pages/guides/_meta.json
deleted file mode 100644
index 3b01143ea..000000000
--- a/pages/guides/_meta.json
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "agents": "AI Agents",
- "agentverse": "Agentverse",
- "apis": "APIs",
- "fetch-network": "ASI Network",
- "agent-courses": "Courses",
- "ai-engine-sdk": "AI Engine SDK",
- "fetchai-sdk": "Fetch.ai SDK",
- "quickstart-with": "Quickstart With"
-}
diff --git a/pages/guides/agent-courses/_meta.json b/pages/guides/agent-courses/_meta.json
deleted file mode 100644
index d9879080e..000000000
--- a/pages/guides/agent-courses/_meta.json
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "introductory-course": {
- "title": "Agents 101",
- "tags": ["Beginner", "Python", "Agents"]
- },
- "agents-for-ai": {
- "title": "Agents 101 for AI Engine",
- "tags": ["Beginner", "Python", "Functions", "AI Engine"]
- }
-}
diff --git a/pages/guides/agent-courses/agents-for-ai.mdx b/pages/guides/agent-courses/agents-for-ai.mdx
deleted file mode 100644
index 6a53c869b..000000000
--- a/pages/guides/agent-courses/agents-for-ai.mdx
+++ /dev/null
@@ -1,566 +0,0 @@
-import { Callout } from 'nextra/components'
-import PackageVersion from 'components/package-version'
-import { CodeGroup, CodeSegment, DocsCode, GithubCodeSegment } from "../../../components/code";
-
-# Agents 101 for AI Engine
-
-## Overview
-
-Welcome to **Agents 101 for AI Engine**! This course is designed to introduce you to the overall system of Fetch.ai, and shows how to build Agents to be accessible to the AI Engine and integrate with other projects. This course is a parallel track to [Agents 101 ↗️](/guides/agent-courses/introductory-course) which instead focuses only on Agents creation using the [uAgents ↗️](/guides/agents/getting-started/installing-uagent) library.
-
-At any stage, if you encounter issues or have questions about specific terms or topics, our support team is available on [Discord ↗️](https://discord.gg/fetchai) to assist you.
-
-
- Checkout the [AI Engine package ↗️](https://pypi.org/project/uagents-ai-engine/) to download it and start integrating your Agents with this tool!
-
- Current version of the AI Engine package is
-
-
-## Quick overview of Fetch.ai
-
-Fetch.ai is developing a platform to help build an AI-enabled decentralized digital economy. Agents are
-programs that can make choices on their own for individuals, companies, and devices. Agents are the actors and the
-heart of the ASI Ecosystem.
-
-To build your solution on Fetch.ai you need to understand four concepts: [Agents ↗️](/concepts/agents/agents), [Agentverse ↗️](/concepts/agent-services/agentverse-intro), [AI Engine ↗️](/concepts/ai-engine/ai-engine-intro) and [DeltaV ↗️](/concepts/ai-engine/deltav).
-
-### Agent, Agentverse, AI Engine and DeltaV
-
-Let's try and keep this simple 🎉:
-
- - **Agents**: These are programs that work as you instruct them. Classically, they are part of a multi-agent system where they have a task and communicate with other agents. But their primary use in this case is to offer a functionality that can be accessed by DeltaV.
-
- - **Agentverse**: It is a managed hosting platform, an online IDE, and an entry point to AI Engine for Agents. You would register your Agents on Agentverse to be a Function in the network.
-
- - **AI Engine**: The AI Engine is a system that combines Agents with human-readable text input to create a scalable AI infrastructure that supports Large Language Models (LLMs). It's an AI system that can convert human text into actionable (computer) commands.
-
- - **DeltaV**: It is an assistive chat interface that allows human input to interact with agents registered through the Agentverse.
-
-
- Agents are programs, whereas functions are specific [Agent Functions ↗️](/guides/agents/intermediate/agent-functions) your Agents offer.
-
-
-In a nutshell, AI Engine indexes Agents and related functions, and translates human input into **objectives**. It may sound like a search engine, but it does much more. Have a look at the following [resource ↗️](/concepts/ai-engine/powering-connections-and-smart-operations-in-deltav) to better understand how this process works.
-
-
-
-The AI Engine allows **chaining**. Say that you ask DeltaV: "Tell me about the animal Zebra". The AI Engine would then look for an Agent that could give you a summary, as well as another agent that could provide information about zebras. The AI Engine understands that the **Summary Agent** requires text to parse and summarise. So it would contact the **Zebra Agent** and get the information from it. The AI Engine would then call the **Summary Agent** with the **Zebra Agent** information so that the former would return the summarized text.
-
-It works like this:
-
-
-
-Simply put, when the AI Engine selects a response, the Secondary Functions available to be called for that Primary Function are already known to it.
-
-Of course, this could be more complicated. What if every sensor on a car was an agent? You could ask your car for
-diagnostics on a system, and each component in that system would independently give its status - making everything extremely complex. That's where the power of the AI Engine comes in. It understands the schema of each Agent, so there would be little need for each component to be compatible in communication with each other.
-
-## Okay, so how does this all work?
-
-To understand this, we need to look into a few more concepts:
-
-
-
-Here, **two separate** processes are happening. The first part of the sequence diagram registers two agents:
-
- 1. Firstly, agents register to a smart contract thus effectively paying to be discoverable.
- 2. Agents then register as a Function on Agentverse (you'd usually do this manually).
-
-Now that the Agents are registered and discoverable - let's move on to the second part of the diagram. The second part of the diagram introduces the flow of the AI Engine. This shows the role of a user who has entered a search term into DeltaV.
-
- 1. A query comes in and it is sent to the AI Engine.
- 2. The AI Engine has an internal loop that updates Agent Functions registered and indexed.
- 3. It also has another internal loop that creates embeddings of these Functions.
- 4. Upon receiving text, the AI Engine understands and maps the text to Functions.
- 5. It now requests addresses from [Almanac ↗️](/references/contracts/uagents-almanac/almanac-overview) to message these Agents.
- 6. The AI Engine sees that Agent (A) needs some text to perform its functions.
- 7. It finds Secondary Function that can provide the required data.
- 8. It then contacts the the Secondary Function, and the required data is returned.
- 9. Data is passed to Agent (A) which returns a summary of the data.
- 10. The response is then returned to the user on DeltaV.
-
-**Primary and Secondary Functions are fundamental to accomplish users' objectives**.
-
-## Okay, let's build a couple of Agents!
-
-We've got a high-level idea of how this works. Let's build this on Agentverse so that we can get this running on
-DeltaV and see the whole stack connected.
-
-If you've never installed anything for Agent development, checkout these guides:
-
- - [Setup the development environment ↗️](/guides/agents/installing-uagent#development-tools)
- - [Install Agents locally ↗️](/guides/agents/installing-uagent#install-with-pip)
-
-### Create your first agent: the text sentiment agent
-
-We're going to run our agents locally, and set up a Mailbox on Agentverse.
-
-
- Check out the [Utilizing the Agentverse Mailroom service ↗️](/guides/agentverse/utilising-the-mailbox) for a better understanding of the Agentverse Mailroom feature.
-
-
-In this guide, our first agent takes any text and returns a sentiment of contents with **openAI**.
-
-We need to create a Python file for this example.
-We can do this by running:
-
-
-
- ```py copy filename="mac"
- touch sentiment_agent.py
- ```
-
-
- ```py copy filename="windows"
- echo. > sentiment_agent.py
- ```
-
-
-
- ```py copy filename="ubuntu"
- touch sentiment_agent.py
- ```
-
-
-
-
-
-
-
-
-
-
- ```py copy filename="sentiment_agent.py"
-
- from uagents import Agent, Context, Protocol, Model
- from ai_engine import UAgentResponse, UAgentResponseType
- import openai
-
-
- class SentimentResponse(Model):
- text: str
-
-
- SEED_PHRASE = ""
-
- sentimentagent = Agent(
- name="SentimentAgent", # or any name
- seed=SEED_PHRASE,
- mailbox=True
- )
-
- print(sentimentAgent.address)
-
- content_protocol = Protocol("text sentiment analysis")
-
-
- def get_sentiment(text):
- response = openai.chat.completions.create(
-
- messages=[{
- "role": "user",
- "content": f"Sentiment analysis of the following text:\n{text}\n",
- }], model=("gpt-3.5-turbo"))
-
- return response.choices[0].message.content
-
-
- @content_protocol.on_message(model=SentimentResponse, replies={UAgentResponse})
- async def sentiment(ctx: Context, sender: str, msg: SentimentResponse):
- sentiment = get_sentiment(msg.text)
- await ctx.send(
- sender, UAgentResponse(message=sentiment, type=UAgentResponseType.FINAL)
- )
-
-
- sentimentAgent.include(content_protocol, publish_manifest=True)
- sentimentAgent.run()
-
- ```
-
-
-
-
-
-
-
- Remember that you need to provide the `SEED_PHRASE`, `name`, `seed` and `mailbox` parameters to correctly run this example.
-
-
-Okay, we've got the whole code block above for our first agent. Have a look at list of available packages on the Agentverse [here ↗️](/guides/agentverse/allowed-imports) to get started with Agents development on the Agentverse.
-
-There are a lot of really cool, neat things you need to know from code above. Let's explore it:
-
-
-
-
-
-
-
- ```py copy filename="sentiment_agent.py"
-
- class SentimentResponse(Model):
- text: str
-
-
- SEED_PHRASE = ""
-
- sentimentagent = Agent(
- name="SentimentAgent", # or any name
- seed=SEED_PHRASE,
- mailbox=True
- )
-
- print(sentimentAgent.address)
-
- content_protocol = Protocol("text sentiment analysis")
-
- ```
-
-
-
-
-
-
- - The `class SentimentResponse` defines the structure of the message the agent expects to receive. In this case, each message
- should have `text` variable
-
- - `SEED_PHRASE` is our agents unique seed.
-
- - `OPENAI_API_KEY` is our API key to OpenAI's APIs.
-
-We can now initialize the Agent and define the [Protocol ↗️](/references/uagents/uagents-protocols/agent-protocols). To read more about **Agent objects**, please check out [the reference docs ↗️](/references/uagents/api/agent#agent-objects).
-
-Then, we have the `on_message()` [handler ↗️](/guides/agents/intermediate/handlers):
-
-
-
-
-
-
-
- ```py copy filename="sentiment_agent.py"
-
-
- @content_protocol.on_message(model=SentimentResponse, replies={UAgentResponse})
- async def sentiment(ctx: Context, sender: str, msg: SentimentResponse):
- sentiment = get_sentiment(msg.text)
- await ctx.send(
- sender, UAgentResponse(message=sentiment, type=UAgentResponseType.FINAL)
- )
-
- ```
-
-
-
-
-
-
-We need a way for our Agent to receive messages. We do this by creating a function for our agent to handle all
- incoming messages from other Agents. We use `on_message()` decorator which activates the `sentiment()` function once
- our Agent receives a message matching the `SentimentResponse` message data `Model` we previously defined. Internally
-you can see that `sentiment()` calls `get_sentiment()`, this is useful for you as a developer as this shows that
-calling another function inside a decorated function is easy to do.
-
-We can finally run the Agent at the bottom of the script:
-
-
-
-
-
-
-
- ```py copy filename="sentiment_agent.py"
-
-
- sentimentAgent.include(content_protocol, publish_manifest=True)
- sentimentAgent.run()
-
- ```
-
-
-
-
-
-
-Including the [Protocol ↗️](/guides/agents/intermediate/protocols) in the Agent effectively allows other Agents to know how this Agent expects communication.
-
-You can run this with: `poetry run python sentiment_agent.py`.
-
-You'll see something like `agent1qtc5m8xudkm6gjv98k3kxl3ydzhkhzsfx6pgla0mzlgsawlqkzkvcjh5en2` in the terminal.
-
-Let's use this address to create a **Mailbox** on the Agentverse.
-
-### Creating a Mailbox for Sentiment Agent
-
-A **mailbox** is a service provided by Agentverse that allows Agents to receive messages when they're not running online.
-The `uagents` library will poll for new messages (and old unread ones) when your Agent is running. Pretty handy.
-
-Let's go to [Agentverse ↗️](https://agentverse.ai/) and create a Mailbox for this agent.
-
-First of all, head over to the **My Agents** tab and click on the **Local Agents** tab.
-
-Then, click on **Connect Local Agent** button and insert the **address** of the agent you want to retrieve.
-
-
-
-Let's paste in the Agent's address we printed before to screen.
-
-
-
-Once the Agent will be successfully fetched, add a **Name** to it.
-
-A new **Mailbox API Key** will be provided for the local agent. Let's first copy the new Mailbox API Key and then update the `AGENT_MAILBOX_KEY = "AGENT_MAILBOX_KEY"` inline.
-
-Now, you can restart your agent, and it will be registered to the Mailbox.
-
-Your terminal output will look similar to the following:
-
- ```
- Poetry run python html_summary_agent.py
- agent1XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX4
- INFO: [SentimentAgent]: Manifest published successfully: Text Sentiment
- INFO: [SentimentAgent]: Almanac registration is up to date!
- INFO: [SentimentAgent]: Connecting to mailbox server at agentverse.ai
- INFO: [SentimentAgent]: Mailbox access token acquired
- ```
-
-#### Let's run this agent on DeltaV, it'll be good to test, right?
-
-We're going to need to create an **Agent Function** on Agentverse; to get a comprehensive overview of what Agent Functions visit [our dedicated guide ↗️](/guides/agents/intermediate/agent-functions). To get the idea, an **Agent Function** refers to an Agent enrolled within the Agentverse, and made discoverable to other Agents and users for interaction, which is retrievable through natural language queries. For instance, a Function could be an Agent helping in booking an airplane ticket to some destination. Successfully registered Agent Functions are discoverable and accessible through DeltaV and users can engage with them using natural language queries.
-
-Let's go to the [Agentverse ↗️](https://agentverse.ai/) and head over to the **My Agents** tab and select the Agent we have fetched above through **Connect Local Agent** button. A page will open showing your Agent Profile details.
-
-
-
-Click on **Deploy** tab to start creating an Agent Function retrievable via DeltaV. Provide all the needed information to correctly register the Function. Remember that descriptions need to be as detailed as possible.
-
-The following is the Agent Function for the **SentimentAgent**:
-
-
-
-Really simple just defining what this function does. Simplicity for single function descriptions is good.
-
-Let's head over to DeltaV and communicate with our agent.
-
-I'm going to go ahead and ask:
-
- > "Provide the sentiment from this text "Petrol prices across the UK have hit an average 150.1 pence a litre, reaching the
- highest level since last November, according to the AA motoring group. Data also showed that average diesel prices rose to 158.3 pence a litre on Monday. Experts blamed a rise in oil prices because of tensions in the Middle East, as well as a weaker pound compared to the dollar. The AA predicted drivers would "re-tighten their belts on other spending". While overall inflation - which measures the pace of price rises - has eased, the cost of petrol and diesel both rose in March. "Inflation has been heading downwards at quite some speed but petrol's rebound to 150p a litre leaves a big boulder in the road," said Luke Bosdet, the AA's spokesman on pump prices. Prices are based on data collected by the Competition and Markets Authority (CMA) from nearly 3,000 forecourts and analyzed by market research firm Fuel Prices Online. Data showed that 28.1% of the forecourts were charging at least 150p per litre for petrol on Monday, up from 23.8% a week earlier. But Mr Bosdet predicted that fuel prices are unlikely to be elevated for long with wholesale costs easing a little in recent days, adding that filling up "may not get much worse in the short-term". Oil prices have fallen after they spiked in the wake of Israel's retaliatory attack on Iran last week. Caroline Bain, chief commodities economist at Capital Economics, said: "Given that there will be some lag between spot crude oil prices in financial markets and prices on the forecourt, the latest rise is perhaps not so surprising." While Brent crude - a key benchmark for oil prices internationally - has receded from last week, it is still trading 13% higher at $87 per barrel compared to the start of the year."
-
-Oil is often an issue in UK news. Let's find out the sentiment.
-
-
-
-
-
-DeltaV tells us AI Engine has found an Agent Function for our query, and checks we want to send the information we defined.
-
-
-
-Then, DeltaV get the response from the Agent Function and returns this to the user.
-
-Your Agent running locally should provide a similar output to this one below:
-
- ```
- INFO: [sentiment]: Manifest published successfully: text sentiment analysis
- INFO: [sentiment]: Almanac registration is up to date!
- INFO: [sentiment]: Connecting to mailbox server at agentverse.ai
- INFO: [sentiment]: Mailbox access token acquired
- INFO:httpx:HTTP Request: POST https://api.openai.com/v1/chat/completions "HTTP/1.1 200 OK"
- ```
-
-Okay, take a quick break then let's create the second Agent; it's time to introduce multi-agent workflows ☕.
-
-### Create the Webpage Summary Agent
-
-The next agent in the chain is the **Summary agent**. Let's name the script `web_summary_agent.py`. To do so run:
-
-
-
- ```py copy filename="mac"
- touch web_sentiment_agent.py
- ```
-
-
- ```py copy filename="windows"
- echo. > web_sentiment_agent.py
- ```
-
-
-
- ```py copy filename="ubuntu"
- touch web_sentiment_agent.py
- ```
-
-
-
-
-This Agent has the same structure as the sentiment Agent we previously defined.
-
-Let's take a look.
-
-
-
-
-
-
-
- ```py copy filename="web_sentiment_agent.py"
-
- from langchain.chains.summarize import load_summarize_chain
- from langchain_community.document_loaders import UnstructuredHTMLLoader
- from langchain_openai import ChatOpenAI
- from uagents import Agent, Context, Protocol, Model
- from ai_engine import UAgentResponse, UAgentResponseType
- import requests
- import os
-
-
- class SummaryRequest(Model):
- url: str
-
-
- SEED_PHRASE = ""
- OPENAI_API_KEY = ""
-
- summaryAgent = Agent(
- name="SummaryAgent",
- seed=SEED_PHRASE,
- mailbox=True
- )
-
- summary_protocol = Protocol("Text Summariser")
-
- print(summaryAgent.address)
- print(OPENAI_API_KEY)
-
-
- @summary_protocol.on_message(model=SummaryRequest, replies={UAgentResponse})
- async def summarise(ctx: Context, sender: str, msg: SummaryRequest):
-
-
- r = requests.get(msg.url)
- with open("./temp.html", "w", encoding="utf-8") as f:
- f.write(r.text)
-
- # Step 1: Initialize WebBaseLoader with the given URL
- loader = UnstructuredHTMLLoader("./temp.html")
-
- # Step 2: Load the document
- docs = loader.load()
-
- # Step 3: Load summarization chain
- llm = ChatOpenAI(openai_api_key=OPENAI_API_KEY, temperature=0, model_name="gpt-3.5-turbo-1106")
- chain = load_summarize_chain(llm, chain_type="stuff")
-
- # Step 4: Run the summarization chain on the loaded document
- summarized_content = chain.invoke(docs)
- summarized = summarized_content["input_documents"][0].to_json()
-
- # Step 5: Define the needed dependencies
- dependencies = {
- "langchain": ">=1.0.0",
- "langchain_community": ">=1.0.0",
- "langchain_openai": ">=1.0.0"
- }
-
- result = chain.invoke(docs)
-
- await ctx.send(
- sender,
- UAgentResponse(message=(result["output_text"]), type=UAgentResponseType.FINAL),
- )
-
- summaryAgent.include(summary_protocol, publish_manifest=True)
- summaryAgent.run()
-
- ```
-
-
-
-
-
- Remember that you need to provide the `SEED_PHRASE`, `OPENAI_API_KEY`, `name`, `seed` and `mailbox` parameters to correctly run this example.
-
-
-This Agent is simple again, hopefully you're seeing a pattern here. These Agents while independent of each other can
-compliment one another.
-
-
- Check out the [Communicating with other agents ↗️](/guides/agents/communicating-with-other-agents) guide to check how agents communication works without the AI Engine.
-
-
-Aside from the different logic, the primary difference in `web_summary_agent.py` is that this agent does not rely on a separate function, and wraps the whole logic in the message handler.
-
-Let's run this one too. Again, follow the steps for the previous Agent and go and connect it via a Mailbox Each agent must have a unique [Mailbox ↗️](/guides/agents/intermediate/mailbox)!
-
-## One more Agent Function 🎵
-
-The following is the Function for the **Summary_agent**:
-
-
-
-This one is quite simple, but we are defining this as a Secondary Function. A Secondary Function tells the AI Engine that this function should only be called to support another Agent, and not as a primary response. You can learn more about this in our [guide ↗️](/guides/services/services#primary-and-secondary-functions)
-
-We also need to go and update the Sentiment Agent Function.
-
-
-
-Oh my, that is quite the field description.
-
-> "This agent will return a sentiment score from the provided text.
-This MUST NOT be a URL or something that looks like a webpage address. If one of these is provided the content of
-that must be generated from another subtask.
-Text is the content to be analyzed, this must be a structured body of prose."
-
-We're talking to an LLM and the above should reinforce that. We're telling the AI Engine that this function returns sentiment analysis on text. However, when this function is called, the user could also provide a URL. If a URL is provided then the AI Engine must get that from somewhere else. Let's test this.
-
-## Let's go to DeltaV!
-
-We're hoping here that we can ask for a sentiment of a webpage. You may need to adjust your question, or update field descriptions for this to work perfectly, but in latest this is working for us.
-
-
- We encourage everyone operating on DeltaV to select the **Next Generation** AI Engine personality type. This AI Engine personality stands as a significant personality type offering _enhanced scalability_, _reliability_, and _flexibility_. The major key features include advanced context understanding, improved function recommendations, and the ability to handle multiple dialogue formats.
-
-
-
-
-
-
-
-
-
-
-## What's next?
-
-Thank you for sticking with us on this guide, this guide aims to show you the true potential of an AI system that can execute code at the prompt of a user.
-
-We invite you to dive deeper into the world of Agents, Agentverse and AI Engine by exploring the dedicated documentation and [GitHub ↗️](https://github.com/fetchai/) repository.
-
-Join our [Discord ↗️](https://discord.com/invite/fetchai) and team up with other developers to participate in hackathons, collectively build projects, or simply have fun!
diff --git a/pages/guides/agent-courses/introductory-course.mdx b/pages/guides/agent-courses/introductory-course.mdx
deleted file mode 100644
index 527ddd442..000000000
--- a/pages/guides/agent-courses/introductory-course.mdx
+++ /dev/null
@@ -1,1848 +0,0 @@
-import { Callout } from 'nextra/components'
-import PackageVersion from 'components/package-version'
-import { CodeGroup, CodeSegment, DocsCode, GithubCodeSegment } from "../../../components/code";
-
-# Agents 101
-
-## Overview
-
-Welcome to **Agents 101**! This course is designed to introduce you to the development of Agents, providing a comprehensive guide from foundational concepts to practical implementation. Whether you're a beginner in programming or an experienced developer, this course caters to various skill levels, offering a pathway to create increasingly sophisticated Agents and explore diverse use cases.
-
-If you encounter uncertainties or have questions about specific terms or topics throughout the course, our support team is available on [Discord ↗️](https://discord.gg/fetchai) to assist you.
-
-## Introduction to Agents
-
-In this course, you'll delve into the world of Agents using the [uAgents Framework ↗️](/concepts/agents/agents). Agents are programs able to operate autonomously within decentralized landscapes, aligned with user-defined objectives. These agents have the ability to connect, search, transact, establish dynamic markets and so on. By leveraging artificial intelligence, API calls, blockchain technology, and business logic, Agents automate multiple workflows. The aim is to facilitate interactions with their environment and other networked agents without human intervention.
-
-## Set up your development environment 🛠️
-### Prerequisites
-
-Before embarking on this course, ensure your machine meets the following requirements:
-
- 1. **Python 3.8+**: download and install Python from [Python's official website ↗️](https://www.python.org/downloads/)
- 2. **Preferred IDE**: Visual Studio Code or PyCharm (alternative options like Notepad are feasible).
-
-### Set up development tools
-#### Installing Homebrew
-
-**Homebrew** streamlines software installations on MacOS via the command line. To install and update Homebrew, execute the following commands:
-
- ```
- /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
- ```
-
-You can verify it [here ↗️](https://brew.sh/). Let's then ensure Homebrew is updated:
-
- ```
- brew update
- ```
-
-
- For more information on Homebrew explore their [website ↗️](https://brew.sh/).
-
-
-#### Installing PyEnv
-
-Now, you need to install **PyEnv**. It is a simple tool to manage multiple versions of Python. Run:
-
- ```
- brew install pyenv
- ```
-
-Once you have installed PyEnv you can configure the shell environment:
-
- ```
- echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.zshrc
- echo 'command -v pyenv >/dev/null || export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.zshrc
- echo 'eval "$(pyenv init -)"' >> ~/.zshrc
- ```
-
-
- These commands configure your shell environment (specifically the **Zsh shell**) to work with PyEnv. These commands set up environment variables, modify the PATH, and initialize PyEnv so that you can easily manage and switch between different Python versions. You can verify all steps [here ↗️](https://github.com/pyenv/pyenv#installation).
-
-
-You are now ready to **install Python** if you haven't done it yet. You need to install a version of Python 3.8 or above (for this example, we use version 3.10):
-
- ```
- pyenv install 3.10
- ```
-
-You can get help or check a command insights by running:
-
- ```
- pyenv help
- ```
-
-Let's now ensure the **global version of Python** you are working with is not the default one in the system. Run:
-
- ```
- pyenv global 3.10 # this sets the global interpreter
- pyenv versions # this verifies if it is set up correctly
- ```
-
-#### Installing Poetry
-
-You now need to install **Poetry**. Poetry is used for managing Python project dependencies, handling virtual environments, packaging, and publishing Python libraries or applications.
-
-You can install Poetry by running the following command:
-
- ```
- curl -sSL https://install.python-poetry.org | python3 -
- ```
-
-
- If you would like to learn more about Poetry, visit the [website ↗️](https://python-poetry.org/docs/#installation) for further information.
-
-
-#### Initialize your project with Poetry
-
-You now have all necessary tools installed. You are ready to initialize your project! Let's create a working directory and initialize Poetry 🎉.
-
-First, you need to create a working directory for your project using `mkdir` command. Then, you will need to change directory to this one, using `cd` command:
-
- ```
- mkdir development/agent-demo
- cd development/agent-demo
- ```
-
-You can ensure you are in the correct directory by checking your current path:
-
- ```
- pwd
- # Example output: /Users/Jessica/Documents
- ```
-
-If you are happy with the install location for the project, go ahead and **initialize Poetry**:
-
- ```
- poetry init
- ```
-
-
- Follow the setup wizard to provide details including project name, version, author, license, and select dependencies (e.g., `uagents`).
-
-
-Once you complete the initialization, run:
-
- ```
- poetry install
- ```
-
-This command will install the dependencies specified in the **pyproject.toml** file.
-
-**Congratulations! You've completed the installation process. You're now all set to embark on creating your first AI Agent!**
-
-## Overview of the uAgents Framework
-
-The [uAgents Framework ↗️](/concepts/agents/agents) provides the essential infrastructure for creating and deploying Agents within the ASI Ecosystem. It offers a comprehensive toolkit, protocols, and functionalities crucial for developing autonomous agents. The uAgents Framework is integrated with several components of the ASI Ecosystem, including the [AI Engine ↗️](/concepts/ai-engine/ai-engine-intro), the [Almanac contract ↗️](/references/contracts/uagents-almanac/almanac-overview) and the [Agentverse ↗️](/concepts/agent-services/agentverse-intro).
-
-
- Check out the official [uAgents Python package ↗️](https://pypi.org/project/uagents/) and start developing your ideas using this library!
-
- Current version of the uAgents package is .
-
-
-Check out the [uAgents Framework installation guide ↗️](/guides/agents/getting-started/installing-uagent) if you wish to get started immediately with Agents creation using the uAgents toolset!
-
-### Core concepts
-#### Addresses
-
-Agents are identified by **two types of addresses**, serving as identifiers for each agent within the ASI Ecosystem:
-
- 1. **uAgent Address**: the primary agent identifier; it allows it to interact with other agents, exchange messages, and participate in decentralized network activities
-
- 2. **Fetch Address**: this cryptographic public address is linked to the agent and its wallet on the Fetch.ai blockchain; it enables various functionalities, including interacting with the [Fetch ledger ↗️](/concepts/fetch-network/ledger/intro), registering in the Almanac contract and performing operations, including token or asset transfers on the blockchain.
-
-
- Check out the following [guide ↗️](/guides/agents/getting-uagent-address) to learn more on Agents' addresses.
-
-
-#### Storage
-
-Agents can store information in **JSON files** that they can freely retrieve when needed. Storage plays a critical role in maintaining agent state, retaining past interactions, and facilitating informed decision-making based on historical data.
-
-
- Discover more about agents' storage functions through our [Using agents storage function ↗️](/guides/agents/storage-function) guide or the [agents storage ↗️](/references/uagents/uagents-protocols/storage) documentation. If you are new to JSON, please see an example [here ↗️](https://www.w3schools.com/whatis/whatis_json.asp).
-
-
-#### Protocols
-
-The uAgents Framework provides comprehensive support for the organization of message types and their handlers within **protocols**. Protocols are sets of rules that govern the transmission, reception and interpretation of data between agents. They define the communication format, timing, sequence and error handling. Protocols enable standardized communication and ensure accurate and reliable data exchange. Agents using the same protocol can communicate directly with each other.
-
-
- If you want to become an expert in Fetch.ai's agent technology, we strongly recommend that you check our [protocols ↗️](/references/uagents/uagents-protocols/agent-protocols) documentation.
-
-
-#### Exchange protocol
-
-The **Exchange Protocol** facilitates efficient communication between agents by using standardized messaging techniques. Messages are packed in envelopes which are encoded and transmitted to specific endpoints via HTTP. Messages consist of key-value pairs (in JSON format) and are packed in envelopes with metadata. **Envelopes** contain:
-
- - Sender and recipient addresses.
- - Message schema.
- - Payload.
- - Expiration time.
- - Signature for authentication.
-
-The exchange protocol uses a standardized `HTTP 1.1 POST /submit` endpoint for message processing and expects JSON formatted data. These details ensure consistent and standardized communication within the Fetch.Agents ecosystem.
-
-
- For more information, see our [Exchange Protocol ↗️](/references/uagents/uagents-protocols/exchange-protocol) documentation.
-
-
-#### Almanac contract, registering, searching and discovery
-
-The [Almanac ↗️](/references/contracts/uagents-almanac/almanac-overview) contract is an important component in ASI Ecosystem. It operates as a blockchain-based repository where agents register, exchange information and establish communication. Registration in the Almanac is mandatory so that agents can participate in remote interactions and become discoverable through the [Agentverse Explorer ↗️](/concepts/agent-services/agent-explorer).
-
-Agents keep their registrations up-to-date within certain block limits to ensure the accuracy and relevance of their data. Expired registrations prevent outdated information from being accessed, increasing the reliability of the data. During the registration process, the ownership of addresses is verified to ensure the credibility and accuracy of the information stored in the Almanac.
-
-The agents registered in the Almanac provide service endpoints for remote communication, which contain weighted parameters that enable effective interaction. As a central hub, the Almanac facilitates the discovery of endpoints based on these assigned weights. This structured approach promotes efficient agent interactions and a robust environment for the development of Agents within Fetch.ai's decentralized network.
-
-
- Check out the [Registering in the Almanac contract ↗️](/guides/agents/register-in-almanac) guide and the [Registration and endpoints weighting ↗️](/references/contracts/uagents-almanac/endpoints) for additional information on the registration process.
-
-
-## Coding and implementation
-### Create your first agent
-
-Creating your first agent is a straightforward process. First of all, we need to create a Python file for this example. We can do this by running:
-
-
-
- ```py copy filename="mac"
- touch alice_agent.py
- ```
-
-
- ```py copy filename="windows"
- echo. > alice_agent.py
- ```
-
-
-
- ```py copy filename="ubuntu"
- touch alice_agent.py
- ```
-
-
-
-
-We can now code our agent. Let's start by importing the required modules. In our case, we would need to import the `Agent` module from the `uagents` library, and proceed to instantiate the agent by providing a `name`. The following code exemplifies the creation of the simplest possible agent:
-
-
-
-
-
-
-
- ```py copy filename="alice_agent.py"
-
- # Import the required classes
- from uagents import Agent, Context
-
- agent = Agent(name="alice", seed="alice recovery phrase")
-
-
- # Provide your Agent with a job
- @agent.on_event("startup")
- async def introduce_agent(ctx: Context):
- ctx.logger.info(f"Hello, I'm agent {agent.name} and my address is {agent.address}.")
-
-
- # This constructor simply ensure that only this script is running
- if __name__ == "__main__":
- agent.run()
-
- ```
-
-
-
-
-
-
-You can run this with `poetry run python alice_agent.py` but it won't do much, yet!
-
-
- If you're not too familiar with classes in Python, take a look [w3schools Python classes ↗️](https://www.w3schools.com/python/python_classes.asp).
-
-
-Check out this [guide ↗️](/guides/agents/getting-started/create-a-uagent) here for a more in-depth overview of all parts of the code provided above.
-
-### Create a second agent and start an interaction
-
-Let's get Alice to do something! We're going to get Alice, on start up, to introduce itself and provide its address by printing both, on the terminal window. We can add a `on_event("startup")` decorator to make the Agent run the defined function when it is run.
-
-Let's update `alice_agent.py` with the code snippet below:
-
-
-
-
-
-
-
- ```py copy filename="alice_agent.py"
-
- # Import the required classes
- from uagents import Agent, Context
-
- agent = Agent(name="alice", seed="alice recovery phrase")
-
-
- # Provide your Agent with a job
- @agent.on_event("startup")
- async def introduce_agent(ctx: Context):
- ctx.logger.info(f"Hello, I'm agent {agent.name} and my address is {agent.address}.")
-
-
- # This constructor simply ensure that only this script is running
- if __name__ == "__main__":
- agent.run()
-
- ```
-
-
-
-
-
-
-Decorators are moderately advanced in Python, but in this guide all you need to know is that they're there so that the agent knows how to act on the declared decorated functions. For additional information on decorators, check out the following resources: [Primer on Python decorators ↗️](https://realpython.com/primer-on-python-decorators/) and [Agent Handlers ↗️](/guides/agents/intermediate/handlers) for additional information on decorators within the uAgents Framework.
-
-In our example above, the `on_event()` decorator specifies that the agent should run an `introduce_agent()` function when the agent starts up. This function will then return a message presenting the agent with its name and address by using the `Context` class, which is used to retrieve the agent's related name and address using the `agent.name` and `agent.address` methods.
-
-Let's run the `alice_agent.py` script again. Run: `poetry run python alice_agent.py`
-
-This time, the output will be:
-
- ```
- Hello, I'm agent alice and my address is agent1qww3ju3h6kfcuqf54gkghvt2pqe8qp97a7nzm2vp8plfxflc0epzcjsv79t.
- ```
-
-### Printing agent's addresses
-
-Sometimes, we just need to see what a value looks like. We can quickly do so in Python by using the `print()` in-built function. As we have mentioned earlier, every AI Agent is identified by two addresses within the uAgents Framework: **uAgent** and **ASI Network** addresses. We have showed above how to check for an uAgent address using the `agent.address` method of the `Context` class. Let's now print them in the console to see their differences using the `print()` function:
-
-
-
-
-
-
-
- ```py copy filename="address.py"
-
- from uagents import Agent
-
- agent = Agent(name="alice")
-
- print("uAgent address: ", agent.address)
- print("ASI network address: ", agent.wallet.address())
-
- ```
-
-
-
-
-
-
-The output of the above would look similar to:
-
- ```
- uAgent address: agent1qww3ju3h6kfcuqf54gkghvt2pqe8qp97a7nzm2vp8plfxflc0epzcjsv79t
- ASI network address: fetch1454hu0n9eszzg8p7mvan3ep7484jxl5mkf9phg
- ```
-
-
- Check out our [Getting an agent addresses ↗️](/guides/agents/getting-uagent-address) guide for an in-depth understanding of these topics.
-
-
-### Agents and interval tasks
-
-**Interval tasks** are tasks or set of instructions executed at predefined time intervals. These are useful for automating repetitive tasks, scheduling background processes, or managing periodic activities in applications. Setting up interval tasks for agents is a great way to harness their potential and streamline processes including bidding, searching, data processing, job scheduling and more.
-
-If you want to create an interval task, you need to use an `on_interval()` decorator to set up an interval with a timer that triggers the task repetition. As an introductory example, we can consider an agent periodically printing hello and its name on the console. Check out the following [resource ↗️](/guides/agents/intermediate/handlers) for a better understanding of **Agent handlers and decorators** in the uAgents Framework.
-
-In this case, we apply the decorator to a `say_hello()` function which will be repeated at the specified time interval:
-
-
-
-
-
-
-
- ```py copy filename="interval_task.py"
-
- from uagents import Agent, Context
-
- agent = Agent(name="agent", seed="alice recovery phrase")
-
-
- @agent.on_interval(period=2.0)
- async def say_hello(ctx: Context):
- ctx.logger.info(f'hello, my name is {agent.name}')
-
-
- if __name__ == "__main__":
- agent.run()
-
- ```
-
-
-
-
-
-
-The output will be printed on your terminal every 2 seconds using the `ctx.logger.info()` method of the `Context` class.
-
-
- The `Context` class in the `uagents` library plays a central role by overseeing message handling and serving as a central hub for essential agent functionalities such as storage, wallet, ledger, and identity management.
-
-
-The output would look as follows:
-
- ```
- hello, my name is agent
- hello, my name is agent
- hello, my name is agent
- ```
-
-### Agent interactions and interval tasks
-
-We can now introduce a second agent to demonstrate how two agents can interact with one another. Considering the previous example, we create two agents, each one with a name and seed phrase, and enable them to periodically engage with each other. We need to introduce the `Bureau` class which enables agents, within the same program, to be run together from the same script.
-
-Let's create a new Python file for these agents:
-
-
-
- ```py copy filename="mac"
- touch duo_agent.py
- ```
-
-
- ```py copy filename="windows"
- echo. > duo_agent.py
- ```
-
-
-
- ```py copy filename="ubuntu"
- touch duo_agent.py
- ```
-
-
-
-
-The script will look as follows:
-
-
-
-
-
-
-
- ```py copy filename="duo_agent.py"
-
- from uagents import Agent, Context, Bureau
-
- alice = Agent(name="alice", seed="alice recovery phrase")
- bob = Agent(name="bob", seed="bob recovery phrase")
-
-
- @alice.on_interval(period=2.0)
- async def say_hello(ctx: Context):
- ctx.logger.info(f'Hello, my name is {alice.name}')
-
-
- @bob.on_interval(period=2.0)
- async def say_hello(ctx: Context):
- ctx.logger.info(f'Hello, my name is {bob.name}')
-
-
- bureau = Bureau()
- bureau.add(alice)
- bureau.add(bob)
-
- if __name__ == "__main__":
- bureau.run()
-
- ```
-
-
-
-
-
-
-You can now run the script: `poetry run python duo_agent.py`.
-
-The output would look as follows:
-
- ```
- [alice] Hello, my name is alice
- [ bob] Hello, my name is bob
- [alice] Hello, my name is alice
- [ bob] Hello, my name is bob
- [alice] Hello, my name is alice
- [ bob] Hello, my name is bob
- ```
-
-Check out the following guides for a better understanding of all above topics:
-
- - [What's an Agent ↗️](/guides/agents/getting-started/whats-an-agent)
- - [Create your first Agent ↗️](/guides/agents/getting-started/create-a-uagent)
- - [Agent Addresses ↗️](/guides/agents/getting-started/getting-uagent-address)
- - [Agent Handlers ↗️](/guides/agents/intermediate/handlers)
- - [Bureau ↗️](/guides/agents/intermediate/bureau)
-
-### Agent communication
-
-We can now show how to enable effective communication between different agents. To do so, we need to introduce the `Model` class which allows to create a structured message format for messages to be exchanged between the agents.
-
-Let's create a new script for this example:
-
-
-
- ```py copy filename="mac"
- touch agent_communication.py
- ```
-
-
- ```py copy filename="windows"
- echo. > agent_communication.py
- ```
-
-
-
- ```py copy filename="ubuntu"
- touch agent_communication.py
- ```
-
-
-
-
-We can now define the `Message` data model and our two agents:
-
-
-
-
-
-
-
- ```py copy filename="agent_communication.py"
-
- from uagents import Agent, Bureau, Context, Model
-
-
- class Message(Model):
- message: str
-
-
- alice = Agent(name="alice", seed="alice recovery phrase")
- bob = Agent(name="bob", seed="bob recovery phrase")
-
- ```
-
-
-
-
-
-
-We need to define a function for `alice` to send messages to `bob` periodically. We can do this by defining a `send_message()` function using the `Context` class and make `alice` send a message to `bob` on an interval:
-
-
-
-
-
-
-
- ```py copy filename="agent_communication.py"
-
- @alice.on_interval(period=3.0)
- async def send_message(ctx: Context):
- await ctx.send(bob.address, Message(message="hello there bob"))
-
- ```
-
-
-
-
-
-
-We then need a way for `bob` to receive these messages. We can do this by creating a function for `bob` to handle all incoming messages from other agents. We can do this with a `on_message()` decorator that will activate the `message_handler()` function once `bob` receives a message matching the `Message` data model we previously defined:
-
-
-
-
-
-
-
- ```py copy filename="agent_communication.py"
-
- @bob.on_message(model=Message)
- async def bob_message_handler(ctx: Context, sender: str, msg: Message):
- ctx.logger.info(f"Received message from {sender}: {msg.message}")
- await ctx.send(alice.address, Message(message="hello there alice"))
-
- ```
-
-
-
-
-
-
-We then need to define a message handler function for `alice` to handle response messages from `bob`. We do so using a `on_message()` decorator:
-
-
-
-
-
-
-
- ```py copy filename="agent_communication.py"
-
- @alice.on_message(model=Message)
- async def alice_message_handler(ctx: Context, sender: str, msg: Message):
- ctx.logger.info(f"Received message from {sender}: {msg.message}")
-
- ```
-
-
-
-
-Finally, we need to add both agents to the `Bureau` in order to run them from the same script:
-
-
-
-
-
-
-
- ```py copy filename="agent_communication.py"
-
- bureau = Bureau()
- bureau.add(alice)
- bureau.add(bob)
-
- if __name__ == "__main__":
- bureau.run()
-
- ```
-
-
-
-
-
-
-The overall script would be:
-
-
-
-
-
-
-
- ```py copy filename="agent_communication.py"
-
- from uagents import Agent, Bureau, Context, Model
-
-
- class Message(Model):
- message: str
-
-
- alice = Agent(name="alice", seed="alice recovery phrase")
- bob = Agent(name="bob", seed="bob recovery phrase")
-
-
- @alice.on_interval(period=3.0)
- async def send_message(ctx: Context):
- await ctx.send(bob.address, Message(message="hello there bob"))
-
-
- @bob.on_message(model=Message)
- async def bob_message_handler(ctx: Context, sender: str, msg: Message):
- ctx.logger.info(f"Received message from {sender}: {msg.message}")
- await ctx.send(alice.address, Message(message="hello there alice"))
-
-
- @alice.on_message(model=Message)
- async def alice_message_handler(ctx: Context, sender: str, msg: Message):
- ctx.logger.info(f"Received message from {sender}: {msg.message}")
-
-
- bureau = Bureau()
- bureau.add(alice)
- bureau.add(bob)
-
- if __name__ == "__main__":
- bureau.run()
-
- ```
-
-
-
-
-We can now run the script. Just run: `poetry run python agent_communication.py` in your terminal.
-
-The output would look as follows:
-
- ```
- [alice]: Received message from agent1q0mau8vkmg78xx0sh8cyl4tpl4ktx94pqp2e94cylu6haugt2hd7j9vequ7: hello there alice
- [ bob]: Received message from agent1qww3ju3h6kfcuqf54gkghvt2pqe8qp97a7nzm2vp8plfxflc0epzcjsv79t: hello there bob
- [alice]: Received message from agent1q0mau8vkmg78xx0sh8cyl4tpl4ktx94pqp2e94cylu6haugt2hd7j9vequ7: hello there alice
- [ bob]: Received message from agent1qww3ju3h6kfcuqf54gkghvt2pqe8qp97a7nzm2vp8plfxflc0epzcjsv79t: hello there bob
- [alice]: Received message from agent1q0mau8vkmg78xx0sh8cyl4tpl4ktx94pqp2e94cylu6haugt2hd7j9vequ7: hello there alice
- [ bob]: Received message from agent1qww3ju3h6kfcuqf54gkghvt2pqe8qp97a7nzm2vp8plfxflc0epzcjsv79t: hello there bob
- ```
-
-Checkout the following documentation and resources for a better understanding of the above topics:
-
- - [What's an Agent ↗️](/guides/agents/getting-started/whats-an-agent)
- - [Create your first Agent ↗️](/guides/agents/getting-started/create-a-uagent)
- - [Agent Addresses ↗️](/guides/agents/getting-started/getting-uagent-address)
- - [Agent Handlers ↗️](/guides/agents/intermediate/handlers)
- - [Bureau ↗️](/guides/agents/intermediate/bureau)
-
-### Registering your Agents to the Open Marketplace
-
-Agent registration in the [Almanac ↗️](/references/contracts/uagents-almanac/almanac-overview) contract enables Agents discoverability and remote Agent communication. When Agents register to the Almanac, they become part of the Open Marketplace and become available for interactions with other users and Agents registered in the contract. To register, Agents must pay a small fee (not currently implemented) that covers the cost of Almanac use.
-
-Agents can communicate by querying the Almanac and retrieving an HTTP [endpoint ↗️](/references/contracts/uagents-almanac/endpoints) from the recipient Agent. Therefore, we need to specify the service endpoints when defining an Agent at registration.
-
-
- HTTP (Hypertext Transfer Protocol) service endpoints are specific locations or URLs (Uniform Resource Locators) on a web server where clients can send HTTP requests to interact with resources or services provided by the server. These endpoints define the entry points for various operations or functions offered by a web service or application.
-
-
-Let's create a Python script for this example:
-
-
-
- ```py copy filename="mac"
- touch almanac_registration.py
- ```
-
-
- ```py copy filename="windows"
- echo. > almanac_registration.py
- ```
-
-
-
- ```py copy filename="ubuntu"
- touch almanac_registration.py
- ```
-
-
-
-
-We will have what follows:
-
-
-
-
-
-
-
- ```py copy filename="almanac_registration.py"
-
- from uagents import Agent, Context, Protocol
-
- agent = Agent(
- name="alice",
- port=8000,
- seed="alice secret phrase",
- endpoint=["http://127.0.0.1:8000/submit"],
- )
-
- @agent.on_interval(period=3)
- async def hi(ctx: Context):
- ctx.logger.info(f"Hello")
-
-
- agent.run()
-
- ```
-
-
-
-
-
-
-Here, we defined a local http address, but you could also define a remote address to allow agent communication over different machines through the internet. Importantly, make sure to add a seed phrase to your Agent, so you don't have to fund different addresses each time you run your agent. The `fund_agent_if_low` is used on the Testnet to make sure your Agent has enough funds in its wallet to register and operate correctly.
-
-
- A seed phrase is a series of random words (typically 12 or 24) that provide the data needed to recover a lost or broken crypto wallet. It is also known as a mnemonic phrase and is best understood as a security measure for self-custody of digital assets. Agents have a crypto wallet address, and having the seed phrase enables the restoration of an agent's wallet address.
-
-
-To run the script use the `poetry run python almanac_registration.py` command.
-
-Check out the following [guide ↗️](/guides/agents/advanced/register-in-almanac) for an in-depth overview of the Almanac registration process.
-
-### Remote Agent communication
-
-Agents can also interact **remotely**. To achieve a remote communication, we simply need an Agent's address and query the rest of its information in the Almanac contract. You can create two agents operating on separate ports and terminals within the same device; this mirrors a real-world scenario in which agents communicate across different geographic locations.
-
-In this example, we provide scripts for two agents. To establish a line of remote communication, both agents need to be registered on the Almanac contract and need to have non-zero balances in their wallet addresses.
-
-We can start with `alice` agent. Let's create a Python script for it:
-
-
-
- ```py copy filename="mac"
- touch remote_alice.py
- ```
-
-
- ```py copy filename="windows"
- echo. > remote_alice.py
- ```
-
-
-
- ```py copy filename="ubuntu"
- touch remote_alice.py
- ```
-
-
-
-
-We first import the required modules. We then use the `Model` class to define a `Message` data model for messages to be exchanged between our Agents. We also need to provide Bob's address as a recipient address for reference. We can then create our Agent `alice`, by providing the needed information for registration. We need to make sure it has enough balance in its wallet. We then proceed and define its functions. Remember that you need to provide the `RECIPIENT_ADDRESS`, `name`, `port`, `seed` and `endpoint` parameters to correctly run this Agent and code.
-
-The script would be as follows:
-
-
-
-
-
-
-
- ```py copy filename="remote_alice.py"
-
- from uagents import Agent, Context, Model
- from uagents.setup import fund_agent_if_low
-
-
- class Message(Model):
- message: str
-
-
- RECIPIENT_ADDRESS = "agent1q2kxet3vh0scsf0sm7y2erzz33cve6tv5uk63x64upw5g68kr0chkv7hw50"
-
- agent = Agent(
- name="alice",
- port=8000,
- seed="alice secret phrase",
- endpoint=["http://127.0.0.1:8000/submit"],
- )
-
- fund_agent_if_low(agent.wallet.address())
-
-
- @agent.on_interval(period=2.0)
- async def send_message(ctx: Context):
- await ctx.send(RECIPIENT_ADDRESS, Message(message="hello there bob"))
-
-
- @agent.on_message(model=Message)
- async def message_handler(ctx: Context, sender: str, msg: Message):
- ctx.logger.info(f"Received message from {sender}: {msg.message}")
-
-
- if __name__ == "__main__":
- agent.run()
-
- ```
-
-
-
-
-
-
-Similarly, we need to define a script for `bob` so to create a remote communication with `alice` Agent. Let's create a Python script for `bob`:
-
-
-
- ```py copy filename="mac"
- touch remote_bob.py
- ```
-
-
- ```py copy filename="windows"
- echo. > remote_bob.py
- ```
-
-
-
- ```py copy filename="ubuntu"
- touch remote_bob.py
- ```
-
-
-
-
-Instead of creating and manually writing out the same script we can copy and rename Alice's script and modify the Agent's `name`, `seed`, `port`, decorator as well as the message content:
-
-
-
-
-
-
-
- ```py copy filename="remote_bob.py"
-
- from uagents import Agent, Context, Model
-
-
- class Message(Model):
- message: str
-
-
- agent = Agent(
- name="bob",
- port=8001,
- seed="bob secret phrase",
- endpoint=["http://127.0.0.1:8001/submit"],
- )
-
-
- @agent.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 alice"))
-
-
- if __name__ == "__main__":
- agent.run()
-
- ```
-
-
-
-
-
-
-Remember that you need to provide the `name`, `port`, `seed` and `endpoint` parameters to correctly run this Agent!
-
-In different terminal windows, first run `remote_bob.py` and then `remote_alice.py`. They will register automatically in the Almanac contract using their funds. The received messages will print out in each terminal. In order to run the two Agents in parallel terminals use the `poetry run python remote_alice.py` and `poetry run python remote_bob.py`. The expected output would be:
-
- **Alice**:
-
- ```
- [alice]: Received message from agent1q2kxet3vh0scsf0sm7y2erzz33cve6tv5uk63x64upw5g68kr0chkv7hw50: hello there alice
- [alice]: Received message from agent1q2kxet3vh0scsf0sm7y2erzz33cve6tv5uk63x64upw5g68kr0chkv7hw50: hello there alice
- [alice]: Received message from agent1q2kxet3vh0scsf0sm7y2erzz33cve6tv5uk63x64upw5g68kr0chkv7hw50: hello there alice
- ```
-
- **Bob**:
-
- ```
- [ bob]: Received message from agent1qdp9j2ev86k3h5acaayjm8tpx36zv4mjxn05pa2kwesspstzj697xy5vk2a: hello there bob
- [ bob]: Received message from agent1qdp9j2ev86k3h5acaayjm8tpx36zv4mjxn05pa2kwesspstzj697xy5vk2a: hello there bob
- [ bob]: Received message from agent1qdp9j2ev86k3h5acaayjm8tpx36zv4mjxn05pa2kwesspstzj697xy5vk2a: hello there bob
- ```
-
-
- Checkout our [Communicating with other agents ↗️](/guides/agents/communicating-with-other-agents) guide for a deeper explanation of the concepts surrounding Agents communication both **locally** and **remotely**.
-
-
-
-### Agents and storage
-
-Agents within the uAgents Framework have the ability to store information locally within a JSON file. This ensures data retrieval as needed. This storage functionality serves as a fundamental component for agents to maintain a state, recollect prior interactions, and base decisions on historical data.
-
-The aim behind integrating storage features is to empower agents to preserve and leverage information over time, facilitating the recollection of past interactions and context for more informed decision-making. This capacity to learn from experiences enables agents to adapt and refine their behavior and decision processes.
-
-Retrieving or setting storage information within the Framework is achieved through two methods:
-
- - `ctx.storage.get()` for retrieval.
- - `ctx.storage.set()` for setting data.
-
-An example is provided below. In this example we have a full script for an agent holding a number, incrementing it by one and saving the new number to its storage.
-
-We first create the Python file containing the script. Run:
-
-
-
- ```py copy filename="mac"
- touch storage.py
- ```
-
-
- ```py copy filename="windows"
- echo. > storage.py
- ```
-
-
-
- ```py copy filename="ubuntu"
- touch storage.py
- ```
-
-
-
-
-The script for this example is:
-
-
-
-
-
-
-
- ```py copy filename="storage.py"
-
- from uagents import Agent, Context
-
- agent = Agent(name="alice", seed="alice recovery phrase")
-
-
- @agent.on_interval(period=1.0)
- async def on_interval(ctx: Context):
- current_count = ctx.storage.get("count") or 0
-
- ctx.logger.info(f"My count is: {current_count}")
-
- ctx.storage.set("count", current_count + 1)
-
-
- if __name__ == "__main__":
- agent.run()
-
- ```
-
-
-
-
-We can then run the script: `poetry run python storage.py`
-The output would be:
-
- ```
- [alice]: My count is: 1
- [alice]: My count is: 2
- [alice]: My count is: 3
- ...
- ```
-
-### Booking a table at a restaurant
-
-We now want to show how to set up the code to create a **restaurant booking service with two **Agents**: a `restaurant` with tables available and a `user` requesting a table availability.
-
-We can do this by defining 2 specific **Protocols**: one for table querying (i.e., `Table querying protocol`) and one for table booking (i.e., `Table booking protocol`). We then need to define two agents, `restaurant` and `user`, which will make use of the protocols to query and book a table.
-
-Check out the following [resource ↗️](/guides/agents/intermediate/protocols) for a better understanding of Agents Protocols.
-
-We can start by writing the code for our two Protocols.
-
-#### Table querying protocol
-
-Let's start by defining the protocol for querying availability of tables at the restaurant. We start by importing the necessary classes and defining the message data models for types of messages being handled. We then proceed and create an instance of the `Protocol` class and name it `query_proto`:
-
-
-
-
-
-
-
- ```py copy filename="query.py"
-
- from typing import List
-
- from uagents import Context, Model, Protocol
-
-
- class TableStatus(Model):
- seats: int
- time_start: int
- time_end: int
-
-
- class QueryTableRequest(Model):
- guests: int
- time_start: int
- duration: int
-
-
- class QueryTableResponse(Model):
- tables: List[int]
-
-
- class GetTotalQueries(Model):
- pass
-
-
- class TotalQueries(Model):
- total_queries: int
-
- ```
-
-
-
-
-Here, we defined different messages data models:
-
- - `TableStatus` represents the status of a table and includes the attributes number of seats, start time, and end time.
- - `QueryTableRequest` is used for querying table availability. It includes information about the number of guests, start time, and duration of the table request.
- - `QueryTableResponse` contains the response to the query table availability. It includes a list of table numbers that are available based on query parameters.
- - `GetTotalQueries` is used to request the total number of queries made to the system.
- - `TotalQueries` contains the response to the total queries request, including the count of total queries made to the system.
-
-Let's then define the message handlers for the `query_proto` protocol:
-
-
-
-
-
-
-
- ```py copy filename="query.py"
-
- query_proto = Protocol(name="RestaurantQueryProtocolExample", version="0.1.0")
-
-
- @query_proto.on_message(model=QueryTableRequest, replies=QueryTableResponse)
- async def handle_query_request(ctx: Context, sender: str, msg: QueryTableRequest):
- tables = {
- int(num): TableStatus(**status)
- for (
- num,
- status,
- ) in ctx.storage._data.items() # pylint: disable=protected-access
- if isinstance(num, int)
- }
-
- available_tables = []
- for number, status in tables.items():
- if (
- status.seats >= msg.guests
- and status.time_start <= msg.time_start
- and status.time_end >= msg.time_start + msg.duration
- ):
- available_tables.append(int(number))
-
- ctx.logger.info(f"Query: {msg}. Available tables: {available_tables}.")
-
- await ctx.send(sender, QueryTableResponse(tables=available_tables))
-
- total_queries = int(ctx.storage.get("total_queries") or 0)
- ctx.storage.set("total_queries", total_queries + 1)
-
-
- @query_proto.on_query(model=GetTotalQueries, replies=TotalQueries)
- async def handle_get_total_queries(ctx: Context, sender: str, _msg: GetTotalQueries):
- total_queries = int(ctx.storage.get("total_queries") or 0)
- await ctx.send(sender, TotalQueries(total_queries=total_queries))
-
- ```
-
-
-
-
-
-
- We define a protocol `query_proto` using the `Protocol` class of `uagents`. It is defined with a `name` and a `version`.
-
- The `handle_query_request()` function is the message handler function defined using the `on_message()` decorator. It handles the `QueryTableRequest` messages and replies with a `QueryTableResponse` message. The handler processes the table availability query based on the provided parameters, checks the table status stored in the agent's storage, and sends the available table numbers as a response to the querying agent.
-
- Additionally, the handler tracks the total number of queries made and increments the count in storage. On the other hand, `handle_get_total_queries()` is the message handler function defined using the `on_query()` decorator. It handles the `GetTotalQueries` query and replies with a `TotalQueries` message containing the total number of queries made to the system. The handler retrieves the total query count from the agent's storage and responds with the count.
-
-The overall script should look as follows:
-
-
-
-
-
-
-
- ```py copy filename="query.py"
-
- from typing import List
-
- from uagents import Context, Model, Protocol
-
-
- class TableStatus(Model):
- seats: int
- time_start: int
- time_end: int
-
-
- class QueryTableRequest(Model):
- guests: int
- time_start: int
- duration: int
-
-
- class QueryTableResponse(Model):
- tables: List[int]
-
-
- class GetTotalQueries(Model):
- pass
-
-
- class TotalQueries(Model):
- total_queries: int
-
-
- query_proto = Protocol(name="RestaurantQueryProtocolExample", version="0.1.0")
-
-
- @query_proto.on_message(model=QueryTableRequest, replies=QueryTableResponse)
- async def handle_query_request(ctx: Context, sender: str, msg: QueryTableRequest):
- tables = {
- int(num): TableStatus(**status)
- for (
- num,
- status,
- ) in ctx.storage._data.items() # pylint: disable=protected-access
- if isinstance(num, int)
- }
-
- available_tables = []
- for number, status in tables.items():
- if (
- status.seats >= msg.guests
- and status.time_start <= msg.time_start
- and status.time_end >= msg.time_start + msg.duration
- ):
- available_tables.append(int(number))
-
- ctx.logger.info(f"Query: {msg}. Available tables: {available_tables}.")
-
- await ctx.send(sender, QueryTableResponse(tables=available_tables))
-
- total_queries = int(ctx.storage.get("total_queries") or 0)
- ctx.storage.set("total_queries", total_queries + 1)
-
-
- @query_proto.on_query(model=GetTotalQueries, replies=TotalQueries)
- async def handle_get_total_queries(ctx: Context, sender: str, _msg: GetTotalQueries):
- total_queries = int(ctx.storage.get("total_queries") or 0)
- await ctx.send(sender, TotalQueries(total_queries=total_queries))
-
- ```
-
-
-
-
-
-
-#### Table booking protocol
-
-We can now proceed by writing the booking protocol script for booking the table at the restaurant. We first need to import the necessary classes and define the message data models. In this case, the booking protocol consists of two message models: `BookTableRequest` and `BookTableResponse`. Then, we create an instance of the `Protocol` class and name it `book_proto` and give it a version:
-
-
-
-
-
-
-
- ```py copy filename="book.py"
-
- from uagents import Context, Model, Protocol
- from .query import TableStatus
-
-
- class BookTableRequest(Model):
- table_number: int
- time_start: int
- duration: int
-
-
- class BookTableResponse(Model):
- success: bool
-
-
- book_proto = Protocol(name="RestaurantBookingProtocolExample", version="0.1.0")
-
- ```
-
-
-
-
-
-
- - `BookTableRequest` represents the request to book a table. It includes attributes: `table_number` to be booked, `time_start`of the booking, and the duration of the booking.
- - `BookTableResponse` contains the response to the table booking request. It includes a boolean attribute success indicating whether the booking was successful or not.
-
-Let's now define the message handler function:
-
-
-
-
-
-
-
- ```py copy filename="book.py"
-
- @book_proto.on_message(model=BookTableRequest, replies=BookTableResponse)
- async def handle_book_request(ctx: Context, sender: str, msg: BookTableRequest):
- tables = {
- int(num): TableStatus(**status)
- for (
- num,
- status,
- ) in ctx.storage._data.items() # pylint: disable=protected-access
- if isinstance(num, int)
- }
- table = tables[msg.table_number]
-
- if (
- table.time_start <= msg.time_start
- and table.time_end >= msg.time_start + msg.duration
- ):
- success = True
- table.time_start = msg.time_start + msg.duration
- ctx.storage.set(msg.table_number, table.dict())
- else:
- success = False
-
- # send the response
- await ctx.send(sender, BookTableResponse(success=success))
-
- ```
-
-
-
-
- The `handle_book_request()` handler first retrieves table statuses from the agent's storage and converts them into a dictionary with integer keys (table numbers) and `TableStatus` values. The `TableStatus` class is imported from the query module. Next, the handler gets the table associated with the requested `table_number` from the tables dictionary. The handler checks if the requested time_start falls within the availability period of the table. If the table is available for the requested booking duration, the handler sets success to `True`, updates the table's `time_start` to reflect the end of the booking, and saves the updated table information in the agent's storage using `ctx.storage.set()`. If the table is not available for the requested booking, the handler sets success to `False`. The handler sends a `BookTableResponse` message back to the sender with the success status of the booking using the `ctx.send()` method.
-
-The overall script should be:
-
-
-
-
-
-
-
- ```py copy filename="book.py"
-
- from uagents import Context, Model, Protocol
- from .query import TableStatus
-
-
- class BookTableRequest(Model):
- table_number: int
- time_start: int
- duration: int
-
-
- class BookTableResponse(Model):
- success: bool
-
-
- book_proto = Protocol(name="RestaurantBookingProtocolExample", version="0.1.0")
-
-
- @book_proto.on_message(model=BookTableRequest, replies=BookTableResponse)
- async def handle_book_request(ctx: Context, sender: str, msg: BookTableRequest):
- tables = {
- int(num): TableStatus(**status)
- for (
- num,
- status,
- ) in ctx.storage._data.items() # pylint: disable=protected-access
- if isinstance(num, int)
- }
- table = tables[msg.table_number]
-
- if (
- table.time_start <= msg.time_start
- and table.time_end >= msg.time_start + msg.duration
- ):
- success = True
- table.time_start = msg.time_start + msg.duration
- ctx.storage.set(msg.table_number, table.dict())
- else:
- success = False
-
- # send the response
- await ctx.send(sender, BookTableResponse(success=success))
-
- ```
-
-
-
-
-#### Restaurant agent
-
-Let's now move forward and create our restaurant agent in a separate file. In this step, we will import the essential classes from the `uagents` library and reintegrate the two protocols (`book_proto` and `query_proto`) we've previously coded:
-
-
-
-
-
-
-
- ```py copy filename="restaurant_agent.py"
-
- from protocols.book import book_proto
- from protocols.query import TableStatus, query_proto
- from uagents import Agent
-
- restaurant = Agent(
- name="restaurant",
- port=8001,
- seed="restaurant recovery phrase",
- endpoint={
- "http://127.0.0.1:8001/submit": {},
- },
- )
-
- ```
-
-
-
-
-
-
-Remember that you need to provide the `name`, `port`, `seed` and `endpoint` parameters to correctly set up the agent. Let's build the `restaurant` agent from above protocols and set the table availability information, by also to storing the `TABLES` information in the `restaurant` agent storage:
-
-
-
-
-
-
-
- ```py copy filename="restaurant_agent.py"
-
- # build the restaurant agent from stock protocols and publish their details
- restaurant.include(query_proto, publish_manifest=True)
- restaurant.include(book_proto, publish_manifest=True)
-
- TABLES = {
- 1: TableStatus(seats=2, time_start=16, time_end=22),
- 2: TableStatus(seats=4, time_start=19, time_end=21),
- 3: TableStatus(seats=4, time_start=17, time_end=19),
- }
-
- for number, status in TABLES.items():
- restaurant.storage.set(number, status.dict())
-
- if __name__ == "__main__":
- restaurant.run()
-
- ```
-
-
-
-
-The `restaurant` agent is now online and ready to receive messages.
-
-The overall script would be as follows:
-
-
-
-
-
-
-
- ```py copy filename="restaurant_agent.py"
-
- from protocols.book import book_proto
- from protocols.query import TableStatus, query_proto
- from uagents import Agent
-
- restaurant = Agent(
- name="restaurant",
- port=8001,
- seed="restaurant recovery phrase",
- endpoint={
- "http://127.0.0.1:8001/submit": {},
- },
- )
-
- # build the restaurant agent from stock protocols and publish their details
- restaurant.include(query_proto, publish_manifest=True)
- restaurant.include(book_proto, publish_manifest=True)
-
- TABLES = {
- 1: TableStatus(seats=2, time_start=16, time_end=22),
- 2: TableStatus(seats=4, time_start=19, time_end=21),
- 3: TableStatus(seats=4, time_start=17, time_end=19),
- }
-
- for number, status in TABLES.items():
- restaurant.storage.set(number, status.dict())
-
- if __name__ == "__main__":
- restaurant.run()
-
- ```
-
-
-
-
-#### User agent
-
-We can now define the script for our `user` agent querying and booking a table at the `restaurant`.
-
-Once we've imported the necessary classes from the `uagents` library and the two protocols we previously defined, we also need the `restaurant` agent's address so for the `user` agent to be able to communicate with it:
-
-
-
-
-
-
-
- ```py copy filename="user_agent.py"
-
- from protocols.book import BookTableRequest, BookTableResponse
- from protocols.query import (
- QueryTableRequest,
- QueryTableResponse,
- )
- from uagents import Agent, Context
-
- RESTAURANT_ADDRESS = (
- "test-agent://agent1qfpqn9jhvp9cg33f27q6jvmuv52dgyg9rfuu37rmxrletlqe7lewwjed5gy"
- )
-
- user = Agent(
- name="user",
- port=8000,
- seed="user recovery phrase",
- endpoint={
- "http://127.0.0.1:8000/submit": {},
- },
- )
-
- ```
-
-
-
-
-Remember that you need to provide the `RESTAURANT_ADDRESS`, `name`, `port`, `seed` and `endpoint` parameters to correctly set up the agent and code. Let's then create the table query to generate the `QueryTableRequest` using the `restaurant` address. Then, we need to create an `on_interval()` function which periodically queries the `restaurant`, asking for the availability of a table given the `table_query` parameters:
-
-
-
-
-
-
-
- ```py copy filename="user_agent.py"
-
- table_query = QueryTableRequest(
- guests=3,
- time_start=19,
- duration=2,
- )
-
-
- @user.on_interval(period=3.0, messages=QueryTableRequest)
- async def interval(ctx: Context):
- completed = ctx.storage.get("completed")
-
- if not completed:
- await ctx.send(RESTAURANT_ADDRESS, table_query)
-
- ```
-
-
-
-
-We then need to define the message handler function for incoming `QueryTableResponse` messages from the `restaurant` agent:
-
-
-
-
-
-
-
- ```py copy filename="user_agent.py"
-
- @user.on_message(QueryTableResponse, replies={BookTableRequest})
- async def handle_query_response(ctx: Context, sender: str, msg: QueryTableResponse):
- if len(msg.tables) > 0:
- ctx.logger.info("There is a free table, attempting to book one now")
- table_number = msg.tables[0]
- request = BookTableRequest(
- table_number=table_number,
- time_start=table_query.time_start,
- duration=table_query.duration,
- )
- await ctx.send(sender, request)
- else:
- ctx.logger.info("No free tables - nothing more to do")
- ctx.storage.set("completed", True)
-
- ```
-
-
-
-
-Let's then define a function which will handle messages from the `restaurant` agent on whether the reservation was successful or not:
-
-
-
-
-
-
-
- ```py copy filename="user_agent.py"
-
- @user.on_message(BookTableResponse, replies=set())
- async def handle_book_response(ctx: Context, _sender: str, msg: BookTableResponse):
- if msg.success:
- ctx.logger.info("Table reservation was successful")
- else:
- ctx.logger.info("Table reservation was UNSUCCESSFUL")
-
- ctx.storage.set("completed", True)
-
-
- if __name__ == "__main__":
- user.run()
-
- ```
-
-
-
-
-The overall script would be:
-
-
-
-
-
-
-
- ```py copy filename="user_agent.py"
-
- from protocols.book import BookTableRequest, BookTableResponse
- from protocols.query import (
- QueryTableRequest,
- QueryTableResponse,
- )
- from uagents import Agent, Context
-
- RESTAURANT_ADDRESS = (
- "test-agent://agent1qfpqn9jhvp9cg33f27q6jvmuv52dgyg9rfuu37rmxrletlqe7lewwjed5gy"
- )
-
- user = Agent(
- name="user",
- port=8000,
- seed="user recovery phrase",
- endpoint={
- "http://127.0.0.1:8000/submit": {},
- },
- )
-
- table_query = QueryTableRequest(
- guests=3,
- time_start=19,
- duration=2,
- )
-
-
- @user.on_interval(period=3.0, messages=QueryTableRequest)
- async def interval(ctx: Context):
- completed = ctx.storage.get("completed")
-
- if not completed:
- await ctx.send(RESTAURANT_ADDRESS, table_query)
-
-
- @user.on_message(QueryTableResponse, replies={BookTableRequest})
- async def handle_query_response(ctx: Context, sender: str, msg: QueryTableResponse):
- if len(msg.tables) > 0:
- ctx.logger.info("There is a free table, attempting to book one now")
- table_number = msg.tables[0]
- request = BookTableRequest(
- table_number=table_number,
- time_start=table_query.time_start,
- duration=table_query.duration,
- )
- await ctx.send(sender, request)
- else:
- ctx.logger.info("No free tables - nothing more to do")
- ctx.storage.set("completed", True)
-
-
- @user.on_message(BookTableResponse, replies=set())
- async def handle_book_response(ctx: Context, _sender: str, msg: BookTableResponse):
- if msg.success:
- ctx.logger.info("Table reservation was successful")
- else:
- ctx.logger.info("Table reservation was UNSUCCESSFUL")
-
- ctx.storage.set("completed", True)
-
-
- if __name__ == "__main__":
- user.run()
-
- ```
-
-
-
-
-We are ready to run the example.
-
-Run the `restaurant` agent and then the `user` agent from different terminals. The output should be as follows:
-
- **Restaurant**:
-
- ```
- [restaurant]: Query: guests=3 time_start=19 duration=2. Available tables: [2].
- ```
-
- **User**:
-
- ```
- [ user]: There is a free table, attempting to book one now
- [ user]: Table reservation was successful
- ```
-
-## From novice to navigator: your course conclusion and beyond!
-
-We appreciate your active participation in our introductory course on Agents! The knowledge you've acquired here forms a robust basis for your future Agents development endeavors.
-
-We invite you to delve deeper into the world of Agents by exploring our dedicated [Agents ↗️](/guides/agents/getting-started/whats-an-agent) documentation, [GitHub ↗️](https://github.com/fetchai/uAgents) and [uAgents Examples ↗️](https://github.com/fetchai/uAgent-Examples) repositories. Also, do not forget to checkout our full list of [Agents guides ↗️](/guides) diving into the development of Agents and concepts explained in this introductory course, but in a more detailed manner.
-
-Also, check out the [Agents 101 for AI Engine ↗️](/guides/agents/getting-started/whats-an-agent) to understand how to integrate the [AI Engine ↗️](/guides/agent-courses/agents-for-ai) within your Agents project.
-
-Join our [Discord ↗️](https://discord.gg/fetchai) and team up with other developers in order to participate in hackathons, collectively build projects, or simply have fun! There, you can not only star the project but also access valuable resources that will enhance your agent development journey. We look forward to seeing your contributions and witnessing your continued growth in the realm of AI and agent-based systems.
diff --git a/pages/guides/agents/_meta.json b/pages/guides/agents/_meta.json
deleted file mode 100644
index f7293e4a4..000000000
--- a/pages/guides/agents/_meta.json
+++ /dev/null
@@ -1,15 +0,0 @@
-{
- "quickstart": {
- "title": "Quickstart",
- "tags": ["Beginner", "Python", "Local"]
- },
- "getting-started": {
- "title": "Getting Started"
- },
- "intermediate": {
- "title": "Intermediate topics"
- },
- "advanced": {
- "title": "Advanced Topics"
- }
-}
diff --git a/pages/guides/agents/advanced/_meta.json b/pages/guides/agents/advanced/_meta.json
deleted file mode 100644
index 0b1e8177e..000000000
--- a/pages/guides/agents/advanced/_meta.json
+++ /dev/null
@@ -1,42 +0,0 @@
-{
- "dialogues": {
- "title": "Introducing dialogues",
- "tags": ["Advanced", "Python", "Dialogues", "DeltaV"],
- "timestamp": true
- },
- "register-in-almanac": {
- "title": "Almanac Contract",
- "tags": ["Advanced", "Python", "Almanac", "Local"],
- "timestamp": true
- },
- "agents-async-loops": {
- "title": "Agents Asynchronous Loops",
- "tags": ["Advanced", "Python", "Communication", "Use Cases", "Local"],
- "timestamp": true
- },
- "agent-envelopes": {
- "title": "Agent Envelopes",
- "tags": ["Advanced", "Python", "Envelopes"],
- "timestamp": true
- },
- "message-verification": {
- "title": "Verify messages with Agents",
- "tags": ["Advanced", "Python", "Communication", "Use Cases", "Local"],
- "timestamp": true
- },
- "utilizing-api-to-build-network-of-task-and-subtask": {
- "title": "Multi-file agent pipeline for AI Engine: Network of Primary and Secondary functions in Agentverse",
- "tags": ["Advanced", "Python", "Functions", "AI Engine", "Local"],
- "timestamp": true
- },
- "localwallet": {
- "title": "Local Wallet",
- "tags": ["Advanced", "Python", "Wallet", "Local"],
- "timestamp": true
- },
- "name-service": {
- "title": "Agents Name Service",
- "tags": ["Advanced", "Python", "Name Service", "Local"],
- "timestamp": true
- }
-}
diff --git a/pages/guides/agents/advanced/agent-envelopes.mdx b/pages/guides/agents/advanced/agent-envelopes.mdx
deleted file mode 100644
index 87f4adafe..000000000
--- a/pages/guides/agents/advanced/agent-envelopes.mdx
+++ /dev/null
@@ -1,56 +0,0 @@
-import { Callout } from 'nextra/components'
-
-# Agent Envelopes in the Fetch.ai uAgents Framework
-
-## Introduction
-
-Within the Fetch.ai uAgents Framework, effective communication between [Agents ↗️](/guides/agents/getting-started/whats-an-agent) is crucial for the execution of complex tasks and exchange of information. To this aim, the **Exchange protocol** is a standardized communication protocol within the Framework that facilitates such interactions. A key component of this protocol are **Envelopes**; these serve as structured containers for messages exchanged between agents.
-
-In particular, envelopes provide a secure and reliable way to exchange messages by encapsulating them along with essential metadata. This metadata includes details about the sender and recipient, the session in which the communication occurs, and other information needed to ensure the integrity and authenticity of the messages. By using envelopes, we ensure that messages are correctly routed, verified, and processed, thereby enabling straightforward interoperability among multiple agents and related functions.
-
-
- Check out the [Exchange protocol ↗️](/references/uagents/uagents-protocols/exchange-protocol) resource for a better comprehension on this topic.
-
-
-## What Are Envelopes?
-
-**Envelopes** are specialized structures used to encapsulate messages in the Exchange protocol. The structure of an envelope can be likened to a physical envelope containing a letter, where the outer envelope holds information such as the sender's and recipient's addresses, while the inner letter (i.e., the payload) carries the actual content.
-
-They play a critical role in the communication process by:
-
- 1. **Packaging the message**: Envelopes contain the message payload, ensuring that all necessary information is transmitted together.
- 2. **Providing metadata**: Envelopes include metadata such as sender and recipient addresses, session information, and expiration times. This metadata helps in identifying and routing the message correctly.
- 3. **Ensuring security and integrity**: Envelopes can include digital signatures and other security features to authenticate the sender and ensure the message has not been tampered with.
-
-## Structure of an Envelope
-
-The `Envelope` class can be defined as follows:
-
- ```py
- @dataclass
- class Envelope(BaseModel):
- version: int # Envelope version
- sender: str: # Bech32-encoded public address of the sender
- target: str: # Bech32-encoded public address of the target recipient
- session: UUID4 # UUID of the session
- schema_digest: str # Digest of the schema used for the payload
- protocol_digest: Optional[str] # Optional protocol digest for custom protocols
- payload: Optional[str] # JSON payload encoded as a base64 string
- expires: Optional[int] # Unix timestamp in seconds indicating expiration
- nonce: Optional[int] # Optional nonce
- signature: Optional[str] # Bech32-encoded signature
- ```
-
-
- Envelopes are quite similar to **blockchain transactions**.
-
-
-## Sending Envelopes
-
-Envelopes are encoded in JSON format and sent via `HTTP 1.1 POST` requests to specific endpoints of receiving agents or services. Currently, the protocol supports only one standardized endpoint:
-
-`HTTP 1.1 POST /submit`
-
-This endpoint expects data that adheres to a JSON-compatible format, typically using the MIME content type `application/json`.
-
-**In essence, Envelopes in the uAgents Framework act as secure wrappers for messages, providing essential information for their secure and reliable transmission between Agents within the Framework itself.**
diff --git a/pages/guides/agents/advanced/agents-async-loops.mdx b/pages/guides/agents/advanced/agents-async-loops.mdx
deleted file mode 100644
index f89805c46..000000000
--- a/pages/guides/agents/advanced/agents-async-loops.mdx
+++ /dev/null
@@ -1,257 +0,0 @@
-import { CodeGroup, CodeSegment, DocsCode, GithubCodeSegment } from "../../../../components/code";
-
-# Agent Asynchronous Loops
-
-## Introduction
-
-Agents need to communicate, perform tasks, and respond to events simultaneously and independently within any decentralized system. This guide shows how to create asynchronous agents that operate in parallel, enabling them to handle their own workflows while still interacting with other agents or external processes.
-
-By using **asynchronous loops** and attaching agents to **external event loops**, you can build agents that manage tasks simultaneously, send periodic updates, and process incoming messages in real-time. This approach is particularly useful when working with distributed systems, where agents must collaborate or handle multiple simultaneous operations without interruptions.
-
-## Supporting documentation
-
- - [Creating an agent ↗️](/guides/agents/create-a-uagent)
- - [Creating an interval task ↗️](/guides/agents/interval-task)
- - [Communicating with other agents ↗️](/guides/agents/communicating-with-other-agents)
- - [Agent Handlers ↗️](/guides/agents/intermediate/handlers)
-
-## Walk-through
-
-The following scripts show how to define agents, manage their life-cycle and attach them to external asynchronous loops.
-
-### Script 1
-
-The first script depicts how to **attach an agent to an external event loop** and allow it to run _simultaneously_ with other asynchronous tasks.
-
-First of all, let's create a Python script:
-
-
-
- ```py copy filename="mac"
- touch external_loop_attach.py
- ```
-
-
-
- ```py copy filename="windows"
- echo. > external_loop_attach.py
- ```
-
-
-
- ```py copy filename="ubuntu"
- touch external_loop_attach.py
- ```
-
-
-
-
-Now, paste the below code into it:
-
-
-
-
-
-
-
- ```py copy filename="external_loop_attach.py"
-
- import asyncio
- import contextlib
-
- from uagents import Agent, Bureau, Context
-
- loop = asyncio.get_event_loop()
-
- agent = Agent(
- name="looper",
- seed="",
- port=8001,
- endpoint=["http://127.0.0.1:8001/submit"],
- )
-
- bureau = Bureau(
- agents=[agent],
- )
-
-
- @agent.on_event("startup")
- async def startup(ctx: Context):
- ctx.logger.info(">>> Looper is starting up.")
-
-
- @agent.on_event("shutdown")
- async def shutdown(ctx: Context):
- ctx.logger.info(">>> Looper is shutting down.")
-
-
- async def coro():
- while True:
- print("doing hard work...")
- await asyncio.sleep(1)
-
-
- if __name__ == "__main__":
- print("Attaching the agent or bureau to the external loop...")
- loop.create_task(coro())
-
- # > when attaching the agent to the external loop
- loop.create_task(agent.run_async())
-
- # > when attaching a bureau to the external loop
- # loop.create_task(bureau.run_async())
-
-
-```
-
-
-
-
-
-
- This script demonstrates using an agent with an external event loop. We begin by importing the necessary libraries; we then proceed and instantiate an Agent named `looper` with a `seed` (``). Then, we create a `bureau` to manage the Agent.
-
- The `startup()` function, marked with the `.on_event("startup")` decorator, logs a message when the Agent starts, while the `shutdown()` function logs a message when the Agent shuts down.
-
- A `coro()` function simulates a long-running task that prints `"Doing hard work..."` every second. This task runs independently, highlighting the Agent's ability to handle multiple simultaneous tasks. Both the Agent and the external task (`coro`) are attached to the event loop using `loop.create_task()`, allowing them to execute simultaneously.
-
- In the `__main__` block, a message indicates the process of attaching tasks to the event loop. The `loop.create_task(coro())` schedules the `coro` task, and `loop.create_task(agent.run_async())` schedules the Agent's operations, enabling both to run without blocking other tasks.
-
- Finally, a context manager suppresses `KeyboardInterrupt` exceptions (which are typically raised when the user presses `Ctrl+C` to stop the program) thus ensuring the program shuts down gracefully without errors or tracebacks.
-
-### Script 2
-
-The goal of the second script is to create an agent that runs tasks inside an external event loop. The agent can execute certain actions (e.g., print messages or respond to events) while simultaneously performing a separate background task.
-
-Let's start by creating a Python script:
-
-
-
- ```py copy filename="mac"
- touch external_loop_run.py
- ```
-
-
- ```py copy filename="windows"
- echo. > external_loop_run.py
- ```
-
-
-
- ```py copy filename="ubuntu"
- touch external_loop_run.py
- ```
-
-
-
-
-Then, let's paste the below code into it:
-
-
-
-
-
-
-
- ```py copy filename="external_loop_run.py"
-
- import asyncio
-
- from uagents import Agent, Bureau, Context
-
- loop = asyncio.get_event_loop()
-
- agent = Agent(
- name="looper",
- seed="",
- loop=loop,
- port = 8000,
- endpoint = ["http://127.0.0.1:8000/submit"],
- )
-
- bureau = Bureau(
- agents=[agent],
- loop=loop,
- )
-
-
- @agent.on_event("startup")
- async def startup(ctx: Context):
- ctx.logger.info(">>> Looper is starting up.")
-
-
- @agent.on_event("shutdown")
- async def shutdown(ctx: Context):
- ctx.logger.info(">>> Looper is shutting down.")
-
-
- async def coro():
- while True:
- print("doing hard work...")
- await asyncio.sleep(1)
-
-
- if __name__ == "__main__":
- print("Starting the external loop from the agent or bureau...")
- loop.create_task(coro())
-
- # > when starting the external loop from the agent
- agent.run()
-
-
-```
-
-
-
-
-
-
- We start by importing the required libraries to correctly run this script. We then create an asynchronous event loop using `asyncio.get_event_loop()`. This loop is used to handle all asynchronous operations, such as the agent's actions and background tasks.
-
- We proceed and create an agent called `looper` using the `Agent` class. The agent takes three parameters: `name`, `seed`, and `loop`. Remember to provide a `seed` for your agent otherwise a random address will be generated every time you run the agent. We then create a `bureau` object using the `Bureau` class. The `bureau` is created with a single agent, `looper`.
-
- We can then define our agent functions to handle the agent's lifecycle events:
-
- 1. `startup()`: This function runs when the agent is started. It logs a message to indicate that the agent has been started up.
- 2. `shutdown()`: This function runs when the agent is shut down. It logs a message to indicate that the agent has been stopped.
-
- In the next step, we define the `coro()` function; As before, this function defines an infinite loop where the agent performs a task (`"doing hard work..."`) every second. This simulates a long-running background task. The `await asyncio.sleep(1)` pauses execution for one second between each iteration, allowing other tasks to run during that time.
-
- Finally, in the `__main__` block, we define a message to be printed indicating that the external event loop is being started. The `loop.create_task(coro())` schedules the `coro()` coroutine to run in the background, simultaneously with the agent's operations.
-
-## Expected Output
-
-We are now ready to run the scripts.
-
-The output should be similar to the following:
-
-- Script 1:
-
- ```
- Attaching the agent or bureau to the external loop...
-
- ```
-
-- Script 2:
-
- ```
- Starting the external loop from the agent or bureau...
- INFO: [looper]: >>> Looper is starting up.
- INFO: [looper]: Agent inspector available at https://agentverse.ai/inspect/?uri=http%3A//127.0.0.1%3A8000&address=agent1qwep424538eh7fcruqcnx8la3q3tgl4tgksrcdtahqs7dqgs4rewsx4jefu
- INFO: [looper]: Starting server on http://0.0.0.0:8000 (Press CTRL+C to quit)
- doing hard work...
- doing hard work...
- doing hard work...
- doing hard work...
- doing hard work...
- ```
diff --git a/pages/guides/agents/advanced/dialogues.mdx b/pages/guides/agents/advanced/dialogues.mdx
deleted file mode 100644
index cdd7e9950..000000000
--- a/pages/guides/agents/advanced/dialogues.mdx
+++ /dev/null
@@ -1,126 +0,0 @@
-import { Callout } from 'nextra/components'
-
-# Dialogues
-
-## Overview
-
-Dialogues are structured and optimized way for agents to communicate. It provides an approach for agents to communicate with each other with consistent message pattern, allowing for multi-message sessions, state tracking, and parallel conversations.
-
-## Understanding Dialogues
-
-Dialogues can be taken as super-powered Protocols, It provides more robust structure for communication between agents. Protocol define interaction patterns but lack state enforcement, leaving developers to manage all possible messaging cases. Dialogues address this by offering predefined patterns and clear state management.
-
-## Difference between Dialogues and Protocols
-
- - **Protocols :** Protocols provide full flexibility to interactions between agents. Developers are responsible for ensuring communication is working correctly by defining right data models and message handlers.
-
- - **Dialogues :** Dialogues add a more rigid structure to communication with enforced state transitions, multi-session state tracking and reusable complex communication patterns. Technically speaking, Dialogues are represented by a directed graph where nodes are the states and edges the messages (message handlers) of a well-defined communication flow.
-
-## Communication Patterns
-
-Communication patterns in dialogues define a general graph-based structure for interactions. They describe every possible flow and branch in the communication process, providing a clear entry, transition and exit point. Patterns are message-agnostic and can be instantiated with various message models as specific Dialogues, adapting to different use cases while maintaining consistent principles.
-
-
-
-## Application and Core Developers
-
-The distinction between communication patterns and Dialogues supports two typical development scenarios with uagents:
-
- - **Application Developers:** Have clear business requirements and are looking to implement concrete use cases with agents as quickly and as easily as possible. They don't want to waste time for creating the necessary building blocks or defining fundamental yet complex processes. Patterns help streamline their workflow, taking the burden of designing communication structures off them.
-
- - **Core Developers:** Improve the infrastructure for agent ecosystems by carefully defining and hardening relevant building blocks, needing full flexibility and power to lay the groundwork for application developers such as defining sound and complete communication patterns that can be reused for various use cases following the same principle.
-
-## How to use dialogues
-
-As explained above dialogues can be used by developers with different requirements. There are different ways in which dialogues can be used but before checking that lets understand what does `stateful communication` means in agent communication ecosystem.
-
-### Stateful Communication
-
-Dialogues support stateful communication which allows agents to access past messages and state status, perform parallel conversations/sessions and also it enforces the sequence of message exchanges. This overall structure and feature of dialogue helps maintain context, improves irrefutability and allows agents to resume conversation from any point of time.
-
-There are different ways in which dialogues can be used as listed below:
-
-### API for Dialogues
-
-Some of the Key APIs exposed to application developers in dialogues include:
-
- - **start_dialogue:** Initiates a dialogue, offering a more explicit way to start communication compared to protocols. Refer [defining dialogue structure](/examples/advanced/open-dialogue-chitchat#step-1-define-the-dialogue-structure) to have better understanding of how to define dialogue nodes and [create a handler for event ↗️](/examples/open-dialogue-chitchat#step-1-define-the-dialogue-structure).
-
- - **get_conversation:** Provides access to past messages, useful for handling complex scenarios and multiple parallel dialogues. Refer [agents on_continue_dialogue handler↗️](/examples/advanced/open-dialogue-chitchat#step-2-setting-up-agents) on how to access history using context's dialogue function.
-
- - **reject_session:** This is the transition for when the dialogue is rejected.
-
-Similarly you can refer more functions and handler in examples [Open Dialogues ↗️](/examples/advanced/open-dialogue-chitchat) and [Predefined Dialogues ↗️](/examples/advanced/predefined-dialogue-chitchat).
-
-### Customization and Predefined Behaviors
-
-Dialogues allow for customization by adding or overwriting message handlers. Predefined behaviors make it easier for application developers to work with dialogues, handling standard interactions while enabling specific customization for unique use-cases.
-
-#### Sample for creating message handler
-
-##### Defining dialogue class
-
-```python copy
-from uagents.experimental.dialogues import Dialogue, Edge, Node
-
-class ChitChatDialogueMessage(Model):
- text: str
-
-# Defining dialogues class
-class ChitChatDialogue(Dialogue):
- def __init__(self, version: str | None = None, agent_address: str | None = None) -> None:
- super().__init__(
- name="ChitChatDialogue",
- version=version,
- agent_address=agent_address,
- nodes=[ node1, node2, node3],
- edges=[ init_session, start_dialogue, cont_dialogue, end_session],
- )
-
- def on_continue_dialogue(self):
- return super()._on_state_transition(
- cont_dialogue.name,
- ChitChatDialogueMessage,
- )
-```
-
-##### Instantiate dialogues and defining continue dialogue handler
-
-```python copy
-from dialogues.hardcoded_chitchat import (ChitChatDialogue,ChitChatDialogueMessage)
-
-# Instantiate the dialogues
-chitchat_dialogue = ChitChatDialogue(
- version="0.1",
- agent_address=,
-)
-
-@chitchat_dialogue.on_continue_dialogue()
-async def continue_chitchat(
- ctx: Context,
- sender: str,
- msg: ChitChatDialogueMessage,
-):
- ctx.logger.info(f"Returning: {msg.text}")
- await ctx.send(sender, ChitChatDialogueMessage(text=msg.text))
-```
-
-## Example to use dialogues
-
-The following examples demonstrate how dialogues can be used in practical scenarios:
-
- - **[Open Dialogue Chit-Chat ↗️](/examples/advanced/open-dialogue-chitchat)**: This example shows an interactive communication setup between agents, where each step and state transition is visible. It is ideal for understanding the flow of messages and state transitions in real-time.
-
- - **[Predefined Dialogue Chit-Chat ↗️](/examples/advanced/predefined-dialogue-chitchat)**: This example illustrates an automated dialogue scenario with hardcoded dialogue management between two agents. It minimizes manual intervention, focusing on predefined responses and interactions.
-
- - **[DeltaV compatible Dialogue Chit-Chat ↗️](/examples/advanced/deltaV-dialogues)**: This example shows how to use dialogues in deltaV compatible agents.
-
-This guide explains the purpose and key aspects of dialogues, drawing on developer comments and feedback. It discusses communication patterns, stateful communication, API highlights, and customization to guide both application and core developers.
-
-
- This guide is part of an experimental feature under heavy development. Backward compatibility is not guaranteed, and updates may cause breaking changes. Each update might introduce significant changes in behavior or functionality. Also, changes may be for Personality types available for the AI Engine.
-
-
-
- Users testing agents using **Dialogues or ChitChat** on [DeltaV ↗️](https://deltav.agentverse.ai/) must select the **Next generation** AI Engine personality type in DeltaV when providing their query through the dedicated bar. The **Next Generation** AI Engine personality stands as a significant AI Engine personality type offering _enhanced scalability_, _reliability_, and _flexibility_. The major key features include advanced context understanding, improved function recommendations, and the ability to handle diverse dialogue formats.
-
diff --git a/pages/guides/agents/advanced/localwallet.mdx b/pages/guides/agents/advanced/localwallet.mdx
deleted file mode 100644
index 5bbbd0795..000000000
--- a/pages/guides/agents/advanced/localwallet.mdx
+++ /dev/null
@@ -1,202 +0,0 @@
-import { Callout } from 'nextra/components'
-import { CodeGroup, CodeSegment, DocsCode, GithubCodeSegment } from "../../../../components/code";
-
-# Local Wallet
-
-## Overview
-
-To transact with fet on the Fetch.ai ledger, you will need to manage your wallet with you agent. We use the Cosmpy library for ledger actions, coupled with in library support for Cosmpy in uAgents.
-
-## Prerequisites
-
-Make sure you have read the following resources before going on with this guide:
-
- - [Quick Start Guide for uAgents Framework ↗️](/guides/agents/quickstart)
- - [Creating your first agent ↗️](/guides/agents/getting-started/create-a-uagent)
- - [Agents address ↗️](/guides/agents/getting-started/getting-uagent-address)
- - [Almanac contract ↗️](/concepts/fetch-network/almanac)
- - [Register in Almanac ↗️](/guides/agents/register-in-almanac)
- - [CosmPy installation ↗️](/guides/fetch-network/cosmpy/install)
- - [CosmPy: Wallets and private keys ↗️](/guides/fetch-network/cosmpy/creating-wallet)
-
-## Imports needed
-
- - [CosmPy ↗️](https://pypi.org/project/cosmpy/)
- - [uAgents ↗️](https://pypi.org/project/uagents/)
-
-## Understanding your wallet
-
-Wallets allow individuals to manage, store and transact across blockchain networks. Wallets are composed of a public and private key pair. The private key is a unique and secret cryptographic code that provides ownership and control over the wallet and allows individuals to authorize transactions signing. The public address is a cryptographic identifier that allows individuals to receive and view transactions.
-
-Changes to the state of a network are achieved by broadcasting transactions. To accomplish this, we can use CosmPy in a straightforward way to create and manage private keys and addresses. In this guide, you will learn how to both generate a new private key as well as recover a previously generated one.
-
-The examples below outlines how to achieve both of these operations.
-
-## Generating a new private key
-
-First of all, import the needed modules and then use the PrivateKey class to create your `private_key`:
-
-```python copy
-# Import necessary classes
-from cosmpy.aerial.wallet import LocalWallet
-from cosmpy.crypto.keypairs import PrivateKey
-
-# Creating a random private key
-private_key = PrivateKey()
-```
-
-## Recover an existing private key
-
-Let's start by extracting the private key and convert it into a base64 encoded string. You can do this on macOS or Linux for the Fetch.ai network using the FetchD CL.
-
-An example is provided in the code snippet below:
-
- ```py copy
- # Extract the private key and convert it into a base64 encoded string
- fetchd keys export mykeyname --unsafe --unarmored-hex | xxd -r -p | base64
- ```
-
-Once you have extracted and converted the key into a base64 encoded string you can recover to an existing private key by following along the provided example below:
-
- ```py copy
- # Import necessary classes
- from cosmpy.aerial.wallet import LocalWallet
- from cosmpy.crypto.keypairs import PrivateKey
-
- # Recovering an existing private key
- private_key = PrivateKey('') # Here is where you provide the base64 encoded private key string
- ```
-
-The `PrivateKey` object is one of CosmPy's low level primitives. This is why it is generally paired with a `Wallet` object. You can now create a local wallet using the `LocalWallet` class from the CosmPy library and initialize it with the `private_key` you generated or recovered earlier. The `LocalWallet` class is used to manage a local wallet associated with a private key for interacting with the Cosmos blockchain.
-
-With this wallet object, you can perform various operations, such as generating the corresponding public address associated with the private key and signing transactions. You can also query useful information such as the address from the wallet directly. The example below showcases how to achieve both of these outlined operations:
-
- ```py copy
- wallet = LocalWallet(private_key)
- print(wallet.address()) # will print the address for the wallet
- ```
-
-## From mnemonic
-
-You can also use an account's mnemonic phrase to get the associated private key. The example provided below showcases how to achieve that:
-
- ```py copy
- from cosmpy.aerial.wallet import LocalWallet
-
- mnemonic = "person knife december tail tortoise jewel warm when worry limit reward memory piece cool sphere kitchen knee embody soft own victory sauce silly page"
-
- wallet = LocalWallet.from_mnemonic(mnemonic)
- ```
-
-## An Agent that checks for a transaction, and sends funds
-
-A simple agent that creates, or loads in a wallet, then validates a transaction has been received.
-
-
-
-
-
-
-
- ```py copy filename="local_wallet_agent.py"
-
- from cosmpy.aerial.wallet import LocalWallet
- from cosmpy.aerial.client import LedgerClient, NetworkConfig
- from cosmpy.crypto.keypairs import PrivateKey
- from uagents import Agent, Context, Model
- from uagents.network import get_faucet, wait_for_tx_to_complete
-
- mainnet_ledger = LedgerClient(NetworkConfig.fetchai_mainnet())
-
-
- class RequestWithTX(Model):
- message: str
- tx_hash: str
-
-
- class DataResponse(Model):
- message: str
-
-
- class PaymentError(Model):
- message: str
- tx_hash: str
-
-
- DataSellingAgent = Agent(
- name="DataSellingAgent",
- seed="dwefwegferdwdwedgko4o430490349jf340-jffjweiopfnw",
- port=8001,
- endpoint=["http://localhost:8001/submit"],
- )
-
- print(DataSellingAgent.address)
-
- AMOUNT = 1
- DENOM = "afet"
- DATA_TO_SELL = "..."
-
- ## at first you may want to generate a wallet
- my_wallet = LocalWallet.generate()
- ## or open one from a seed you've set
- # my_wallet = LocalWallet.from_unsafe_seed("registration test wallet")
- # pk = my_wallet._private_key
- ## or from a pk you already have
- # wallet = LocalWallet(PrivateKey("T7w1yHq1QIcQiSqV27YSwk+i1i+Y4JMKhkpawCQIh6s="))
-
- ...
-
-
- @DataSellingAgent.on_message(model=RequestWithTX)
- async def message_handler(ctx: Context, sender: str, msg: RequestWithTX):
- ctx.logger.info(f"Received message from {sender}: {msg.message}")
-
- mainnet_ledger.query_tx(msg.tx_hash)
- tx_resp = await wait_for_tx_to_complete(msg.tx_hash, mainnet_ledger)
-
- coin_received = tx_resp.events["coin_received"]
- if (
- coin_received["receiver"] == str(my_wallet.address)
- and coin_received["amount"] == f"{AMOUNT}{DENOM}"
- ):
- ctx.logger.info(f"Transaction was successful: {coin_received}")
- await ctx.send(sender, DataResponse(message=DATA_TO_SELL))
-
- else:
- await ctx.send(sender, PaymentError(message="Incorrect tx", tx_hash=msg.tx_hash))
-
-
- if __name__ == "__main__":
- DataSellingAgent.run()
-
-```
-
-
-
-
-
-
-The output for the above would be:
-
- ```
- agent1qtqdeme8s6fu2zdwdw72eacpxms3jg8dxctc7v4gvw0hlmlahayw5mqmt68
- INFO: [DataSellingAgent]: Registration on Almanac API successful
- INFO: [DataSellingAgent]: Registering on almanac contract...
- INFO: [DataSellingAgent]: Registering on almanac contract...complete
- INFO: [DataSellingAgent]: Agent inspector available at https://agentverse.ai/inspect/?uri=http%3A//127.0.0.1%3A8001&address=agent1qtqdeme8s6fu2zdwdw72eacpxms3jg8dxctc7v4gvw0hlmlahayw5mqmt68
- INFO: [DataSellingAgent]: Starting server on http://0.0.0.0:8001 (Press CTRL+C to quit)
- ```
-
-Validating a transaction with Cosmpy and uAgents is really easy, and to test the above agent you just need to replicate the `Models` and send a `RequestWithTX` in any function in another agent:
-
- ```
- @DataBuyingAgent.on_event("startup")
- async def introduce_agent(ctx: Context):
- ctx.logger.info("Starting DataBuyingAgent...")
- await ctx.send(agent_address, RequestWithTX(message="buy", tx_hash="D165966A6B9269EHHHHH7C8F659F1CDA871C8CD83F9102DD35A437211F3DE0CF"))
- ```
diff --git a/pages/guides/agents/advanced/message-verification.mdx b/pages/guides/agents/advanced/message-verification.mdx
deleted file mode 100644
index be894d780..000000000
--- a/pages/guides/agents/advanced/message-verification.mdx
+++ /dev/null
@@ -1,388 +0,0 @@
-import { CodeGroup, CodeSegment, DocsCode, GithubCodeSegment } from "../../../../components/code";
-
-# How to use agents to verify messages
-
-## Introduction
-
-The emergence of decentralized technologies has introduced new possibilities for secure communication and data exchange. In this guide, we will delve into the process of setting up a scenario where two Agents communicate with each other, employing cryptographic methods to verify the messages exchanged between them. We will showcase how to create a secure messaging environment using Agents, where messages are not only exchanged but also signed and verified to prevent unauthorized access and tampering.
-
-## Prerequisites
-
-Make sure you have read the following resources before going on with this guide:
-
- - [Quick Start Guide for uAgents Framework ↗️](/guides/agents/quickstart)
- - [Creating your first agent ↗️](/guides/agents/getting-started/create-a-uagent)
- - [Agents address ↗️](/guides/agents/getting-started/getting-uagent-address)
- - [Almanac contract ↗️](/concepts/fetch-network/almanac)
- - [Register in Almanac ↗️](/guides/agents/register-in-almanac)
-
-## Imports needed
-
- - [uAgents ↗️](https://pypi.org/project/uagents/)
-
-## Walk-through
-
-1. First of all, you need to navigate towards the directory you created for your project.
-
-2. In here, let's create a Python script for this task and name it:
-
-
-
- ```py copy filename="mac"
- touch message_verification.py
- ```
-
-
- ```py copy filename="windows"
- echo. > message_verification.py
- ```
-
-
-
- ```py copy filename="ubuntu"
- touch message_verification.py
- ```
-
-
-
-
-3. We now need to import the necessary classes from `uagents` (`Agent`, `Bureau`, `Context`, and `Model`), `uagents.crypto` (`Identity`) and `hashlib`. Then we would need to define the messages format using the `Message` class as a subclass of `Model`:
-
-
-
-
-
-
-
- ```py copy filename="message_verification.py"
-
- import hashlib
- from uagents import Agent, Bureau, Context, Model
- from uagents.crypto import Identity
-
-
- class Message(Model):
- message: str
- digest: str
- signature: str
-
-```
-
-
-
-
-
-
- The message format has three attributes:
-
- - `message`: a string representing the message text.
- - `digest`: a string representing the SHA-256 hash of the message.
- - `signature`: a string representing the digital signature of the hash using the sender's private key.
-
-4. Let's now define an `encode()` function used to generate the digest for each message before it is signed:
-
-
-
-
-
-
-
- ```py copy filename="message_verification.py"
-
- def encode(message: str) -> bytes:
- hasher = hashlib.sha256()
- hasher.update(message.encode())
- return hasher.digest()
-
-```
-
-
-
-
-
-
- This function is used to hash a string message using the SHA-256 algorithm and return the resulting digest as bytes.
-
-5. We can now proceed and create our agents using the `Agent` class:
-
-
-
-
-
-
-
- ```py copy filename="message_verification.py"
-
- alice = Agent(name="alice", seed="alice recovery password", port=8000, endpoint=["http://127.0.0.1:8000/submit"])
- bob = Agent(name="bob", seed="bob recovery password", port=8001, endpoint=["http://127.0.0.1:8001/submit"])
-
-```
-
-
-
-
-
-
-6. Let's now define a `send_message()` function for `alice` to send messages to `bob`:
-
-
-
-
-
-
-
- ```py copy filename="message_verification.py"
-
- @alice.on_interval(period=3.0)
- async def send_message(ctx: Context):
- msg = "hello there bob"
- digest = encode(msg)
-
- await ctx.send(
- bob.address,
- Message(message=msg, digest=digest.hex(), signature=alice.sign_digest(digest)),
- )
-
-```
-
-
-
-
-
-
- This function is decorated using the `.on_interval()` decorator, which indicates that the function is called periodically every `3.0` seconds to send messages to `bob`'s address. It takes in a single argument `ctx`. The function first creates a message, `msg`, and computes its digest using the `encode` function. The message is then sent to `bob` using the `ctx.send()` method, along with the `digest` and a `signature` of the digest using the `alice.sign_digest()` function.
-
-7. Let's then define an `alice_rx_message()` function used to receive and process messages sent by `bob`:
-
-
-
-
-
-
-
- ```py copy filename="message_verification.py"
-
- @alice.on_message(model=Message)
- async def alice_rx_message(ctx: Context, sender: str, msg: Message):
- assert Identity.verify_digest(
- sender, bytes.fromhex(msg.digest), msg.signature
- ), "couldn't verify bob's message"
-
- ctx.logger.info("Bob's message verified!")
- ctx.logger.info(f"Received message from {sender}: {msg.message}")
-
-```
-
-
-
-
-
-
- This function is decorated using the `.on_message()`, indicating that the function is triggered when a message is being received of type `Message`. The function takes in three arguments: `ctx`, `sender`, and `msg`.
-
- The function first verifies the authenticity of the message using the `Identity.verify_digest()` function. If the message cannot be verified, the function raises an assertion error. Assuming the message is verified, the function logs a message indicating that the message was verified and another message indicating the contents of the message.
-
-8. We can now define a `bob_rx_message()` function used by `bob` to receive and process messages sent by `alice`:
-
-
-
-
-
-
-
- ```py copy filename="message_verification.py"
-
- @bob.on_message(model=Message)
- async def bob_rx_message(ctx: Context, sender: str, msg: Message):
- assert Identity.verify_digest(
- sender, bytes.fromhex(msg.digest), msg.signature
- ), "couldn't verify alice's message"
-
- ctx.logger.info("Alice's message verified!")
- ctx.logger.info(f"Received message from {sender}: {msg.message}")
-
- msg = "hello there alice"
- digest = encode(msg)
-
- await ctx.send(
- alice.address,
- Message(message=msg, digest=digest.hex(), signature=bob.sign_digest(digest)),
- )
-
-```
-
-
-
-
-
-
- This function is decorated using the `.on_message()` decorator, indicating that the function is triggered when a message is being received of type `Message`. It takes in three arguments: `ctx`, `sender`, and `msg`.
-
- The function first verifies the authenticity of the message using the `Identity.verify_digest()` function. If the message cannot be verified, the function raises an assertion error. On the other hand, if the message is verified, the function logs a message indicating that the message was verified and another message indicating the contents of the message using the `ctx.logger.info()` method. It then creates a response message, `msg`, and computes its digest using the `encode()` function. The response message is then sent to `alice` using the `ctx.send()` method.
-
-9. We can now create a `bureau` object from the `Bureau` class and then add both agents to it so for them to be run together.
-
-
-
-
-
-
-
- ```py copy filename="message_verification.py"
-
- bureau = Bureau()
- bureau.add(alice)
- bureau.add(bob)
-
- if __name__ == "__main__":
- bureau.run()
-
-```
-
-
-
-
-
-
-10. Save the script.
-
-The overall script should look as follows:
-
-
-
-
-
-
-
- ```py copy filename="message_verification.py"
-
- import hashlib
- from uagents import Agent, Bureau, Context, Model
- from uagents.crypto import Identity
-
-
- class Message(Model):
- message: str
- digest: str
- signature: str
-
-
- def encode(message: str) -> bytes:
- hasher = hashlib.sha256()
- hasher.update(message.encode())
- return hasher.digest()
-
-
- alice = Agent(name="alice", seed="alice recovery password", port=8000, endpoint=["http://127.0.0.1:8000/submit"])
- bob = Agent(name="bob", seed="bob recovery password", port=8001, endpoint=["http://127.0.0.1:8001/submit"])
-
-
- @alice.on_interval(period=3.0)
- async def send_message(ctx: Context):
- msg = "hello there bob"
- digest = encode(msg)
-
- await ctx.send(
- bob.address,
- Message(message=msg, digest=digest.hex(), signature=alice.sign_digest(digest)),
- )
-
-
- @alice.on_message(model=Message)
- async def alice_rx_message(ctx: Context, sender: str, msg: Message):
- assert Identity.verify_digest(
- sender, bytes.fromhex(msg.digest), msg.signature
- ), "couldn't verify bob's message"
-
- ctx.logger.info("Bob's message verified!")
- ctx.logger.info(f"Received message from {sender}: {msg.message}")
-
-
- @bob.on_message(model=Message)
- async def bob_rx_message(ctx: Context, sender: str, msg: Message):
- assert Identity.verify_digest(
- sender, bytes.fromhex(msg.digest), msg.signature
- ), "couldn't verify alice's message"
-
- ctx.logger.info("Alice's message verified!")
- ctx.logger.info(f"Received message from {sender}: {msg.message}")
-
- msg = "hello there alice"
- digest = encode(msg)
-
- await ctx.send(
- alice.address,
- Message(message=msg, digest=digest.hex(), signature=bob.sign_digest(digest)),
- )
-
-
- bureau = Bureau()
- bureau.add(alice)
- bureau.add(bob)
-
- if __name__ == "__main__":
- bureau.run()
-
-```
-
-
-
-
-
-
-## Run your script
-
-On your terminal, make sure to have activated your virtual environment.
-
-Run the script: `python message_verification.py`.
-
-The output should be as follows:
-
- ```
- WARNING: [alice]: No endpoints provided. Skipping registration: Agent won't be reachable.
- WARNING: [ bob]: No endpoints provided. Skipping registration: Agent won't be reachable.
- [ bob]: Alice's message verified!
- [ bob]: Received message from agent1qf5gfqm48k9acegez3sg82ney2aa6l5fvpwh3n3z0ajh0nam3ssgwnn5me7: hello there bob
- [alice]: Bob's message verified!
- [alice]: Received message from agent1qvjjle8dlf22ff7zsh6wr3gl8tdepzygftdxpc2vn8539ngt962a709c90s: hello there alice
- ```
diff --git a/pages/guides/agents/advanced/name-service.mdx b/pages/guides/agents/advanced/name-service.mdx
deleted file mode 100644
index 1091aeae7..000000000
--- a/pages/guides/agents/advanced/name-service.mdx
+++ /dev/null
@@ -1,550 +0,0 @@
-import { CodeGroup, CodeSegment, DocsCode, GithubCodeSegment } from "../../../../components/code";
-
-# Agents Name Service
-
-## Introduction
-
-This file can be run on any platform supporting Python, with the necessary install permissions. This example shows how to set up the Agents Name Service contract using the `uagents` and `cosmpy` Python libraries. The **Fetch.ai Name Service Smart Contract** aims at enhancing the usability and accessibility of the Fetch.ai blockchain by providing a decentralized, secure, and user-friendly way to manage names for various digital entities. Indeed, the Name Service Smart Contract acts similarly to a phonebook for the Fetch.ai blockchain; It assigns memorable names (i.e., domains) to blockchain addresses, making it easier to find and interact with other agents and resources on the network. Imagine it as a way to give user-friendly names to complex wallet addresses.
-
-In this guide we set up a communication line between two agents, Alice and Bob, where Alice sends a message to Bob every 5 seconds by first constructing Bob's address using a predefined domain (example.agent) and Bob's name (bob-0).
-
-In turn, Bob is coded to listen for incoming messages and log them. On startup, Bob registers its name on a blockchain network using a name service contract. This ensures that Alice can address messages to Bob correctly.
-
-**Let's get started!**
-
-## Walk-through
-
-First of all, we need to create 2 Python scripts for our two agents using the following commands within your terminal:
-
- Bob:
-
-
-
- ```py copy filename="mac"
- touch bob.py
- ```
-
-
- ```py copy filename="windows"
- echo. > bob.py
- ```
-
-
-
- ```py copy filename="ubuntu"
- touch bob.py
- ```
-
-
-
-
- Alice:
-
-
-
- ```py copy filename="mac"
- touch alice.py
- ```
-
-
- ```py copy filename="windows"
- echo. > alice.py
- ```
-
-
-
- ```py copy filename="ubuntu"
- touch alice.py
- ```
-
-
-
-
-### Bob
-
-Let's start with the first agent of this example, Bob.
-
-1. First of all, we import the required libraries and modules:
-
-
-
-
-
-
-
- ```py copy filename="bob.py"
-
- from cosmpy.aerial.wallet import LocalWallet
- from uagents import Agent, Context, Model
- from uagents.network import get_faucet, get_name_service_contract
-
-```
-
-
-
-
-
-
- - `LocalWallet`: From the `cosmpy.aerial.wallet` module, this is used to create and manage wallets for blockchain interactions.
- - `Agent`, `Context`, `Model`: From the `uagents` module, these are used to define the agent, its context, and the message model.
- - `get_faucet`: From the `uagents.network` module, this function is used to get a faucet for funding wallets.
- - `get_name_service_contract`: From the `uagents.network` module, this function is used to get the contract for registering agent names on the network.
-
-2. We then define the Message model defining the structure of messages that Bob will be able to handle:
-
-
-
-
-
-
-
- ```py copy filename="bob.py"
-
- class Message(Model):
- message: str
-
-```
-
-
-
-
-
-
- We have defined a `Message` data model which contains a single attribute `message` of type string.
-
-3. We then need to initialize the agent:
-
-
-
-
-
-
-
- ```py copy filename="bob.py"
-
- bob = Agent(
- name="bob-0",
- seed="agent bob-0 secret phrase",
- port=8001,
- endpoint=["http://localhost:8001/submit"],
- )
-
-```
-
-
-
-
-
-
- We have created an agent named `bob-0` with a specified `seed`. The agent listens on port `8001` and has an `endpoint` for receiving messages.
-
-4. We are now ready to set up the **Wallet**, **Name Service Contract**, and **Faucet**:
-
-
-
-
-
-
-
- ```py copy filename="bob.py"
-
- my_wallet = LocalWallet.from_unsafe_seed("registration test wallet")
- name_service_contract = get_name_service_contract(test=True)
- faucet = get_faucet()
-
- DOMAIN = "example.agent"
-
- faucet.get_wealth(my_wallet.address())
-
-```
-
-
-
-
-
-
- We first create a wallet from a seed phrase and this wallet is used for interacting with the Fetch.ai blockchain. We then proceed and define the Name Service Contract. It retrieves the name service contract to register the agent's name on the blockchain. The `test=True` parameter indicates this is a `test` setup. Then, we define the faucet used to fund the wallet with test tokens. We then define the domain for the agent's name registration and finally proceed to request funds from the faucet to ensure the agent's wallet has sufficient funds to operate. Remember that you need to provide the `name`, `seed`, `port`, `endpoint` and `DOMAIN` parameters to correctly run this code!
-
-5. We continue and define Bob's functions. We start with a register_agent_name function which registers Bob's name within the blockchain using the agent's wallet, address, name and domain parameters:
-
-
-
-
-
-
-
- ```py copy filename="bob.py"
-
- @bob.on_event("startup")
- async def register_agent_name(ctx: Context):
- await name_service_contract.register(
- bob.ledger, my_wallet, bob.address, bob.name, DOMAIN
- )
-
-```
-
-
-
-
-
-
- Here, we defined the `register_agent_name` function. It registers the agent's name on the blockchain when the agent is initialized. The function uses the name service contract to register `bob-0.example.agent` agent using the `my_wallet` wallet. **It is important that you provide only lower case letters for your agent's `name` and `DOMAIN` parameters as otherwise you will face issues the moment you run your agent**.
-
-6. We now define a `message_handler` function for Bob to handle incoming messages:
-
-
-
-
-
-
-
- ```py copy filename="bob.py"
-
- @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}")
-
-
- if __name__ == "__main__":
- bob.run()
-
-```
-
-
-
-
-
-
- Here we defined a function handling incoming messages of type `Message`. It logs the sender's address and the message content.
-
-7. Finally, we save and run the script.
-
-The overall script for this example should look as follows:
-
-
-
-
-
-
-
- ```py copy filename="bob.py"
-
- from cosmpy.aerial.wallet import LocalWallet
- from uagents import Agent, Context, Model
- from uagents.network import get_faucet, get_name_service_contract
-
-
- # NOTE: Run sender_agent.py before running receiver_agent.py
-
-
- class Message(Model):
- message: str
-
-
- bob = Agent(
- name="bob-0",
- seed="agent bob-0 secret phrase",
- port=8001,
- endpoint=["http://localhost:8001/submit"],
- )
-
- my_wallet = LocalWallet.from_unsafe_seed("registration test wallet")
- name_service_contract = get_name_service_contract(test=True)
- faucet = get_faucet()
-
- DOMAIN = "example.agent"
-
- faucet.get_wealth(my_wallet.address())
-
-
- @bob.on_event("startup")
- async def register_agent_name(ctx: Context):
- await name_service_contract.register(
- bob.ledger, my_wallet, bob.address, bob.name, DOMAIN
- )
-
-
- @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}")
-
-
- if __name__ == "__main__":
- bob.run()
-
-```
-
-
-
-
-
-
-### Alice
-
-Let's now define the code for our second agent, Alice.
-
-1. First of all, we import the required libraries and modules:
-
-
-
-
-
-
-
- ```py copy filename="alice.py"
-
- from uagents import Agent, Context, Model
-
-```
-
-
-
-
-
-
-2. Let's then define the message data model similarly to what we did for Bob:
-
-
-
-
-
-
-
- ```py copy filename="alice.py"
-
- class Message(Model):
- message: str
-
-```
-
-
-
-
-
-
-3. We proceed and initialize the agent:
-
-
-
-
-
-
-
- ```py copy filename="alice.py"
-
- alice = Agent(
- name="alice-0",
- seed="agent alice-0 secret phrase",
- port=8000,
- endpoint=["http://localhost:8000/submit"],
- )
-
-```
-
-
-
-
-
-
- We initialize an agent named `alice-0` with a specified `seed`. The agent listens on port `8000` and has an `endpoint` for submitting messages.
-
-4. We then need to define the domain of the agent. The `DOMAIN` specifies the domain for the agent communication. This domain is used to construct the full address of Bob:
-
-
-
-
-
-
-
- ```py copy filename="alice.py"
-
- message: str
-
-
- alice = Agent(
- name="alice-0",
- seed="agent alice-0 secret phrase",
- port=8000,
- endpoint=["http://localhost:8000/submit"],
- )
-
- DOMAIN = "example.agent"
-
-```
-
-
-
-
-
-
-5. Finally, we define the functions and behaviors for Alice:
-
-
-
-
-
-
-
- ```py copy filename="alice.py"
-
- @alice.on_interval(period=5)
- async def alice_interval_handler(ctx: Context):
- bob_name = "bob-0" + "." + DOMAIN
- ctx.logger.info(f"Sending message to {bob_name}...")
- await ctx.send(bob_name, Message(message="Hello there bob."))
-
-
- if __name__ == "__main__":
- alice.run()
-
-```
-
-
-
-
-
-
- This `alice_interval_handler()` function runs at regular intervals of 5 seconds to send messages. The handler constructs Bob's address using the domain and sends a message to Bob. It combines `bob-0` name with the `DOMAIN` to form `bob-0.example.agent`. The agent logs the action and sends a message with the content "Hello there bob." to Bob agent.
-
- Remember that you need to provide the `name`, `seed`, `port`, `endpoint` and `DOMAIN` parameters to correctly run this code! **Additionally, it is important that you provide only lower case letters for your agent's `name` and `DOMAIN` parameters as otherwise you will face issues the moment you run your agent**.
-
-The overall script for this example should look as follows:
-
-
-
-
-
-
-
- ```py copy filename="alice.py"
-
- from uagents import Agent, Context, Model
-
-
- class Message(Model):
- message: str
-
-
- alice = Agent(
- name="alice-0",
- seed="agent alice-0 secret phrase",
- port=8000,
- endpoint=["http://localhost:8000/submit"],
- )
-
- DOMAIN = "example.agent"
-
-
- @alice.on_interval(period=5)
- async def alice_interval_handler(ctx: Context):
- bob_name = "bob-0" + "." + DOMAIN
- ctx.logger.info(f"Sending message to {bob_name}...")
- await ctx.send(bob_name, Message(message="Hello there bob."))
-
-
- if __name__ == "__main__":
- alice.run()
-
-```
-
-
-
-
-
-
-### Expected output
-
-Within your terminal windows you should see something similar to the following:
-
-1. **Bob**:
-
- ```
- INFO: [bob-0]: Registration on Almanac API successful
- INFO: [bob-0]: Registering on almanac contract...
- INFO: [bob-0]: Registering on almanac contract...complete
- INFO: [network]: Registering name...
- INFO: [network]: Registering name...complete
- INFO: [bob-0]: Agent inspector available at https://agentverse.ai/inspect/?uri=http%3A//127.0.0.1%3A8001&address=agent1qwep424538eh7fcruqcnx8la3q3tgl4tgksrcdtahqs7dqgs4rewsx4jefu
- INFO: [bob-0]: Starting server on http://0.0.0.0:8001 (Press CTRL+C to quit)
- INFO: [bob-0]: Received message from agent1qwquu2d237gntfugrnwch38g8jkl76vdr05qjm4wyps6ap04fvt8vtzhpqw: Hello there bob.
- INFO: [bob-0]: Received message from agent1qwquu2d237gntfugrnwch38g8jkl76vdr05qjm4wyps6ap04fvt8vtzhpqw: Hello there bob.
- INFO: [bob-0]: Received message from agent1qwquu2d237gntfugrnwch38g8jkl76vdr05qjm4wyps6ap04fvt8vtzhpqw: Hello there bob.
- INFO: [bob-0]: Received message from agent1qwquu2d237gntfugrnwch38g8jkl76vdr05qjm4wyps6ap04fvt8vtzhpqw: Hello there bob.
- ```
-
-2. **Alice**:
-
- ```
- INFO: [alice-0]: Registration on Almanac API successful
- INFO: [alice-0]: Registering on almanac contract...
- INFO: [alice-0]: Registering on almanac contract...complete
- INFO: [alice-0]: Starting server on http://0.0.0.0:8000 (Press CTRL+C to quit)
- INFO: [alice-0]: Sending message to bob-0.agent...
- INFO: [alice-0]: Sending message to bob-0.agent...
- INFO: [alice-0]: Sending message to bob-0.agent...
- ```
diff --git a/pages/guides/agents/advanced/register-in-almanac.mdx b/pages/guides/agents/advanced/register-in-almanac.mdx
deleted file mode 100644
index fbab453ca..000000000
--- a/pages/guides/agents/advanced/register-in-almanac.mdx
+++ /dev/null
@@ -1,120 +0,0 @@
-import {Callout} from 'nextra/components'
-import { CodeGroup, CodeSegment, DocsCode, GithubCodeSegment } from "../../../../components/code";
-
-# Registering in Almanac Contract
-
-## Introduction
-
-The [Almanac ↗️](/references/contracts/uagents-almanac/almanac-overview) contract requires agents to register using their **Agent Address** and pay a fee for registration to be found by other agents on the network.
-
-## Prerequisites
-
-Make sure you have read the following resources before going on with this guide:
-
- - [Quick Start Guide for uAgents Framework ↗️](/guides/agents/quickstart)
- - [Creating your first agent ↗️](/guides/agents/getting-started/create-a-uagent)
- - [Agents address ↗️](/guides/agents/getting-started/getting-uagent-address)
- - [Almanac contract ↗️](/concepts/fetch-network/almanac)
- - [Register in Almanac ↗️](/guides/agents/register-in-almanac)
-
-## Imports needed
-
- - [uAgents ↗️](https://pypi.org/project/uagents/)
-
-## Walk-through
-
-1. First of all, create a Python script and name it:
-
-
-
- ```py copy filename="mac"
- touch registration.py
- ```
-
-
- ```py copy filename="windows"
- echo. > registration.py
- ```
-
-
-
- ```py copy filename="ubuntu"
- touch registration.py
- ```
-
-
-
-
-2. Open your terminal and `registration.py` file in an editor of your choice. Let's start by importing the `Agent` class from the `uagents` library to create our Agent. This function will check if you have enough tokens to register in the Almanac contract, if not it will add testnet tokens to your `ASI Network address`. Then, create an agent, `alice`, you need to provide the `name`, `seed`, `port` and `endpoint` parameters to correctly run it! The code will look similar to the following:
-
-
-
-
-
-
-
- ```py copy filename="registration.py"
-
- from uagents import Agent, Context, Protocol
-
- agent = Agent(
- name="alice",
- port=8000,
- seed="alice secret phrase",
- endpoint=["http://127.0.0.1:8000/submit"],
- )
-
- @agent.on_interval(period=3)
- async def hi(ctx: Context):
- ctx.logger.info(f"Hello")
-
- agent.run()
-
-```
-
-
-
-
-
-
-There's a few things happening in this script; we initialize Alice with an endpoint. An endpoint is the address in which other agents can send messages to where Alice will be listening. As highlighted in [Registration and Endpoints Weighting ↗️](/references/contracts/uagents-almanac/endpoints), agents can communicate by querying the Almanac and retrieving an endpoint from the recipient agent. Therefore, we need to specify the service endpoints when defining our agents.
-
-We also have to define `agent.run()`. This `.run()` function runs the agent, but more importantly this registers the agent to the Almanac when code is initialized.
-
-Once you run your script, your agent will start the registration process automatically. Finally, it will try to register on the Almanac contract. Then, we will be ready to start to a remote communication with other agents registered within the Almanac contract. The output should be similar to:
-
- ```
- INFO: [Alice]: Registration on Almanac API successful
- INFO: [Alice]: Registering on almanac contract...
- INFO: [Alice]: Registering on almanac contract...complete
- INFO: [Alice]: Hello
- INFO: [Alice]: Agent inspector available at https://agentverse.ai/inspect/?uri=http%3A//127.0.0.1%3A8000&address=agent1qfccl7xc2hrwzntx9rxgf56lh80kuf5av6h4nyk3ywvxyu846zqwyl3g0jf
- INFO: [Alice]: Starting server on http://0.0.0.0:8000 (Press CTRL+C to quit)
- INFO: [Alice]: Hello
- INFO: [Alice]: Hello
- INFO: [Alice]: Hello
- ```
-
-The output for the above code would be similar to the following:
-
- ```
- INFO: [alice]: Registration on Almanac API successful
- INFO: [alice]: Registering on almanac contract...
- INFO: [alice]: Registering on almanac contract...complete
- INFO: [alice]: Agent inspector available at https://agentverse.ai/inspect/?uri=http%3A//127.0.0.1%3A8000&address=agent1q0c5m0ugjml6rwa05fwe8wecqnxjc8vk6grqwlylpp9h4nfzxm4cyaha7r8
- INFO: [alice]: Starting server on http://0.0.0.0:8000 (Press CTRL+C to quit)
- INFO: [alice]: Hello
- INFO: [alice]: Hello
- INFO: [alice]: Hello
- ```
-
-
- For further information on how to set up your Agents and register them into the Almanac to allow for remote
- communication, visit the [Communicating with other Agents ↗️](/guides/agents/communicating-with-other-agents)
- guide.
-
diff --git a/pages/guides/agents/advanced/utilizing-api-to-build-network-of-task-and-subtask.mdx b/pages/guides/agents/advanced/utilizing-api-to-build-network-of-task-and-subtask.mdx
deleted file mode 100644
index 9fd81bfb2..000000000
--- a/pages/guides/agents/advanced/utilizing-api-to-build-network-of-task-and-subtask.mdx
+++ /dev/null
@@ -1,649 +0,0 @@
-import { Callout } from 'nextra/components'
-import PackageVersion from 'components/package-version'
-import { CodeGroup, CodeSegment, DocsCode, GithubCodeSegment } from "../../../../components/code";
-
-# Multi-file agent pipeline for AI Engine: using News API to build network of functions and secondary functions in Agentverse
-
-## Introduction
-
-This agents network helps users to read news of different types including **Categorical**, **Country** based or **Keyword** related news. The system operates based on a multiple layers structure of Primary and Secondary functions, each one of them playing a vital role in delivering personalized news content to users.
-
-There are three layers of functions to let users read news and which altogether return news matching the specific type and subtype based on the user's preferences. For an overall workflow of the user's requests, please refer below flow chart.
-
-
-
-First of all, we have the **News Reading URL System**; this one acts as the gateway to news headlines. This layer enables the connection between users and the latest news headlines. When the user expresses interest in reading the news, the [AI Engine ↗️](/concepts/ai-engine/ai-engine-intro) drives the News Reading System and initiates the process of fetching news articles for the user. Once the system understands your intent is to read news headlines, it will call upon the **News Reading Details Secondary function**. At this point, users will be required to provide the news type and subtype they want to read via [DeltaV ↗️](/concepts/ai-engine/deltav).
-
-Once users provides the input for the type and subtype of news they want to read, the system will take in the user's preferences and decide which specific type of news the user is interested in, whether it it categorical (e.g., business or sports), regional news from a specific country, or news related to a particular keyword.
-
-With the user's news preference in hand, the system redirects request to one of the specialized Secondary functions: the **Generate news_type Secondary function**. These Secondary functions are like expert news gatherers, each dedicated to a specific type of news based on the user's preference provided.
-
-All **Primary** and **Secondary** functions redirections are handled by **AI Engine**. It processes user preferences and triggers the appropriate functions to fulfil the user's objective. By providing clear and concise field descriptions for each Primary and Secondary functions, the AI Engine will ensure straightforward navigation through the News Reading System and operations, making it easy for users to stay informed on the topics that matter the most to them.
-
-## Prerequisites
-
-Make sure you have read the following resources before going on with this guide:
-
- - [Quick Start Guide for uAgents Framework ↗️](/guides/agents/quickstart)
- - [Creating your first agent ↗️](/guides/agents/getting-started/create-a-uagent)
- - [Agents address ↗️](/guides/agents/getting-started/getting-uagent-address)
- - [Almanac contract ↗️](/concepts/fetch-network/almanac)
- - [Register in Almanac ↗️](/guides/agents/register-in-almanac)
- - [Agents protocols ↗️](/guides/agents/intermediate/protocols)
- - [Exchange protocol ↗️](/references/uagents/uagents-protocols/exchange-protocol)
- - [Agent Functions ↗️](/guides/agents/intermediate/agent-functions)
- - [Make your agents AI Engine compatible ↗️](/guides/agents/intermediate/ai-engine-compatible-agent)
- - [Multi-file agent pipeline for AI Engine: Hugging face API to create a multi agent pipeline ↗️](/guides/agents/intermediate/primary-secondary-functions)
-
-## Imports needed
-
- - [uAgents ↗️](https://pypi.org/project/uagents/)
- - [AI Engine ↗️](https://pypi.org/project/uagents-ai-engine/)
-
-## Primary and Secondary functions
-
-The **Primary** and **Secondary** functions descriptions and names should be relevant to make it easy for the LLM to identify the type of Secondary function to trigger and when. Descriptions of Primary and Secondary functions should always indicate when specific Secondary functions should be triggered. In this case one of multiple Secondary functions is to be triggered, it should be provided in the dictionary to enhance the LLM's understanding. For instance, you can refer to the example below where the **News Reading Details Secondary function** triggers one of the **Generate news_type Secondary function** based on the user's requirement.
-
-**Field description** is another feature of services which should mention use of subtasks in a clear and concise way.
-Refer to the [Agentverse Functions ↗️](/guides/agents/intermediate/agent-functions#primary-and-secondary-functions) for more details on Primary and Secondary functions. Also, have a look at the [Agentverse Functions ↗️](/guides/agentverse/agentverse-functions/field-descriptions-for-deltav) for guidance on fields descriptions of your Agent Functions!
-
-## News API
-
-Login to [News API ↗️](https://newsapi.org/docs/endpoints/top-headlines) and get your API key by logging in and registering for API. This API key will be used in agent scripts to fetch news related to a specific type and subtype.
-
-### News Reading URL System Agent
-
-This agent helps users to read news according to their willingness. This agent triggers the news details gathering secondary functions and asks the user for the news type and subtype they want to read today. This agent responds to the final result to the [DeltaV ↗️](/concepts/ai-engine/deltav) GUI as well.
-
-
-
-
-
-
-
- ```py copy filename="news_reading_url_system_agent.py"
-
- # Here we demonstrate how we can create a news reading system agent that is compatible with DeltaV
-
- # After running this agent, it can be registered to DeltaV on Agentverse. For registration you will have to use the agent's address
-
- # Import required libraries
- import requests
- from ai_engine import UAgentResponse, UAgentResponseType
-
-
- # Define News Reading Model
- class News(Model):
- news: str
-
-
- # Define Protocol for news reading system
- news_protocol = Protocol("News System")
-
-
- # Define a handler for the News system protocol
- @news_protocol.on_message(model=News, replies=UAgentResponse)
- async def on_news_request(ctx: Context, sender: str, msg: News):
- # Printing the news response on logger
- ctx.logger.info(f"Received news request from {sender} with title: {msg.news}")
- # Creating hyperlink and sending final response to the DeltaV GUI
- message = f"YOUR NEWS CONTENT"
- await ctx.send(sender, UAgentResponse(message=message, type=UAgentResponseType.FINAL))
-
-
- # Include the Generate News protocol in your agent
- agent.include(news_protocol)
-
-```
-
-
-
-
-
-
-Now click on the **Run** button in the upper right corner of the editor so that you have your news system agent up and running!
-
-### News Reading Details Agent
-
-This agent asks users for the type and subtype of news they want to read today from options like **categorical**, **country** related or **keyword** related and respective subtypes. It then directs the user request to relevant secondary function to generate that type of news title and respond it back to the **News Reading system**.
-
-
-
-
-
-
-
- ```py copy filename="news_reading_details_agent.py"
-
- # Here we demonstrate how we can create a news details agent that is compatible with DeltaV.
- # After running this agent, it can be registered to DeltaV on Agentverse. For registration you will have to use the agent's address.
-
- # Import required libraries
- import requests
- import json
- from ai_engine import UAgentResponse, UAgentResponseType
-
-
- # Define News Generating Model.
- class GetNewsDetails(Model):
- news_type: str
- news_subtype: str
- news_url_content: str
-
-
- # Define Generate news protocol.
- generate_news_protocol = Protocol("Get News Details")
-
-
- # Define a handler for the News generation protocol
- @generate_news_protocol.on_message(model=GetNewsDetails, replies=UAgentResponse)
- async def news_details_agent(ctx: Context, sender: str, msg: GetNewsDetails):
- # Logging user request
- ctx.logger.info(
- f"Received ticket request from {sender} with prompt: {msg.news_type} and {msg.news_subtype}") # and {msg.news_subtype}
- # Defining dictionary for country codes
- country_codes = {
- "argentina": "ar", "australia": "au", "austria": "at", "belgium": "be",
- "bulgaria": "bg", "brazil": "br", "canada": "ca", "china": "cn",
- "colombia": "co", "cuba": "cu", "czech republic": "cz", "germany": "de",
- "egypt": "eg", "france": "fr", "united kingdom": "gb", "greece": "gr",
- "hong kong": "hk", "hungary": "hu", "indonesia": "id", "ireland": "ie",
- "israel": "il", "india": "in", "italy": "it", "japan": "jp",
- "south korea": "kr", "lithuania": "lt", "latvia": "lv", "morocco": "ma",
- "mexico": "mx", "malaysia": "my", "nigeria": "ng", "netherlands": "nl",
- "norway": "no", "new zealand": "nz", "philippines": "ph", "poland": "pl",
- "portugal": "pt", "romania": "ro", "serbia": "rs", "russia": "ru",
- "saudi arabia": "sa", "sweden": "se", "singapore": "sg", "slovenia": "si",
- "slovakia": "sk", "thailand": "th", "turkey": "tr", "taiwan": "tw",
- "ukraine": "ua", "united states": "us", "venezuela": "ve", "south africa": "za"
- }
-
- try:
- # Generate news based on the requested category.
- ctx.logger.info('Getting News URL')
- ctx.logger.info(f'User have selected {msg.news_type} type and {msg.news_subtype} subtype')
-
- # Checking news type and getting news url
- if msg.news_type.lower() == 'categorical': # For categorical news type
- main_url = f"https://newsapi.org/v2/top-headlines?country=gb&category={msg.news_subtype}&apiKey={api_key}"
- response = requests.get(main_url).json()
- ctx.logger.info(response)
- # Iterate through the news articles to find a title containing the msg.news
- for article in response['articles']:
- if msg.news_url_content.lower() in article['title'].lower():
- # If found, send the URL back as a clickable link
- news_url = article['url']
- ctx.logger.info(f'Categorical news {news_url}')
- await ctx.send(sender, UAgentResponse(message=str(news_url), type=UAgentResponseType.FINAL))
- elif msg.news_type.lower() == 'regional': # For regional news type
- main_url = f"https://newsapi.org/v2/top-headlines?country={country_codes.get(msg.news_subtype.lower())}&apiKey={api_key}"
- response = requests.get(main_url).json()
- ctx.logger.info(response)
- # Iterate through the news articles to find a title containing the msg.news
- for article in response['articles']:
- if msg.news_url_content.lower() in article['title'].lower():
- # If found, send the URL back as a clickable link
- news_url = article['url']
- ctx.logger.info(f'Regional news {news_url}')
- await ctx.send(sender, UAgentResponse(message=str(news_url), type=UAgentResponseType.FINAL))
-
- elif msg.news_type.lower() == 'keyword': # For Keyword news type
- main_url = f"https://newsapi.org/v2/top-headlines?q={msg.news_subtype}&apiKey={api_key}"
- response = requests.get(main_url).json()
- ctx.logger.info(response)
- # Iterate through the news articles to find a title containing the msg.news
- for article in response['articles']:
- if msg.news_url_content.lower() in article['title'].lower():
- # If found, send the URL back as a clickable link
- news_url = article['url']
- ctx.logger.info(f'Keyword news {news_url}')
- await ctx.send(sender, UAgentResponse(message=str(news_url), type=UAgentResponseType.FINAL))
- else: # If news type is not valid
- await ctx.send(sender, UAgentResponse(message="You have not provided valid news type",
- type=UAgentResponseType.FINAL))
-
- # Handle any exceptions that occur during news generation.
- except Exception as exc:
- ctx.logger.error(f"Error in generating news: {exc}")
-
- # Send an error response with details of the encountered error.
- await ctx.send(
- sender,
- UAgentResponse(
- message=f"Error in generating news: {exc}",
- type=UAgentResponseType.ERROR
- )
- )
-
-
- # Include the Generate News protocol in your agent.
- agent.include(generate_news_protocol)
-
-```
-
-
-
-
-
-
-Now click on the **Run** button in the upper right corner of the editor so that you have your news system agent up and running!
-
-### Generate Categorical News
-
-This secondary function is triggered if the user wants to read categorical news and it provides the the category of news which is subtype in news reading details from options business, entertainment, general, health, science, sports, technology and return specific news titles options as list to **News Reading Details Secondary function**.
-
-
-
-
-
-
-
- ```py copy filename="generate_categorical_news.py"
-
- # Here we demonstrate how we can create a categorical news generating agent that is compatible with DeltaV.
- # After running this agent, it can be registered to DeltaV on Agentverse. For registration you will have to use the agent's address.
-
- # Importing libraries
- import requests
- import json
- from ai_engine import UAgentResponse, UAgentResponseType
-
-
- # Define the Generate News model
- class GenerateNews(Model):
- category: str
-
-
- # Define protocol for categorical news generation
- generate_cat_news_protocol = Protocol("Generate Categorical News")
-
-
- # Define function to generate news according to category in great britain - GB
- async def generate_news(category):
- api_key = 'YOUR_NEWS_API_KEY'
- main_url = f"https://newsapi.org/v2/top-headlines?country=gb&category={category}&apiKey={api_key}"
- news = requests.get(main_url).json()
- # strip the source, get top 10 news and join the list with ' nnn ' to return the news as string and not list (DeltaV compatible type)
- titles = [article['title'].split(' - ')[0].strip() for article in news['articles']]
- titles = titles[:10]
- return titles
-
-
- # Define a handler for the Categorical News generation protocol
- @generate_cat_news_protocol.on_message(model=GenerateNews, replies=UAgentResponse)
- async def on_generate_cat_news_request(ctx: Context, sender: str, msg: GenerateNews):
- # Logging category of news user wants to read
- ctx.logger.info(f"Received ticket request from {sender} with prompt: {msg.category}")
- try:
- # Generate news based on the requested category
- news_titles = generate_news(msg.category)
- # logging news
- ctx.logger.info(news_titles)
- # Send a successful response with the generated news
- await ctx.send(sender, UAgentResponse(message=str(news_titles), type=UAgentResponseType.FINAL))
-
- # Handle any exceptions that occur during news generation
- except Exception as exc:
- ctx.logger.error(f"Error in generating News: {exc}")
- # Send an error response with details of the encountered error.
- await ctx.send(
- sender,
- UAgentResponse(
- message=f"Error in generating News: {exc}",
- type=UAgentResponseType.ERROR
- )
- )
-
-
- # Include the Generate News protocol in your agent
- agent.include(generate_cat_news_protocol)
-
-```
-
-
-
-
-
-
-Remember that you need to provide the `api_key` parameter to correctly run this code. Now click on the **Run** button in the upper right corner of the editor so that you have your news system agent up and running!
-
-### Generate Regional News
-
-This secondary function is triggered if the user wants to read regional or country specific news, it gets country as news subtype **News Reading details Secondary function** and get list of news titles.
-
-
-
-
-
-
-
- ```py copy filename="generate_regional_news.py"
-
- # Import libraries
- import requests
- import json
- from ai_engine import UAgentResponse, UAgentResponseType
-
- # Define dictionary with country codes
- country_codes = {
- "argentina": "ar", "australia": "au", "austria": "at", "belgium": "be",
- "bulgaria": "bg", "brazil": "br", "canada": "ca", "china": "cn",
- "colombia": "co", "cuba": "cu", "czech republic": "cz", "germany": "de",
- "egypt": "eg", "france": "fr", "united kingdom": "gb", "greece": "gr",
- "hong kong": "hk", "hungary": "hu", "indonesia": "id", "ireland": "ie",
- "israel": "il", "india": "in", "italy": "it", "japan": "jp",
- "south korea": "kr", "lithuania": "lt", "latvia": "lv", "morocco": "ma",
- "mexico": "mx", "malaysia": "my", "nigeria": "ng", "netherlands": "nl",
- "norway": "no", "new zealand": "nz", "philippines": "ph", "poland": "pl",
- "portugal": "pt", "romania": "ro", "serbia": "rs", "russia": "ru",
- "saudi arabia": "sa", "sweden": "se", "singapore": "sg", "slovenia": "si",
- "slovakia": "sk", "thailand": "th", "turkey": "tr", "taiwan": "tw",
- "ukraine": "ua", "united states": "us", "venezuela": "ve", "south africa": "za"
- }
-
-
- # Define the Generate News model
- class GenerateNews(Model):
- country: str
-
-
- # Define function to generate regional news according to country
- async def get_regional_news(country):
- api_key = 'YOUR_API_KEY'
- main_url = f"https://newsapi.org/v2/top-headlines?country={country_codes.get(country.lower())}&apiKey={api_key}"
- news = requests.get(main_url).json()
- # Strip the source, get top 10 news and join the list with nnn to return the news as string and not list - DeltaV compatible type
- titles = [article['title'].split(' - ')[0].strip() for article in news['articles']]
- titles = titles[:10]
- return titles
-
-
- # Define protocol for regional news generation Protocol
- generate_news_reg_protocol = Protocol("Generate Regional News")
-
-
- # Define a handler for the Regional News generation protocol
- @generate_news_reg_protocol.on_message(model=GenerateNews, replies=UAgentResponse)
- async def on_generate_news_request(ctx: Context, sender: str, msg: GenerateNews):
- ctx.logger.info(f"Received ticket request from {sender} with prompt: {msg.country}")
- try:
- # Get the country code from the country_code dictionary
- country_code = country_codes.get(msg.country.lower())
- # Generate news based on the requested country and log it on agentverse
- news_titles = await get_regional_news(msg.country)
- ctx.logger.info(f"Message from endpoint: {news_titles}")
- # Send a successful response with the generated news
- await ctx.send(sender, UAgentResponse(message=str(news_titles), type=UAgentResponseType.FINAL))
- # Handle any exceptions that occur during news generation
- except Exception as exc:
- ctx.logger.error(f"Error in generating News: {exc}")
- # Send an error response with details of the encountered error
- await ctx.send(
- sender,
- UAgentResponse(
- message=f"Error in generating News: {exc}",
- type=UAgentResponseType.ERROR
- )
- )
-
-
- # Include the Generate Regional News protocol in your agent
- agent.include(generate_news_reg_protocol)
-
-```
-
-
-
-
-
-
-Remember that you need to provide the `api_key` parameter to correctly run this code. Now click on the **Run** button in the upper right corner of the editor so that you have your news system agent up and running!
-
-### Generate Keyword News
-
-This secondary function is triggered if the user wants to read keyword specific news, it gets keyword as news subtype **News reading details Secondary function** and get list of news titles.
-
-
-
-
-
-
-
- ```py copy filename="generate_keyword_news.py"
-
- # Import libraries
- import requests
- import json
- from ai_engine import UAgentResponse, UAgentResponseType
-
-
- # Define the Generate News model
- class GenerateNews(Model):
- keyword: str
-
-
- # Define protocol for keyword news generation
- generate_news_keyw_protocol = Protocol("Generate Keyword News")
-
-
- # Define function to generate news according to keyword
- async def get_keyword_news(keyword):
- api_key = 'YOUR_API_KEY'
- main_url = f"https://newsapi.org/v2/top-headlines?q={keyword}&apiKey={api_key}"
- news = requests.get(main_url).json()
- # Strip the source, get top 10 news and join the list with nnn to return the news as string and not list - DeltaV compatible type
- titles = [article['title'].split(' - ')[0].strip() for article in news['articles']]
- titles = titles[:10]
- return titles
-
-
- # Define a handler for the Keyword News generation protocol
- @generate_news_keyw_protocol.on_message(model=GenerateNews, replies=UAgentResponse)
- async def on_generate_news_request(ctx: Context, sender: str, msg: GenerateNews):
- ctx.logger.info(f"Received news request from {sender} with prompt: {msg.keyword}")
- # Generate news based on the requested keyword
- try:
- news_titles = get_keyword_news(msg.keyword)
- # Send a successful response with the generated news
- await ctx.send(
- sender,
- UAgentResponse(
- message=str(news_titles),
- type=UAgentResponseType.FINAL
- )
- )
-
- # Handle any exceptions that occur during news generation
- except Exception as exc:
- ctx.logger.error(f"Error in generating News: {exc}")
- # Send an error response with details of the encountered error
- await ctx.send(
- sender,
- UAgentResponse(
- message=f"Error in generating News: {exc}",
- type=UAgentResponseType.ERROR
- )
- )
-
-
- # Include the Generate Keyword News protocol in your agent
- agent.include(generate_news_keyw_protocol)
-
-```
-
-
-
-
-
-
-Remember that you need to provide the `api_key` parameter to correctly run this code. Now click on the **Run** button in the upper right corner of the editor so that you have your news system agent up and running!
-
-## Registering Functions
-
-Let's navigate to the [Agentverse ↗️](https://agentverse.ai) to start registering your agent Functions.
-
-
- For further information on Agent Functions and registration process, see [Register Agent Functions on the Agentverse ↗️](/guides/agentverse/registering-agent-services) resource.
-
-
-
-Considering the local agents in this guide, in order to register **Local Agents and respective Functions** on the Agentverse, you will first need to log in the [Agentverse ↗️](https://agentverse.ai/) and head over to the **My Agents** tab. Then, click on **Local Agents** tab and click one of the **Connect Local Agent** buttons.
-
-
-
-You will need to provide the **local agent address** and make sure it is running on your terminal as only running agents can enroll Agent Functions on the Agentverse!
-
-
-
-
- If you see a message saying **"We couldn't find this agent address on ASI Network"** you will need to wait for some time (around 5 minutes) until the protocols are uploaded successfully on the ASI Network and your agent is retrievable.
-
-
-Once your agent is retrieved correctly, you will see a box depicting it within the **My Agents** tab. Click on it and head over to the **Deploy** tab and click on **+ New Function**. Here, you can now provide the needed details for your Agent Function in the dedicated fields. Remember to provide detailed descriptions for what your **Agent Function** does and the **Fields** for data Models expected. understanding of Functions fields descriptions.
-
-You will need to fill the Agent Function form out with a description for each _Primary_ and _Secondary_ functions. Below you have a full description for each field requested considering the example from this guide.
-
-### News Reading URL System
-
- - **Function title**: just the name of your function; in this example let's call it **News Reading URL System**.
- - **Description for AI Engine**: super important to be as detailed as you can, as reasoning engine looks at descriptions to understand what your function does; in this example we can specify something like "**Always go for Secondary function with ID **news reading details** secondary function. The function provides news clickable hyperlink user wants to read according to their choice.**".
- - **Application**: Primary function.
- - **Protocol** and **Data Model** will be automatically populated based on the source code of [your news reading system agent ↗️](/guides/agents/advanced/utilizing-api-to-build-network-of-task-and-subtask#news-reading-agent).
- - **Field descriptions**:
-
- **news**: _Go for Secondary function with id "news reading details". never ask this to user. This describes news which user wants to read._
-
-Click **Save** button after filling out the form.
-
-### News Reading Details Secondary function
-
- - **Function title**: just the name of your function; in this example let's call it **News Reading details**.
- - **Description for AI Engine**: super important to be as detailed as you can, as reasoning engine looks at descriptions to understand what your function does; in this example we can specify something like "**This function takes different details for news reading from user. This is triggered always after News Reading url system.**
- - **Application**: Secondary function.
- - **Protocol** and **Data Model** will be automatically populated based on the source code of [your news generating agent ↗️](/guides/agents/advanced/utilizing-api-to-build-network-of-task-and-subtask#news-generating-agent).
- - **Field descriptions**: Below are the field descriptions for News reading system.
- - **news_subtype**: _This describes the news subtype user wants to read and ask for question corresponding to user's choice of news type below. Only ask one of the below to user:_
-
- - **'categorical'**: _One from list [business, entertainment, general, health, science, sports, technology]._
- - **'regional'**: _What is the country you want to get news for?_
- - **'keyword'**: _What is the keyword you want to read news for?_
-
- - **news_type**: _This is type of news user wants to read from options from Categorical, Regional or Keyword. After this ask user for field news_subtype._
- - **news_url_content**: _Trigger corresponding secondary function according to 'news_type' given by user to get this field:_
-
- - **Categorical**: _Generate Categorical news Secondary function._
- - **Regional**: _Generate Regional News Secondary function._
- - **Keyword**: _Generate Keyword News Secondary function._
-
- _This provides list of relevant news options, ask user which news they want to read._
- _user category, keyword and country as provided by user in field 'news_subtype'._
-
-Click **Save** button after filling out the form.
-
-### Generate Categorical News
-
- - **Function title**: just the name of your service; in this example let's call it **Generate Categorical News**.
- - **Description for AI Engine**: Super important to be as detailed as you can, as reasoning engine looks at descriptions to understand what your function does; in this example we can specify something like "**This function helps generate list of options for categorical news for the user. Give these options to user and ask let them select the option they want to choose.**".
- - **Application**: Secondary function.
- - **Protocol** and **Data Model** will be automatically populated based on the source code of [your generate categorical Agent ↗️](/guides/agents/advanced/utilizing-api-to-build-network-of-task-and-subtask#generate-categorical-news).
- - **Field descriptions**:
- - **category**: _this is provided by user in news subtype in news reading details. This is category for which user want to read news._
-
-Click **Save** button after filling out the form.
-
-### Generate Regional News Secondary function
-
- - **Function title**: just the name of your function; in this example let's call it **Generate Regional news**.
- - **Description for AI Engine**: super important to be as detailed as you can, as reasoning engine looks at descriptions to understand what your function does - in this example we can specify something like "**This function helps generate list of options for regional news for the user. Give these options to user and ask let them select the option they want to choose.**".
- - **Application**: Secondary functions.
- - **Protocol** and **Data Model** will be automatically populated based on the source code of [your generate regional Agent ↗️](/guides/agents/advanced/utilizing-api-to-build-network-of-task-and-subtask#generate-regional-news).
- - **Field descriptions**:
- - **country**: _this is provided by user in news subtype in news reading details. This is country for which user want to read news._
-
-Click **Save** button after filling out the form.
-
-### Generate Keyword News Secondary function
-
- - **Function title**: just the name of your function; in this example let's call it **Generate Keyword**.
- - **Description for AI Engine**: super important to be as detailed as you can, as reasoning engine looks at descriptions to understand what your function does; in this example we can specify something like "**This function helps generate list of options for keyword news for the user. Give these options to user and ask let them select the option they want to choose.**".
- - **Application**: Secondary function.
- - **Protocol** and **Data Model** will be automatically populated based on the source code of [your generate keyword Agent ↗️](/guides/agents/advanced/utilizing-api-to-build-network-of-task-and-subtask#generate-keyword-news).
- - **Field descriptions**:
- - **keyword**: _this is provided by user in news subtype in news reading details. This is keyword for which user want to read news._
-
-Click **Save** button after filling out the form
-
-## Let's Find our Function on deltaV
-
-Now, head to [DeltaV ↗️](https://deltav.agentverse.ai/) and sign in.
-
-Firstly, type in something like **I want to read news of my choice** into what function you would like to assemble and switch on **Advanced Options**. In advanced options select **All function groups** and click on **submit** button.
-
-
- We encourage everyone operating on DeltaV to select the **Next Generation** AI Engine personality type. This AI Engine personality stands as a significant personality type offering _enhanced scalability_, _reliability_, and _flexibility_. The major key features include advanced context understanding, improved function recommendations, and the ability to handle multiple dialogue formats.
-
-
-
-
-After being navigated to the chat screen, you will be asked to select an Objective (function).
-
-As your objective (`I want to read news of my choice`) specified on the previous screen contained words related to the description of your news reading system agent, your News Reading URL System function is listed as an option.
-
-Let's select it.
-
-
-
-**News Reading Details Secondary function** will be triggered once we select **News Reading URL System** and it will provide options as mentioned in field description for **News Reading Secondary Function**.
-
-Select the news type and subtype you want to read.
-
-
-
-
-
-Once you select the news type respective Secondary functions will be triggered as mentioned in [objective description ↗️](/guides/agents/advanced/utilizing-api-to-build-network-of-task-and-subtask#news-reading-details-subtask) for **Generate news_type secondary function**.
-
-The respective **Generate news_type secondary function** will fetch _category_, _country_ or _keyword_ based on news type and subtype selected and will generate _top news_ related to news subtype provided.
-
-The news list will be passed from **Generate news_type Secondary functions** to **News Reading Details Secondary functions** and user can select one title.
-
-Chosen news title URL will be fetched and provided to **News Reading URL system** and User will get clickable link to read news in details.
-
-
-
-
-
-
-
-
-
-With that, **you have gotten a news reading url service which can be discovered and contacted with DeltaV. Awesome!**
-
-
- If one of multiple secondary functions is to be triggered, it should be mentioned in dictionary rather than writing a description of each as it confuses the DeltaV LLM model. If we mention **"Trigger generate categorical secondary functions for user selecting categorical news and trigger generate regional for user selecting regional news and so on...."**, will lead to either non-traceability of secondary functions or wrong selection of secondary functions.
-
diff --git a/pages/guides/agents/getting-started/_meta.json b/pages/guides/agents/getting-started/_meta.json
deleted file mode 100644
index 00391ac60..000000000
--- a/pages/guides/agents/getting-started/_meta.json
+++ /dev/null
@@ -1,25 +0,0 @@
-{
- "whats-an-agent": {
- "title": "What's an Agent?",
- "tags": ["Beginner", "Python"],
- "timestamp": true
- },
- "installing-uagent": {
- "title": "uAgents Framework installation",
- "tags": ["Beginner", "Python"],
- "timestamp": true
- },
- "create-a-uagent": {
- "title": "Create your first agent",
- "tags": ["Beginner", "Python", "Local"],
- "timestamp": true
- },
- "seedphrase": "Seed phrase",
- "getting-uagent-address": {
- "title": "Agents address",
- "tags": ["Beginner", "Python", "Address", "Local"],
- "timestamp": true
- },
- "almanac": "Almanac",
- "fet-token-for-agents": "Agent Funds"
-}
diff --git a/pages/guides/agents/getting-started/almanac.mdx b/pages/guides/agents/getting-started/almanac.mdx
deleted file mode 100644
index 5b9cabe0a..000000000
--- a/pages/guides/agents/getting-started/almanac.mdx
+++ /dev/null
@@ -1,13 +0,0 @@
-import { Callout } from 'nextra/components'
-
-# Almanac contract, registering, searching and discovery
-
-The [Almanac ↗️](/references/contracts/uagents-almanac/almanac-overview) contract is a decentralised register of all agents that are available in the system. Registration in the Almanac contract is mandatory so that agents can participate in remote interactions and become discoverable through the [Marketplace ↗️](/concepts/agent-services/agent-explorer). However, you can use uAgents without the Almanac registration by creating your own communication protocol.
-
-Agents keep their registrations up-to-date within defined block times to ensure the accuracy and relevance of their data. Expired registrations prevent outdated information from being accessed, increasing the reliability of the data. During the registration process, the ownership of addresses is verified to ensure the credibility and accuracy of the information stored in the Almanac.
-
-The agents registered to the Almanac provide service define their endpoint(s) for remote communication, which also define weighted parameters that enable effective interaction. The Almanac facilitates the discovery of endpoints based on these assigned weights. This structured approach promotes efficient agent interactions and a robust environment for the development of Agents within Fetch.ai's decentralized network.
-
-
- Check out the [Registering in the Almanac contract ↗️](/guides/agents/register-in-almanac) guide and the [Registration and endpoints weighting ↗️](/references/contracts/uagents-almanac/endpoints) for additional information on the registration process.
-
\ No newline at end of file
diff --git a/pages/guides/agents/getting-started/create-a-uagent.mdx b/pages/guides/agents/getting-started/create-a-uagent.mdx
deleted file mode 100644
index 02542a94f..000000000
--- a/pages/guides/agents/getting-started/create-a-uagent.mdx
+++ /dev/null
@@ -1,159 +0,0 @@
-import { CodeGroup, CodeSegment, DocsCode, GithubCodeSegment } from "../../../../components/code";
-
-# Creating your first agent
-
-## Introduction
-
-Once you've [installed ↗️](/guides/agents/installing-uagent) the uAgents library, it's quite simple to get a minimal use case running.
-
-The uAgents Framework simplifies Agents creation, and enables Agents communication, discovery, and publication on the Fetch.ai network. The Framework supports building Agents using anything from advanced Large Language Models (LLMs) to basic APIs.
-
-Let's start with a simple Agent that initializes and prints its name and address
-
-## Prerequisites
-
-Make sure you have read the following resources before going on with this guide:
-
- - [Quick Start Guide for uAgents Framework ↗️](/guides/agents/quickstart)
- - [Agents address ↗️](/guides/agents/getting-started/getting-uagent-address)
-
-## Imports needed
-
- - [uAgents ↗️](https://pypi.org/project/uagents/)
-
-### The agent
-
-1. Let's create a Python script for this task, and name it by running:
-
-
-
- ```py copy filename="mac"
- touch first_agent.py
- ```
-
-
-
- ```py copy filename="windows"
- echo. > first_agent.py
- ```
-
-
-
- ```py copy filename="ubuntu"
- touch first_agent.py
- ```
-
-
-
-2. We then need to import the `Agent` and `Context` classes from the `uagents` library, and then create an agent using the class `Agent`:
-
-
-
-
-
-
-
- ```py copy filename="first_agent.py"
-
- from uagents import Agent, Context
-
- agent = Agent(name="alice", seed="secret_seed_phrase", port=8000, endpoint=["http://localhost:8000/submit"])
-
-```
-
-
-
-
-
-
- It is optional but useful to include a `seed` parameter when creating an agent to set fixed [addresses ↗️](/guides/agents/getting-uagent-address). Otherwise, random addresses will be generated every time you run the agent. Your address is kind of important, as this is how other agents will identify you.
-
-3. Let's define a `say_hello()` function for our agent to print a message periodically saying `hello, my name is ...`:
-
-
-
-
-
-
-
- ```py copy filename="first_agent.py"
-
- @agent.on_event("startup")
- async def introduce_agent(ctx: Context):
- ctx.logger.info(f"Hello, I'm agent {agent.name} and my address is {agent.address}.")
-
- if __name__ == "__main__":
- agent.run()
-
-```
-
-
-
-
-
-
- The `.on_event("startup")` decorator defines a behavior for this agent when it is run. In this case, the agent will execute the `say_hello()` function when the agent starts. The `Context` object is a collection of data and functions related to the agent. In this case, we just use the agent's `name`, `alice`. The agent executes the function and uses the `ctx.logger.info()` method to print the message.
-
-4. Save the script.
-
-The overall script should look as follows:
-
-
-
-
-
-
-
- ```py copy filename="first_agent.py"
-
- from uagents import Agent, Context
-
- agent = Agent(name="alice", seed="secret_seed_phrase", port=8000, endpoint=["http://localhost:8000/submit"])
-
- @agent.on_event("startup")
- async def introduce_agent(ctx: Context):
- ctx.logger.info(f"Hello, I'm agent {agent.name} and my address is {agent.address}.")
-
- if __name__ == "__main__":
- agent.run()
-
-```
-
-
-
-
-
-
-### Run your agent
-
-Make sure to have activated your virtual environment correctly.
-
-Run the script: `python first_agent.py`
-
-The output would be:
-
- ```
- INFO: [alice]: Registration on Almanac API successful
- INFO: [alice]: Registering on almanac contract...
- INFO: [alice]: Registering on almanac contract...complete
- INFO: [alice]: Agent inspector available at https://agentverse.ai/inspect/?uri=http%3A//127.0.0.1%3A8000&address=agent1qtu6wt5jphhmdjau0hdhc002ashzjnueqe89gvvuln8mawm3m0xrwmn9a76
- INFO: [alice]: Starting server on http://0.0.0.0:8000 (Press CTRL+C to quit)
- INFO: [alice]: Hello, I'm agent alice and my address is agent1qtu6wt5jphhmdjau0hdhc002ashzjnueqe89gvvuln8mawm3m0xrwmn9a76.
- ```
-
-**Congratulations, you have just created your first Agent!**
diff --git a/pages/guides/agents/getting-started/fet-token-for-agents.mdx b/pages/guides/agents/getting-started/fet-token-for-agents.mdx
deleted file mode 100644
index fab0b7d24..000000000
--- a/pages/guides/agents/getting-started/fet-token-for-agents.mdx
+++ /dev/null
@@ -1,92 +0,0 @@
-import { Callout } from 'nextra/components'
-
-# Getting Started with FET Token for Agent development
-
-
- This is currently a work in progress and may be subject to further updates and revisions.
-
-
-## Introduction
-
-The FET token was created to facilitate payments in an Agentic ecosystem, these are micro payments to one another which traditional currencies do not support. FET tokens are used for agent Almanac registration, and wider contract interactions.
-
-## Acquiring FET Tokens
-
-Exchanges are the simplest way to get FET tokens.
-
-Visit a trusted exchange such as Coinbase or Binance. You may need to create an account, which will involve you
-passing [KYC ↗️](https://www.gov.uk/government/publications/know-your-customer-guidance/know-your-customer-guidance-accessible-version). Once your account is enabled, you can buy FET token. You can buy this with most global
-currencies, just check on the exchange which currencies they accept.
-
-## Storing FET
-
-Ideally you would be sending this FET to your agent to transact on the network. However, if you'd like greater
-security or accessibility.
-
-For short-term storage goals, the ASI Wallet is an excellent choice; it provides direct functionalities for daily activities such as staking and interacting with Agents.
-
-For long-term storage goals, you can enhance security by integrating your ASI Wallet with a hardware wallet like Ledger, offering robust protection for your assets. Follow this guide [here ↗️](/guides/fetch-network/asi-wallet/asi-wallet-hardware-connection-guide) if you wish to set up the ASI Alliance extension wallet with a Ledger hardware wallet.
-
-## How to transfer tokens to your Agents
-
-You can download and use the uAgents library to create autonomous Agents capable of interacting with other Agents in a decentralized environment. Check out this guide [here ↗️](/guides/agents/getting-started/installing-uagent) to get started with Agents development.
-
-In order to get your Agent up and running within the ASI Ecosystem, you will need to retrieve the Agent's address and fund it with FET tokens to make it correctly register within the network.
-
-
- When creating your account, it is crucial to securely store your [seed phrase ↗️](/guides/agents/getting-started/seedphrase). The seed phrase is essential for accessing your Agent's identity and controlling any funds it holds. Treat it with the highest level of security to prevent unauthorized access!
-
-
-### Getting your Agent address to send tokens to your Agent
-
-The following Python script demonstrates how to create and initialize an Agent using the `uagents` and `cosmpy` libraries, to connect it to the Fetch.ai Mainnet, and retrieve its address and balance information:
-
- ```py copy filename="agent_address_and_balance.py"
- from uagents import Agent, Context
- import cosmpy
-
- from cosmpy.aerial.client import LedgerClient, NetworkConfig
-
- agent = Agent(name="alice", seed="", port=8000, test=False, endpoint=["http://localhost:8000/submit"])
-
- @agent.on_event("startup")
- async def introduce_agent(ctx: Context):
- ctx.logger.info(f"ASI network address:{agent.wallet.address()}")
- ledger_client = LedgerClient(NetworkConfig.fetch_mainnet())
- address: str = agent.wallet.address()
- balances = ledger_client.query_bank_all_balances(address)
- ctx.logger.info(f"Balance of addr: {balances}")
-
- if __name__ == "__main__":
- agent.run()
-
- ```
-
-**You must update the seed value, and store it safely. Losing this value will lose you your tokens.**
-
-In the code example above an Agent named `alice` is initialized with a specified `name`, `port`, `endpoint`, and `seed`
-parameters. When the Agent starts up, it logs the wallet address and queries the balance using the `LedgerClient` connected to the Fetch.ai Mainnet. Finally, the script runs the Agent, which processes the `startup` event and retrieves the balance, allowing the Agent to interact with the Fetch.ai network.
-
-Once you run the above Agent script, you will see your Agent address and balance printed out. You will see something similar to the following output:
-
- ```
- INFO: [alice]: Registration on Almanac API successful
- INFO: [alice]: Registering on almanac contract...
- INFO: [alice]: Registering on almanac contract...complete
- INFO: [alice]: Agent inspector available at https://agentverse.ai/inspect/?uri=http%3A//127.0.0.1%3A8000&address=agent1qdxdrwqek4pt9xt8kggcxus0zm54d4vgdznrs6y5acn26paphervwfj7pdd
- INFO: [alice]: Starting server on http://0.0.0.0:8000 (Press CTRL+C to quit)
- INFO: [alice]: ASI network address:fetch1ujr7wyuvza7uwnkr3usv53hjlwjvu8s7l06vzf
- INFO: [alice]: Balance of addr: []
- ```
-
-You can now use this address to transfer your purchased FET tokens from the exchange to this Agent's address. This
-should be as simple as withdrawing native FET, by selecting the Fetch.ai Mainnet network when withdrawing. Some
-exchanges do not support Native FET, and you will need to use the [token bridge](https://token-bridge.fetch.ai/),
-luckily we have [a guide for that too](/guides/fetch-network/how-to-convert-fet-to-and-from-erc20)
-
-Check out the following resources for more information on Agents and how these integrate within the ASI Ecosystem and perform operations using FET tokens:
-
-- [Agents - uAgents Framework ↗️](/guides/agents/getting-started/whats-an-agent)
-- [The Agentverse ↗️](/concepts/agent-services/agentverse-intro)
-- [AI Engine ↗️](/concepts/ai-engine/ai-engine-intro)
-- [DeltaV ↗️](/concepts/ai-engine/deltav)
diff --git a/pages/guides/agents/getting-started/getting-uagent-address.mdx b/pages/guides/agents/getting-started/getting-uagent-address.mdx
deleted file mode 100644
index 568407aab..000000000
--- a/pages/guides/agents/getting-started/getting-uagent-address.mdx
+++ /dev/null
@@ -1,314 +0,0 @@
-import { CodeGroup, CodeSegment, DocsCode, GithubCodeSegment } from "../../../../components/code";
-
-# Agents address
-
-## Introduction
-
-Agents within the ASI Ecosystem are characterized by different addresses. These can allow the agent to perform different actions, including sending messages or interacting with the [Almanac contract ↗️](/references/contracts/uagents-almanac/almanac-overview).
-
-It is possible to distinguish between two different types of addresses:
-
- - `uAgent address`: this address identifies the agent within the ASI Network. It's similar to a username within a chat platform, allowing other agents to discover and communicate with that specific agent by querying that agent's information from the Almanac contract.
-
- - `ASI network address`: this address is linked to the agent's wallet on the ASI network. It is essential to perform multiple functionalities like holding cryptocurrency, interacting with the [Fetch Ledger ↗️](/concepts/fetch-network/ledger/intro) and performing secure transactions. This address is needed to register an agent to the [Almanac ↗️](/concepts/fetch-network/almanac) contract. Note, you must ensure the agents has enough funds available to perform operations in the ASI Network, however this is all done automatically and no funds are currently required.
-
-If you want to retrieve the address of an agent, you can either use the `print()` function and specify which of the above addresses you wish to print out, or by calling the `.address()` or `.wallet.address()` methods using the `agent` object to retrieve specific information.
-
-**Let's now check how these ways of retrieving addresses look like!**
-
-## Prerequisites
-
-Make sure you have read the following resources before going on with this guide:
-
- - [Quick Start Guide for uAgents Framework ↗️](/guides/agents/quickstart)
- - [Creating your first agent ↗️](/guides/agents/getting-started/create-a-uagent)
-
-## Imports needed
-
- - [uAgents ↗️](https://pypi.org/project/uagents/)
-
-## Print uAgent address
-
-You can print the `uAgent address` related to your agent in the following way:
-
-1. First of all, create a Python script and name it:
-
-
-
- ```py copy filename="mac"
- touch uagent_address.py
- ```
-
-
-
- ```py copy filename="windows"
- echo. > uagent_address.py
- ```
-
-
-
- ```py copy filename="ubuntu"
- touch uagent_address.py
- ```
-
-
-
-2. We then need to import the `Agent` class from the `uagents` library to create an agent, `alice`. Then, using the `print()` function, we will print the related `uAgent address`. Importantly, remember that the `seed` parameter is used, when creating an agent, to set fixed addresses, otherwise a random address will be generated every time you run the agent:
-
-
-
-
-
-
-
- ```py copy filename="uagent_address.py"
-
- from uagents import Agent
-
- agent = Agent(name="alice", seed="alice recovery phrase", port=8000, endpoint=["http://127.0.0.1:8000/submit"])
-
- print("uAgent address: ", agent.address)
-
- if __name__ == "__main__":
- agent.run()
-
-```
-
-
-
-
-
-
-3. Save the script.
-
-The output would be as follows:
-
- ```
- uAgent address: agent1qww3ju3h6kfcuqf54gkghvt2pqe8qp97a7nzm2vp8plfxflc0epzcjsv79t
- INFO: [alice]: Registration on Almanac API successful
- INFO: [alice]: Registering on almanac contract...
- INFO: [alice]: Registering on almanac contract...complete
- INFO: [alice]: Agent inspector available at https://agentverse.ai/inspect/?uri=http%3A//127.0.0.1%3A8000&address=agent1qww3ju3h6kfcuqf54gkghvt2pqe8qp97a7nzm2vp8plfxflc0epzcjsv79t
- INFO: [alice]: Starting server on http://0.0.0.0:8000 (Press CTRL+C to quit)
- ```
-
-## Print ASI network address
-
-You can print the `ASI network address` related to your agent in the following way:
-
-1. Let's create a Python script, and name it:
-
-
-
- ```py copy filename="mac"
- touch fetch_address.py
- ```
-
-
-
- ```py copy filename="windows"
- echo. > fetch_address.py
- ```
-
-
-
- ```py copy filename="ubuntu"
- touch fetch_address.py
- ```
-
-
-
-2. As before, we first need to import the `Agent` class from the `uagents` library to create an Agent, `alice`. Then, using the `print()` function, we will print the related `ASI Network address`:
-
-
-
-
-
-
-
- ```py copy filename="fetch_address.py"
-
- from uagents import Agent
-
- agent = Agent(name="alice", seed="alice recovery phrase", port=8000, endpoint=["http://127.0.0.1:8000/submit"])
-
- print("ASI network address: ", agent.wallet.address())
-
- if __name__ == "__main__":
- agent.run()
-
-```
-
-
-
-
-
-
-3. Save the script.
-
-The output would be as follows:
-
- ```
- ASI network address: fetch1454hu0n9eszzg8p7mvan3ep7484jxl5mkf9phg
- INFO: [alice]: Registration on Almanac API successful
- INFO: [alice]: Registering on almanac contract...
- INFO: [alice]: Registering on almanac contract...complete
- INFO: [alice]: Agent inspector available at https://agentverse.ai/inspect/?uri=http%3A//127.0.0.1%3A8000&address=agent1qww3ju3h6kfcuqf54gkghvt2pqe8qp97a7nzm2vp8plfxflc0epzcjsv79t
- INFO: [alice]: Starting server on http://0.0.0.0:8000 (Press CTRL+C to quit)
- ```
-
-## Print agent name and address using `name` and `address` methods
-
-In this guide, we aim at showing how to create an agent being able to say hello and printing its `name` and `address` using the `uagents` library tools. Indeed, it is possible to retrieve the `name` and `address` of any agent directly from the `agent` object representing the agent you create and initialize. More specifically, we refer to the following methods:
-
- - `.name()`: this returns the provided name of the agent, if specified, otherwise, if the agent's name is not explicitly set, then it will use the first ten characters of the agent's address as its name.
-
- - `.address()`: this returns the unique address of the agent in the form `agent1...`. This address is essential for other agents to interact with your agent.
-
-**Let's get started and use the `agent` object to make our agent print its name and address!**
-
-### Walk-through
-
-1. First of all, you need to create a Python script and name it:
-
-
-
- ```py copy filename="mac"
- touch my_agent.py
- ```
-
-
-
- ```py copy filename="windows"
- echo. > my_agent.py
- ```
-
-
-
- ```py copy filename="ubuntu"
- touch my_agent.py
- ```
-
-
-
-2. We then need to import the necessary classes `Agent` and `Context` from the `uagents` library, and then create an instance of the `Agent` class, `alice`. Below you can see the `agent` object being initialized:
-
-
-
-
-
-
-
- ```py copy filename="my_agent.py"
-
- from uagents import Agent, Context
-
- agent = Agent(name="alice", seed="alice recovery phrase", port=8000, endpoint=["http://127.0.0.1:8000/submit"])
-
-```
-
-
-
-
-
-
-3. We would then need to assign the agent the behavior to be executed. In this case, `agent` could send a message when it is being run saying hello and printing its `name` and `address` using the `agent` object:
-
-
-
-
-
-
-
- ```py copy filename="my_agent.py"
-
- @agent.on_event("startup")
- async def introduce_agent(ctx: Context):
- ctx.logger.info(f"Hello, I'm agent {agent.name} and my address is {agent.address}.")
-
- if __name__ == "__main__":
- agent.run()
-
-```
-
-
-
-
-
-
- This `introduce_agent()` function takes a single argument `ctx` of type `Context`. The message is printed out using the `ctx.logger.info()` method, and includes the agent's name obtained from attribute `name` and retrieved using `agent.name()` method. The same for the agent's address, which is obtained from attribute `address` and retrieved using `agent.address()` method.
-
-4. Save the script.
-
-The overall script should look as follows:
-
-
-
-
-
-
-
- ```py copy filename="my_agent.py"
-
- from uagents import Agent, Context
-
- agent = Agent(name="alice", seed="alice recovery phrase", port=8000, endpoint=["http://127.0.0.1:8000/submit"])
-
- @agent.on_event("startup")
- async def introduce_agent(ctx: Context):
- ctx.logger.info(f"Hello, I'm agent {agent.name} and my address is {agent.address}.")
-
- if __name__ == "__main__":
- agent.run()
-
-```
-
-
-
-
-
-
-### Run the script
-
-On your terminal, run the script: `python my_agent.py`
-
-The output should be as follows:
-
- ```
- INFO: [alice]: Registration on Almanac API successful
- INFO: [alice]: Registering on almanac contract...
- INFO: [alice]: Registering on almanac contract...complete
- INFO: [alice]: Agent inspector available at https://agentverse.ai/inspect/?uri=http%3A//127.0.0.1%3A8000&address=agent1qww3ju3h6kfcuqf54gkghvt2pqe8qp97a7nzm2vp8plfxflc0epzcjsv79t
- INFO: [alice]: Hello, I'm agent alice and my address is agent1qww3ju3h6kfcuqf54gkghvt2pqe8qp97a7nzm2vp8plfxflc0epzcjsv79t.
- INFO: [alice]: Starting server on http://0.0.0.0:8000 (Press CTRL+C to quit)
- ```
diff --git a/pages/guides/agents/getting-started/installing-uagent.mdx b/pages/guides/agents/getting-started/installing-uagent.mdx
deleted file mode 100644
index a7348715b..000000000
--- a/pages/guides/agents/getting-started/installing-uagent.mdx
+++ /dev/null
@@ -1,162 +0,0 @@
-import { Callout } from 'nextra/components'
-import PackageVersion from 'components/package-version'
-
-# Installing the uAgents Framework
-
-## System Requirements
-
-Fetch.ai's [uagents ↗️](https://pypi.org/project/uagents/) Frameworks package is a Python library running on Ubuntu/Debian, MacOS, and Windows systems.
-
-On your computer, you may need to install:
-
- - [Python ↗️](https://www.python.org/downloads/) 3.8+.
- - [PIP ↗️](https://pypi.org/project/pip/) - the Python package manager.
- - [uAgents library ↗️](https://pypi.org/project/uagents/)
-
-## Install with Pip
-
- 1. Create a directory for your agents project: `mkdir directory_name`
-
- 2. Install Fetch.ai `uagents` library: `pip install uagents`
-
- 3. Check if installation was successful: `pip show uagents`
-
-## Install from source code
-
- 1. Download the latest released version from Github and navigate to the agents directory:
-
- ```py
- git clone https://github.com/fetchai/uAgents.git
- cd uAgents
- ```
-
- 2. Install the required dependencies:
-
- ```py
- poetry install
- ```
-
- 3. Open the virtual environment:
-
- ```py
- poetry shell
- ```
-
-## Troubleshooting
-
-It is possible that you may face issues during the installation process. Here, you can find common problems and their solutions.
-
-
- **Problem (MacOS/Python 3.11)**: `Installing coincurve (17.0.0): Failed`
-
- **Solution**: install the latest versions of `automake`, `autoconf`, and `libtool`: `brew install automake autoconf libtool`
-
-
-For any other problems, please let us know by creating an [issue ↗️](https://github.com/fetchai/uAgents/issues).
-
-## Simplified Installation for Windows users
-
-Installing the uagents framework on a Windows machine is a straightforward process. The `uagents` library is a Python package, so you'll need to have Python installed on your system before you can use it.
-
-If you don't already have Python installed on your Windows machine, visit the official Python website at [Python ↗️](https://www.python.org/downloads/windows/) and download the latest stable version of Python for Windows.
-
-Run the downloaded installer executable file (e.g., python-3.x.x.exe).
-
-During installation, make sure to check the box that says "Add Python X.X to PATH." This will automatically add Python to your system's PATH variable, making it easier to use from the command line.
-
-### Install uagents library using pip
-
-Once you have Python installed and added to your PATH, follow these steps to install the uagents framework using pip:
-
- 1. To install using PIP open your terminal. To ensure that PIP (Python's package manager) is up-to-date, run the following command:
-
- ```
- python -m pip install --upgrade pip
- ```
-
- 2. Now, you can install the `uagents` framework by running the following command:
-
- ```
- pip install uagents
- ```
-
-PIP will download and install the `uagents` package and its dependencies. Wait for the process to complete. To verify the complete installation explore your terminal. As part of the installation you will see a message showcasing the completion of the installation as well as the exact version.
-
-## Installing other essential python libraries
-
-### Installing AI Engine library
-
-If you wish to create [AI Engine ↗️](/concepts/ai-engine/ai-engine-intro) compatible Agents, you will need to get the `uagents-ai-engine` package installed. Checkout the [AI Engine package ↗️](https://pypi.org/project/uagents-ai-engine/) to download it and start developing your AI Engine compatible Agents.
-
-You can install AI Engine with pip: `pip install uagents-ai-engine`
-
-
- Explore the additional resources we have on AI Engine compatible Agents:
- - [DeltaV ↗️](/concepts/ai-engine/deltav)
- - [Agent Functions ↗️](/guides/agents/intermediate/agent-functions)
- - [Make your agents AI Engine compatible ↗️](/guides/agents/intermediate/ai-engine-compatible-agent)
- - [Register Agent Functions ↗️](/guides/agentverse/agentverse-functions/registering-agent-services)
-
-
-
- Current version of the package AI Engine is .
-
-
-## Development tools
-
-#### Installing Homebrew
-
-**Homebrew** streamlines software installations on MacOS via the command line. To install and update Homebrew, execute the following commands:
-
- ```
- /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
- ```
-
-You can verify it [here ↗️](https://brew.sh/). Let's then ensure Homebrew is updated:
-
- ```
- brew update
- ```
-
-
- For more information on Homebrew explore their [website ↗️](https://brew.sh/).
-
-
-#### Installing PyEnv
-
-Now, you need to install **PyEnv**. It is a simple tool to manage multiple versions of Python. Run:
-
- ```
- brew install pyenv
- ```
-
-Once you have installed PyEnv you can configure the shell environment:
-
- ```
- echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.zshrc
- echo 'command -v pyenv >/dev/null || export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.zshrc
- echo 'eval "$(pyenv init -)"' >> ~/.zshrc
- ```
-
-
- These commands configure your shell environment (specifically the **Zsh shell**) to work with PyEnv. These commands set up environment variables, modify the PATH, and initialize PyEnv so that you can easily manage and switch between different Python versions. You can verify all steps [here ↗️](https://github.com/pyenv/pyenv#installation).
-
-
-You are now ready to **install Python** if you haven't done it yet. You need to install a version of Python 3.8 or above (for this example, we use version 3.10):
-
- ```
- pyenv install 3.10
- ```
-
-You can get help or check a command insights by running:
-
- ```
- pyenv help
- ```
-
-Let's now ensure the **global version of Python** you are working with is not the default one in the system. Run:
-
- ```
- pyenv global 3.10 # this sets the global interpreter
- pyenv versions # this verifies if it is set up correctly
- ```
\ No newline at end of file
diff --git a/pages/guides/agents/getting-started/seedphrase.mdx b/pages/guides/agents/getting-started/seedphrase.mdx
deleted file mode 100644
index 0baa99ab7..000000000
--- a/pages/guides/agents/getting-started/seedphrase.mdx
+++ /dev/null
@@ -1,7 +0,0 @@
-# Seed phrases
-
-Imagine you have a treasure chest full of your code, but instead of a key, it has a secret password to open it. This password is made up of any characters you choose. This "password" is your seed phrase, when you create one make it really complicated.
-
-If you remember your seed phrase, you can open your treasure chest anytime, anywhere, even if you lose the chest. In our case, our chest is our agent identity. However, if someone else learns your seed phrase, they can impersonate your agent! Not just impersonate, but they would also have access to the wallet of the agent. So, it's super important to keep the seed phrase safe, like hiding it in a secret place or writing it down where no one can find it. Never tell anyone your seed phrase unless you really, really trust them!
-
-uAgents creates an address for your agent cryptographically with your defined seed phrase, this all happens out of view in the uAgents library [view the src](https://github.com/fetchai/uAgents/blob/3a76aa0f364fcd6464562f495d722fe80568a24b/python/src/uagents/agent.py#L425).
diff --git a/pages/guides/agents/getting-started/whats-an-agent.mdx b/pages/guides/agents/getting-started/whats-an-agent.mdx
deleted file mode 100644
index 7ea122833..000000000
--- a/pages/guides/agents/getting-started/whats-an-agent.mdx
+++ /dev/null
@@ -1,78 +0,0 @@
-import { Callout } from 'nextra/components'
-import { ImageByTheme } from "components/mdx"
-import PackageVersion from 'components/package-version'
-import communication from 'src/images/concepts/tech/I2.svg';
-
-# Agents - uAgents Framework
-
-## Introduction
-
-The **uAgents Framework** is a lightweight library designed to facilitate the development of decentralized **Agents**. Agents in a multi-agent system can communicate with any, and all agents in the system to solve problems, execute tasks and transact.
-
-
- Head over to the [uagents package ↗️](https://pypi.org/project/uagents/) to download it and start developing your Agents!
-
- Current version of the uAgents package is .
-
-
-
-### Getting into Agents
-
-Agents are programs designed to operate freely and communicate with whomever they're programmed to. Agents can connect, search, and transact in order to create dynamic markets, and they can be programmed to interact both within their environment and with other agents in the network. Because they're siloed, and decentralized they can safely accomplish particular activities and objectives without requiring human participation. We have a very simple guide in our documentation that gets you started on building an agent to be part [of the network ↗️](/guides/agents/getting-started/create-a-uagent).
-
-
-At the simplest level, and agent would work as follows:
-
-
-
-
-
-Of course, many agents in the above workflow can come together to become multi-agents workflows, where single Agents call one another to complete a task. Agents that you design could be programmed to contact known agents, whereas in a dynamic marketplace you may need an agent that you haven't created, searching and interacting with that agent may be the more optimal strategy.
-
-
-
-A simple Agent using the uAgents library could be:
-
-```
-from uagents import Agent, Context, Model
-
-agent = Agent(name="concept", seed="secret_seed_phrase_concept", endpoint="127.0.0.1", port="8001")
-
-class Message(Model):
- message : str
-
-
-@agent.on_message(model=Message)
-async def print_message(ctx: Context, msg : Message):
- ctx.logger.info(f"Message received: {msg.message}")
-
-if __name__ == "__main__":
- agent.run()
-```
-
-This Agent defines its communication method as receiving any Object of `Class Message`, with a value for `message` of type `string`. You can see how this agent behaves, and how to extend this in [our guides ↗️](/guides)
-
-
-Agents are lightweight programs that can be inserted to existing systems with the ability to simplify the way we see complicated systems. As an example, supply chain management could deploy Agents using the uAgents Framework to improve operations at various stages. Demand forecasting, inventory control, logistics optimization, supplier relationships monitoring, quality control and risk mitigation in all areas can be done with their help. Agents could transform supply chain operations by increasing efficiency, reducing costs, improving accuracy and providing real-time visibility.
-
-You can view the source code for an Agent that monitors inventory levels in [our examples ↗️](https://github.com/fetchai/uAgent-Examples/blob/main/3-applications/inventory-monitoring/src/main.py)
-
-Agents thrive on IoT devices such as Raspberry Pi, and there are some great examples of multi-agent simulations using Agents on Raspberry Pi available on [Github ↗️](https://github.com/Agents-Lab/sensor-agent).
-
-
-#### LLMs
-
-Agents can wrap and orchestrate LLMs to create personalized Agents for any task. With the rise of Large Language Models (LLMs) and AI-related products, autonomous intelligent Agents have become the link between these models and tools. They are revolutionizing the way we solve problems, make decisions and collaborate with each other.
-
-Integrating LLMs into an Agent is relatively trivial, [we have a guide for that too ↗️](/guides/agents/intermediate/langchain-rag-agent)
-
-
-### Getting started with Agent development!
-
-Visit the [GitHub repository ↗️](https://github.com/fetchai/uAgents) to see the source code for uAgents, and to keep up-to-date with any update made to the uAgents Framework.
-
-From there, view the examples on uAgents repository, or start reading our guides, we'd recommend starting with [agent to agent communication ↗️](/guides/agents/intermediate/communicating-with-other-agents).
diff --git a/pages/guides/agents/intermediate/_meta.json b/pages/guides/agents/intermediate/_meta.json
deleted file mode 100644
index b65e3ed22..000000000
--- a/pages/guides/agents/intermediate/_meta.json
+++ /dev/null
@@ -1,131 +0,0 @@
-{
- "communicating-with-other-agents": {
- "title": "Communicating with other agents",
- "tags": ["Intermediate", "Python", "Communication", "Local"],
- "timestamp": true
- },
- "protocols": {
- "title": "Protocols",
- "tags": ["Intermediate", "Python", "Communication"],
- "timestamp": true
- },
- "handlers": {
- "title": "Agent Handlers (on_...)",
- "tags": ["Intermediate", "Python", "Handlers", "Local"],
- "timestamp": true
- },
- "storage-function": {
- "title": "Agents storage functions",
- "tags": ["Intermediate", "Python", "Storage", "Local"],
- "timestamp": true
- },
- "agent-types": {
- "title": "Hosted, Local, Mailbox and Proxy Agents",
- "tags": [
- "Intermediate",
- "Python",
- "Agents",
- "Hosted",
- "Local",
- "Mailbox",
- "Proxy"
- ],
- "timestamp": true
- },
- "bureau": {
- "title": "Bureau",
- "tags": ["Intermediate", "Python", "Bureau", "Local"],
- "timestamp": true
- },
- "broadcast": {
- "title": "Broadcast",
- "tags": ["Intermediate", "Python", "Broadcast", "Local"],
- "timestamp": true
- },
- "synchronous-communication": {
- "title": "Synchronous Communication",
- "tags": ["Intermediate", "Python", "Communication", "Local"],
- "timestamp": true
- },
- "mailbox": {
- "title": "Agents Mailboxes",
- "tags": ["Intermediate", "Python", "Communication", "Mailbox", "Local"],
- "timestamp": true
- },
- "agent-proxy": {
- "title": "Agent with Proxy",
- "tags": ["Intermediate", "Python", "Communication", "Proxy", "Local"],
- "timestamp": true
- },
- "local-agent-inspector": {
- "title": "Local Agent Inspector",
- "tags": ["Intermediate", "Python", "Agents", "Local"],
- "timestamp": true
- },
- "agent-functions": {
- "title": "Agent Functions",
- "tags": ["Intermediate", "Python", "Functions", "AI Engine", "Local"],
- "timestamp": true
- },
- "ai-engine-compatible-agent": {
- "title": "Make agents AI Engine compatible",
- "tags": ["Intermediate", "Python", "Functions", "AI Engine"],
- "timestamp": true
- },
- "options-for-running-local-agents": {
- "title": "Options for running local agents",
- "tags": ["Intermediate", "Python", "Agentverse", "Local"],
- "timestamp": true
- },
- "hosted-agent": {
- "title": "Hosted agent",
- "tags": ["Intermediate", "Python", "Agentverse", "Hosted"],
- "timestamp": true
- },
- "langchain-rag-agent": {
- "title": "Building a RAG Agent",
- "tags": [
- "Intermediate",
- "Python",
- "Functions",
- "LangChain",
- "AI Engine",
- "Local"
- ],
- "timestamp": true
- },
- "rest-endpoints": {
- "title": "REST endpoints",
- "tags": ["Intermediate", "Python", "REST API", "HTTP Protocols", "Local"],
- "timestamp": true
- },
- "public-private-agents": {
- "title": "Public and private Agents",
- "tags": ["Intermediate", "Python", "Agents"],
- "timestamp": true
- },
- "send-tokens": {
- "title": "Send tokens with Agents",
- "tags": ["Intermediate", "Python", "Transactions", "Local"],
- "timestamp": true
- },
- "primary-secondary-functions": {
- "title": "Multi-file agent pipeline for AI Engine: Hugging face API to create a multi agent pipeline",
- "tags": ["Intermediate", "Python", "Functions", "AI Engine", "Local"],
- "timestamp": true
- },
- "chat-protocol": {
- "title": "Chat protocol",
- "tags": ["Intermediate", "Python", "Agents", "Chat Protocols"]
- },
- "search-agent": {
- "title": "Search Agent",
- "tags": ["Intermediate", "Python", "Search", "Local"],
- "timestamp": true
- },
- "chat-proto": {
- "title": "Chat Protocol using AI Agents",
- "tags": ["Intermediate", "Python", "Protocols", "AI"],
- "timestamp": true
- }
-}
diff --git a/pages/guides/agents/intermediate/agent-functions.mdx b/pages/guides/agents/intermediate/agent-functions.mdx
deleted file mode 100644
index 03815200b..000000000
--- a/pages/guides/agents/intermediate/agent-functions.mdx
+++ /dev/null
@@ -1,186 +0,0 @@
-import { Callout } from 'nextra/components'
-import PackageVersion from 'components/package-version'
-import { CodeGroup, CodeSegment, DocsCode, GithubCodeSegment } from "../../../../components/code";
-
-# Agent Functions
-
-Agents can act as executable functions for the AI Engine. We can enable this by utilizing Agentverse and registering
-our Agent's function on the platform. The AI Engine then indexes the registered function and can then communicate with
-your Agent. Checkout the [Agents 101 for AI Engine ↗️](/guides/agent-courses/agents-for-ai#agent-agentverse-ai-engine-and-deltav) for a wider explanation of how this works.
-
-
- Check out the [AI Engine package ↗️](https://pypi.org/project/uagents-ai-engine/) to download it and start integrating your Agents with this tool!
-
- Current version of the package is .
-
-
-## Prerequisites
-
-Make sure you have read the following resources before going on with this guide:
-
- - [Quick Start Guide for uAgents Framework ↗️](/guides/agents/quickstart)
- - [Creating your first Agent ↗️](/guides/agents/getting-started/create-a-uagent)
- - [Agent Handlers ↗️](/guides/agents/intermediate/handlers)
- - [Using Agents storage function ↗️](/guides/agents/intermediate/storage-function)
- - [Almanac contract ↗️](/concepts/fetch-network/almanac)
- - [Register in Almanac ↗️](/guides/agents/register-in-almanac)
- - [Agents protocols ↗️](/guides/agents/intermediate/protocols)
- - [Exchange protocol ↗️](/references/uagents/uagents-protocols/exchange-protocol)
- - [Options for running your Agents ↗️](/guides/agents/intermediate/options-for-running-local-agents)
- - [Make your Agents AI Engine compatible ↗️](/guides/agents/intermediate/ai-engine-compatible-agent)
-
-## Imports needed
-
- - [uAgents ↗️](https://pypi.org/project/uagents/)
- - [AI Engine ↗️](https://pypi.org/project/uagents-ai-engine/)
-
-## Local Agent Function registration
-
-Sometimes you'll want to run an Agent on your own hardware or infrastructure; luckily this is very easy to do on any system that supports **Python 3.10**.
-
-### Overview
-
-This system is pretty simple and makes you get started as quickly as possible. You can run this Agent on any device you'd like; in this scenario we're running on a VM, but you could run this on your laptop, raspberry pi or tweak for [Agentverse ↗️](/concepts/agent-services/agentverse-intro).
-
-On startup our script will register our Agent to the [Almanac ↗️](/concepts/fetch-network/almanac), and then our Agent will be available to communicate with other Agents. To get this Agent to be [DeltaV ↗️](/concepts/ai-engine/deltav) accessible, we will also go to Agentverse to create a new Function for the Agent, to then allow this Agent to be found in DeltaV.
-
-### The agent
-
-
-
-
-
-
-
- ```py copy filename="simple_function.py"
-
- from uagents.setup import fund_agent_if_low
- from uagents import Agent, Context, Protocol, Model
- import random
- from uagents import Field
- from ai_engine import UAgentResponse, UAgentResponseType
- import sys
-
- dungeons = Agent(
- name="dungeonsanddragonsdiceroll",
- port=6145,
- seed="RANDOM STRINGS",
- endpoint=["http://YOUR_IP:6145/submit"],
- )
-
- fund_agent_if_low(dungeons.wallet.address())
-
- @dungeons.on_event("startup")
- async def hi(ctx: Context):
- ctx.logger.info(dungeons.address)
-
- class Request(Model):
- dice_sides: int = Field(description="How many sides does your dice need?")
-
-
- dice_roll_protocol = Protocol("DungeonsAndDragonsDiceRoll")
-
- @dice_roll_protocol.on_message(model=Request, replies={UAgentResponse})
- async def roll_dice(ctx: Context, sender: str, msg: Request):
- result = str(random.randint(1, msg.dice_sides))
- message = f"Dice roll result: {result}"
- await ctx.send(
- sender, UAgentResponse(message=message, type=UAgentResponseType.FINAL)
- )
-
- dungeons.include(dice_roll_protocol, publish_manifest=True)
-
- dungeons.run()
-
-```
-
-
-
-
-
-
-It is important that you provide the `name`, `port`, `seed` and `endpoint` for your Agent to correctly run this code.
-
-A few things to note; you'll need to be running this Agent on infrastructure that allows you to open a port, in our example we run on port `6145`. The agent is initialized with an `endpoint`, and a `port` - this is so that we can receive messages, and other Agents know where to send them. On the Testnet, you can use the `fund_agent_if_low` to get some funds, if you need them to register your Agent to the Almanac. We then define the protocol, which is just an `int` as seen in the `Request` object.
-
-The `on_message` doesn't do much other than return a number between 1 and the defined `dice_sides` from the message inclusive. However, the response type is of `UAgentResponse` which is essential to communicate with DeltaV.
-
-`.run()` initializes the Agent.
-
-Finally, we run our Agent as follows: `python simple_function.py`
-
-**Expected output**:
-
- ```
- INFO: [dungeonsanddragonsdiceroll]: Manifest published successfully: DungeonsAndDragonsDiceRoll
- INFO: [dungeonsanddragonsdiceroll]: Registration on Almanac API successful
- INFO: [dungeonsanddragonsdiceroll]: Registering on almanac contract...
- INFO: [dungeonsanddragonsdiceroll]: Registering on almanac contract...complete
- INFO: [dungeonsanddragonsdiceroll]: Agent inspector available at https://agentverse.ai/inspect/?uri=http%3A//127.0.0.1%3A6145&address=agent1qvwk0ntr38yyghccrg530hnnm88r5uske4hdcalsa7gqp7sjgx42k4mp62r
- INFO: [dungeonsanddragonsdiceroll]: agent1qvh76795enwgnzkrjpedlnqxwv83d8wxnkkcszs9z46zc3qpfs3yvzc5kuw
- INFO: [dungeonsanddragonsdiceroll]: Starting server on http://0.0.0.0:6145 (Press CTRL+C to quit)
- ```
-
-### Register a local Agent Function on the Agentverse
-
-For this example we set up a really simple Agent Function. For further information on Agent Functions and registration process, see [Register Agent Functions on the Agentverse ↗️](/guides/agentverse/registering-agent-services) resource.
-
-To register **Local Agents and Functions**, you will first need to head over to the [local Agent Inspector ↗️](/guides/agents/intermediate/local-agent-inspector) available by clicking on the dedicated link presented within your terminal output after running the above local Agent. Once you do so, click on **Connect** button and select **Mailbox**. Follow the steps closely and provide all needed data required.
-
-
-
-
-
-After this, click **Connect**.
-
-
-
-At this point, you do not need to do anything else. Click **Finish**.
-
- 
-
-Once your agent is connected via the Mailbox correctly, you will see a box depicting it within the **My Agents** tab.
-
-
-
-Click on it and head over to the **Deploy** tab and click on **+ New Function**.
-
-
-
-Here, you can now provide the needed details for your Agent Function in the dedicated fields. Remember to provide detailed descriptions for what your **Agent Function** does and the **Fields** for data Models expected. understanding of Functions fields descriptions.
-
-
-
-It's recommended you alter the contract slightly, and follow the above steps so that you can run an Agent, create a function for the Agent and then have that Agent accessible by DeltaV.
-
-## Description of your Agent Function
-
-The **Description** is super important to the success of your Agent Function. The [AI Engine ↗️](/concepts/ai-engine/ai-engine-intro) will catalogue descriptions and parse these into its understanding. Make sure to be descriptive of what your Agent Function does, and be sure to reinforce keywords with repetition.
-
-Read more and see examples on how to properly set field descriptions by heading over to: [Field descriptions for DeltaV ↗️](/guides/services/field-descriptions-for-deltav) guide.
-
-## Primary and Secondary Functions
-
-**Primary** and **Secondary** functions are different but have strong similarities.
-
-The first one is the primary Agent Function and for instance, it could be an agent that would respond to a user or be accessible via DeltaV. _Primary Functions are expected to fully or partially fulfill an objective provided by users_.
-
-Similarly, a **Secondary** function is an Agent Sub-function providing secondary functionalities that likely need additional context or information to carry out the Primary Function. _Secondary Functions are executed in combination with the Objective task_. If that's the case, DeltaV would see that the Agent Primary Function can be fulfilled by executing a Secondary Function, thus, it will contact this latter one which may or may not require gaining context directly from the user.
-
-
- DeltaV supports rich text and hyperlinks, enhancing formatting and navigation within the interface. You can include hyperlinks using standard HTML tags for clickable links. For more details, refer to the [guide on rich text and hyperlinks ↗️](/guides/agentverse/agentverse-functions/hyperlinks-and-rich-text-deltav).
-
-
-## Functions registration resources
-
-For further information and examples on how to register an Agent Function make it discoverable on DeltaV, check out our dedicated resources:
-
- - [Register Agentverse Functions ↗️](/guides/agentverse/agentverse-functions/registering-agent-services).
- - [Register a coin toss Agent as a Function ↗️](/guides/agentverse/agentverse-functions/registering-agent-coin-toss).
-
-For any additional questions, the Team is waiting for you on [Discord ↗️](https://discord.gg/fetchai) and [Telegram ↗️](https://t.me/fetch_ai) channels.
diff --git a/pages/guides/agents/intermediate/agent-proxy.mdx b/pages/guides/agents/intermediate/agent-proxy.mdx
deleted file mode 100644
index f29d45e70..000000000
--- a/pages/guides/agents/intermediate/agent-proxy.mdx
+++ /dev/null
@@ -1,116 +0,0 @@
-import { CodeGroup, CodeSegment, DocsCode, GithubCodeSegment } from "../../../../components/code";
-
-# Agent with Proxy
-
-## Introduction
-
-A Proxy serves as a bridge between your Agent and the Agentverse, allowing the Agent to publish interaction data without the need of a [Mailbox ↗️](/guides/agents/intermediate/mailbox). This setup is particularly beneficial for Agents requiring continuous operation and visibility in the Agentverse Marketplace.
-
-## Prerequisites
-
-Make sure you have read the following resources before going on with this guide:
-
- - [Quick Start Guide for uAgents Framework ↗️](/guides/agents/quickstart)
- - [Creating your first agent ↗️](/guides/agents/getting-started/create-a-uagent)
- - [Agents address ↗️](/guides/agents/getting-started/getting-uagent-address)
- - [Almanac contract ↗️](/concepts/fetch-network/almanac)
- - [Register in Almanac ↗️](/guides/agents/register-in-almanac)
- - [Agent Mailboxes ↗️](/guides/agents/intermediate/mailbox)
- - [Local Agent Inspector ↗️](/guides/agents/intermediate/local-agent-inspector)
-
-## The Agent setup
-
-An Agent connected via a Proxy uses the Agentverse as an intermediary to record interactions relevant to the [Agentverse Marketplace ↗️](/concepts/agent-services/agent-explorer), causing it to rank higher in the search index.
-
-The following code demonstrates how to connect a local Agent to the Agentverse using a Proxy:
-
-
-
-
-
-
-
- ```py copy filename="agent_with_proxy.py"
-
- 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()
-
-```
-
-
-
-
-
-
-The Agent is initialized with multiple parameters: `name`, `seed` and `proxy`. Remember to correctly specify these parameters in order to successfully run the Agent. By running the above Agent code, you should be able to see the following output within your terminal:
-
-```
-INFO: [alice]: Starting agent with address: agent1qtx288pfqm9e5qausyzdy6zmmn65ytwygqdq2h7d4g0q00ft04rygg96jtt
-INFO: [alice]: Agent inspector available at https://agentverse.ai/inspect/?uri=http%3A//127.0.0.1%3A8000&address=agent1qtx288pfqm9e5qausyzdy6zmmn65ytwygqdq2h7d4g0q00ft04rygg96jtt
-INFO: [alice]: Starting server on http://0.0.0.0:8000 (Press CTRL+C to quit)
-INFO: [alice]: Registration on Almanac API successful
-INFO: [alice]: Registering on almanac contract...
-INFO: [alice]: Registering on almanac contract...complete
-```
-
-Now, you are ready to connect the Agent using a Proxy. To connect your Agent using a Proxy, obtain the IP address where your Agent is accessible. Use the Agent Inspector URL from the terminal output to access the Inspector UI. **Log in** to the Agentverse and click the **Connect** button.
-
-
-
-Then, select **Proxy** as your connection method, provide your Agent's **public URL** or **IP address** followed by `/submit`. Once it is being validated, click **Next**.
-
-
-
-Now, you will need to provide a **public URL** or **IP address** for your Agent.
-
-_**Make sure you are running the latest [uagents package ↗️](https://pypi.org/project/uagents/) version on your end!**_
-
-
-
-Once you do so, and the Agent's public URL or IP address is verified, you will be asked to verify your Agent configuration and finalize the setup process.
-
-
-
-Great! You successfully set up a proxy for your local Agent!
-
-You should be able to see the following updated output in your terminal:
-
-```
-INFO: [alice]: Starting agent with address: agent1qtx288pfqm9e5qausyzdy6zmmn65ytwygqdq2h7d4g0q00ft04rygg96jtt
-INFO: [alice]: Agent inspector available at https://agentverse.ai/inspect/?uri=http%3A//127.0.0.1%3A8000&address=agent1qtx288pfqm9e5qausyzdy6zmmn65ytwygqdq2h7d4g0q00ft04rygg96jtt
-INFO: [alice]: Starting server on http://0.0.0.0:8000 (Press CTRL+C to quit)
-INFO: [alice]: Registration on Almanac API successful
-INFO: [alice]: Registering on almanac contract...
-INFO: [alice]: Registering on almanac contract...complete
-INFO: [mailbox]: Successfully registered as proxy agent in Agentverse
-```
-
-Now that your Agent is connected through the Proxy to the Agentverse, it is able to receive messages from any other Agents.
-
-Using a Proxy enables your Agent to seamlessly interact with the Agentverse, tracking interactions and displaying them on the [Marketplace ↗️](/concepts/agent-services/agent-explorer). These interactions are showcased on the Agent's dedicated page within the [Agentverse: My Agents ↗️](/concepts/agent-services/agent-hosting) tab, providing visibility and engagement opportunities for users exploring the Marketplace.
-
-A Proxy differs from a [Mailbox ↗️](/guides/agents/intermediate/mailbox) in key ways. While a Mailbox stores messages for offline Agents, a Proxy requires the Agent to be online to process incoming messages in real-time. Messages sent to an offline Proxy Agent are dropped, making it suitable for Agents that are continuously running and accessible through a public endpoint.
-
-Setting up a Proxy benefits agents that require consistent operation and visibility in the Agentverse. It tracks interactions, showcases activity in the Marketplace, and ensures that Agents remain discoverable to other users, enhancing engagement and utility.
diff --git a/pages/guides/agents/intermediate/agent-types.mdx b/pages/guides/agents/intermediate/agent-types.mdx
deleted file mode 100644
index 546d7a91e..000000000
--- a/pages/guides/agents/intermediate/agent-types.mdx
+++ /dev/null
@@ -1,134 +0,0 @@
-import { CodeGroup, CodeSegment, DocsCode, GithubCodeSegment } from "../../../../components/code";
-
-# Hosted, Local, Mailbox and Proxy Agents
-
-Agents operate in various environments depending on how they are created and deployed.
-
-Understanding the difference between **Hosted**, **Local**, **Mailbox** and **Proxy** Agents helps developers choose the right setup for their needs.
-
-## Hosted Agents
-
-[Hosted Agents ↗️](/guides/agentverse/creating-agentverse-agents/creating-a-hosted-agent) are cloud-based Agents managed within the [Agentverse ↗️](https://agentverse.ai/),enabling developers to deploy and manage Agents without handling infrastructure. These Agents function as lightweight, efficient tasks, resetting global variables after each call. To maintain state across calls, developers must use Agent Storage for stateful behavior.
-
-Developers can start with blank scripts or use customizable templates for common use cases like retrieving stock prices or finding nearby restaurants. Hosted Agents are highly accessible, requiring no local dependencies, and include an `agent.py` file from which you can develop them straightforwardly. For a better reference to these topics, check out the following resources:
-
- - [Creating Hosted Agents ↗️](/guides/agentverse/creating-agentverse-agents/creating-a-hosted-agent).
- - [Agentverse: Allowed Imports ↗️](/guides/agentverse/creating-agentverse-agents/allowed-imports).
- - [How Agents handle their state ↗️](/guides/agents/intermediate/hosted-agent).
-
-## Local Agents
-
-Local Agents run on your machine or infrastructure, providing complete control over their environment, configuration, and execution. Unlike hosted Agents, they handle real-time events, messages, and tasks continuously, making them ideal for persistent state and direct access to local resources. Local Agents integrate with any Python package or custom module, supporting advanced capabilities like machine learning and data processing. They maintain persistent state across function executions, unlike hosted Agents, where state resets after each call. Setting up a Local Agent requires a Python environment, dependencies, and running the Agent script. They can operate continuously or within Docker containers for scalability and isolation.
-
-Local Agents are perfect for high-performance, real-time applications requiring deep customization, resource management, and direct integration with local functions. Head over to the following resource for a better understanding of Agents and their applications:
-
- - [Agents - uAgents Framework ↗️](/guides/agents/getting-started/whats-an-agent).
- - [Creating your first agent ↗️](/guides/agents/getting-started/create-a-uagent).
- - [Agent Functions ↗️](/guides/agents/intermediate/agent-functions).
- - [Options for running your Agents ↗️](/guides/agents/intermediate/options-for-running-local-agents#run-a-local-agent-with-an-endpoint).
-
-## Mailbox Agents
-
-The [Agentverse Mailbox feature ↗️](/guides/agents/intermediate/mailbox) makes Agents a hybrid between Hosted and Local types. This because Local Agents may not always be online all the time due to network outages, being behind a firewall, or intentionally going offline for resource management. To manage such scenarios, the **Mailbox** feature in Agentverse allows Agents to receive messages while they are offline with ease. Once the Agent comes back online, it can retrieve these messages from its mailbox.
-
-**Local Agents can use a Mailbox to ensure that no messages are lost when they are temporarily disconnected from the network**; the Mailbox acts as a message buffer, storing communications until the Agent comes back online and ready to process them. Indeed, this feature enables interaction with other Agents or functions without the Agent being online continuously.
-
-In order to set up a mailbox for a local Agent, you first need to create and configure the local Agent. For instance, consider the following basic Agent:
-
-
-
-
-
-
-
- ```py copy filename="mailbox_agent.py"
-
- from uagents import Agent, Context, Model
-
-
- class Message(Model):
- message: str
-
-
- SEED_PHRASE = "put_your_seed_phrase_here"
-
- # Now your agent is ready to join the agentverse!
- agent = Agent(
- name="alice",
- port=8000,
- mailbox=True
- )
-
- # Copy the address shown below
- print(f"Your agent's address is: {agent.address}")
-
- if __name__ == "__main__":
- agent.run()
-
- ```
-
-
-
-
-
-
-Once you run this Agent, you will be able to see a link in your terminal output redirecting you towards the [Local Agent Inspector ↗️](/guides/agents/intermediate/local-agent-inspector) for this specific Agent on the [Agentverse ↗️](https://agentverse.ai/).
-
-
-
-By clicking the **Connect** button and then choosing **Mailbox** you will be guided into correctly setting up a mailbox for your local Agent. To test your Mailbox setup, you can create another Agent (on Agentverse for instance) that sends messages to the Mailbox while the first Agent is offline. When the first Agent comes back online, it will retrieve and process the stored messages.
-
-For a complete example, check out this [guide ↗️](/guides/agentverse/agentverse-mailbox/utilising-the-mailbox). For a more complex example of an Agent using a Mailbox, check out the following [guide ↗️](/guides/agents/intermediate/langchain-rag-agent).
-
-## Proxy Agents
-
-A Proxy serves as a bridge between your Agent and the Agentverse, allowing the Agent to publish interaction data without needing a Mailbox. This setup is particularly beneficial for Agents requiring continuous operation and visibility in the [Agentverse Marketplace ↗️](/concepts/agent-services/agent-explorer).
-
-Consider the following basic Agent with a proxy:
-
-
-
-
-
-
-
- ```py copy filename="proxy_agent.py"
-
- from uagents import Agent, Context, Model
-
- class Message(Model):
- message: str
-
- # Initialize the agent
- agent = Agent(
- name="alice",
- seed="your_agent_seed_phrase",
- proxy=True
- )
-
- # Display the agent's address
- print(f"Your agent's address is: {agent.address}")
-
- if __name__ == "__main__":
- agent.run()
-
-```
-
-
-
-
-
-
-Run the Agent and access the Agent Inspector using the terminal output. Log in to the Agentverse and configure the Proxy connection by providing the public URL or IP address of your Agent. Verify and finalize the setup. Using a Proxy ensures that Agents remain discoverable and can interact with others in the Agentverse, enhancing engagement and visibility in the Marketplace.
-
-For a complete overview of the PRoxy setup, check out this [guide ↗️](/guides/agents/intermediate/agent-proxy).
diff --git a/pages/guides/agents/intermediate/ai-engine-compatible-agent.mdx b/pages/guides/agents/intermediate/ai-engine-compatible-agent.mdx
deleted file mode 100644
index c7f11718f..000000000
--- a/pages/guides/agents/intermediate/ai-engine-compatible-agent.mdx
+++ /dev/null
@@ -1,108 +0,0 @@
-import { Callout } from 'nextra/components'
-import PackageVersion from 'components/package-version'
-
-# Make your agents AI Engine compatible
-
- In the previous resource, ([Agent functions ↗️](/guides/agents/intermediate/agent-functions)) we created a simple agent that
- returned a dice roll, however this agent was already ready to be callable by [AI Engine ↗️](/concepts/ai-engine/ai-engine-intro). Let's get into how.
-
-
- Check out the [AI Engine package ↗️](https://pypi.org/project/uagents-ai-engine/) to download it and start integrating your Agents with this tool!
-
- Current version of the package is .
-
-
-## Prerequisites
-
-Make sure you have read the following resource before going on with this guide:
-
- - [Agent Functions ↗️](/guides/agents/intermediate/agent-functions)
-
-## from ai_engine
-
-To enable communication from agents to the AI Engine, we import **3 objects** that define the allowed responses:
-
-1. `UAgentResponseType()`:
-
- ```python
- class UAgentResponseType(Enum):
- FINAL = "final"
- ERROR = "error"
- VALIDATION_ERROR = "validation_error"
- SELECT_FROM_OPTIONS = "select_from_options"
- FINAL_OPTIONS = "final_options"
- ```
-
- - We used `FINAL` in our [dice roll ↗️](/examples/intermediate/dice-roll) example:
-
- ```python
- await ctx.send(
- sender, UAgentResponse(message=str(result), type=UAgentResponseType.FINAL)
- )
- ```
-
- `UAgentResponseType.FINAL` tells us that the message has no other responses.
-
- - We can use `ERROR` to signify the agent has encountered an error:
-
- ```python
- await ctx.send(sender, UAgentResponse(message="Unexpected Error", type=UAgentResponseType.ERROR))
-
- ```
-
- - `UAgentResponseType.SELECT_FROM_OPTIONS` gives the user who is interacting with AI Engine options to select from, you could build this like so:
-
- ```python
- options = []
- ctx_storage = {}
- for idx, value in enumerate(response):
- options.append(KeyValue(key=idx, value=value))
- if options:
- await ctx.send(
- sender,
- UAgentResponse(
- options=options,
- type=UAgentResponseType.SELECT_FROM_OPTIONS,
- request_id=request_id
- )
- )
- ```
-
- - `UAgentResponseType.FINAL_OPTIONS` signals the end of the options to AI Engine:
-
- ```python
- options = [KeyValue(key=x, value=x) for x in result if len(x) > 1]
- await ctx.send(
- sender,
- UAgentResponse(options=options, type=UAgentResponseType.FINAL_OPTIONS),
- )
- ```
-
-2. The AI Engine also enforces `key` and `value` to be strings:
-
- ```python
- class KeyValue(Model):
- key: str
- value: str
- ```
-
-3. `UAgentResponse` it an extension of the UAgents response type:
-
- ```python
- class UAgentResponse(Model):
- version: Literal["v1"] = "v1"
- type: UAgentResponseType
- request_id: Optional[str]
- agent_address: Optional[str]
- message: Optional[str]
- options: Optional[List[KeyValue]]
- verbose_message: Optional[str]
- verbose_options: Optional[List[KeyValue]]
- ```
-
- We don't need to alter `UAgentResponse`, using as `UAgentResponse(message=message, type=UAgentResponseType.*)` will
- satisfy current requirements.
-
-
- Whenever operating on DeltaV, we encourage everyone to select the **Next Generation AI Engine** personality type. This AI Engine personality stands as a significant AI Engine personality type offering _enhanced scalability_, _reliability_, and _flexibility_. The major key features include advanced context understanding, improved function recommendations, and the ability to handle multiple dialogue formats.
-
diff --git a/pages/guides/agents/intermediate/broadcast.mdx b/pages/guides/agents/intermediate/broadcast.mdx
deleted file mode 100644
index 792544fcd..000000000
--- a/pages/guides/agents/intermediate/broadcast.mdx
+++ /dev/null
@@ -1,207 +0,0 @@
-import {CodeGroup, DocsCode} from "components/code";
-
-# Broadcast
-
-## Introduction to `ctx.broadcast()`
-
-The `ctx.broadcast()` function is used within an agent to send a message to all other agents that support a specific protocol. It is a powerful method when you want to communicate with multiple agents at once without knowing their addresses beforehand. This is especially useful in systems where many agents may be participating in the same protocol, and you want to notify or query all of them simultaneously.
-
-Let's get started!
-
-## Prerequisites
-
-Make sure you have read the following resources before going on with this guide:
-
- - [Quick Start Guide for uAgents Framework ↗️](/guides/agents/quickstart)
- - [Creating your first agent ↗️](/guides/agents/getting-started/create-a-uagent)
- - [Agents address ↗️](/guides/agents/getting-started/getting-uagent-address)
- - [Almanac contract ↗️](/concepts/fetch-network/almanac)
- - [Register in Almanac ↗️](/guides/agents/register-in-almanac)
-
-## Imports needed
-
- - [uAgents ↗️](https://pypi.org/project/uagents/)
-
-## Bureau Walkthrough
-
-### Overview
-
-In this guide, we will create a multi-agent broadcast system using the `uagents` library. Three agents will be initialized: Ethan, Olivia, and Liam. Ethan and Olivia will support a defined communication protocol, while Liam will broadcast a message to all agents supporting this protocol and handle their responses. We’ll use `ctx.broadcast` to manage communication between agents and demonstrate the structure of message handling within the context of the `uagents` framework.
-
-### Step 1: Import Classes and Initialize Agents
-
-```py
-from uagents import Agent, Bureau, Context, Model, Protocol
-
-ethan = Agent(name="ethan", seed="ethan recovery phrase")
-olivia = Agent(name="olivia", seed="olivia recovery phrase")
-liam = Agent(name="liam", seed="liam recovery phrase")
-
-```
-In this step, we import the core classes needed to define agents, protocols, and message handling. We then initialize three agents: Ethan, Olivia, and Liam, each with unique seed phrases, ensuring fixed addresses for their identities.
-
-### Step 2: Define Message Models
-
-```py
-class BroadcastExampleRequest(Model):
- pass
-
-class BroadcastExampleResponse(Model):
- text: str
-
-```
-
-We define two message models:
-
-- `BroadcastExampleRequest`: This model represents a request message (empty for now).
-- `BroadcastExampleResponse`: This model holds a response message containing a text field.
-
-### Step 3: Define a Communication Protocol
-
-```py
-proto = Protocol(name="proto", version="1.0")
-
-```
-
-A protocol named proto with version 1.0 is defined. This protocol will govern communication between agents that support it.
-
-### Step 5: Message Handler for Broadcast Requests
-
-```py
-
-@proto.on_message(model=BroadcastExampleRequest, replies=BroadcastExampleResponse)
-async def handle_request(ctx: Context, sender: str, _msg: BroadcastExampleRequest):
- await ctx.send(
- sender, BroadcastExampleResponse(text=f"Hello from {ctx.agent.name}")
- )
-
-```
-
-This function handles incoming `BroadcastExampleRequest` messages. When an agent (e.g., Ethan or Olivia) receives a request, it replies with a `BroadcastExampleResponse`, sending a message containing its own name.
-
-### Step 6: Include the Protocol in Agents
-
-```py
-ethan.include(proto)
-olivia.include(proto)
-
-```
-
-We include the protocol in Ethan and Olivia. This allows them to participate in communication governed by the `proto` protocol.
-
-### Step 7: Liam's Behavior - Broadcasting and Handling Responses
-
-```py
-@liam.on_interval(period=5)
-async def say_hello(ctx: Context):
- status_list = await ctx.broadcast(proto.digest, message=BroadcastExampleRequest())
- ctx.logger.info(f"Trying to contact {len(status_list)} agents.")
-
-```
-
-The `say_hello` function is executed by Liam every 5 seconds (using `on_interval`). Liam sends a `BroadcastExampleRequest` message to all agents supporting the `proto` protocol via `ctx.broadcast`. The `proto.digest` is used to identify the protocol.
-
-```py
-@liam.on_message(model=BroadcastExampleResponse)
-async def handle_response(ctx: Context, sender: str, msg: BroadcastExampleResponse):
- ctx.logger.info(f"Received response from {sender}: {msg.text}")
-
-```
-
-When Liam receives a BroadcastExampleResponse, the handle_response function logs the sender and the content of the message.
-
-### Step 8: Run the Bureau
-
-```py
-bureau = Bureau(port=8000, endpoint="http://localhost:8000/submit")
-bureau.add(ethan)
-bureau.add(olivia)
-bureau.add(liam)
-
-if __name__ == "__main__":
- bureau.run()
-
-```
-
-## Explanation of ctx.broadcast
-
-The broadcast() method in the Context class allows an agent to send a message to multiple agents that support a specific protocol. Here's a detailed look at its usage:
-
-`status_list = await ctx.broadcast(proto.digest, message=BroadcastExampleRequest())`
-
-- `proto.digest`: This is a unique identifier for the protocol that the message will be sent under. Only agents supporting this protocol will receive the broadcast.
-- `message`: The message being broadcast, in this case, a BroadcastExampleRequest.
-- `status_list`: This is a list of statuses returned by the broadcast, indicating which agents were successfully contacted.
-
-By calling broadcast, Liam attempts to contact all agents supporting the proto protocol. This communication is asynchronous and can target multiple agents concurrently.
-
-The overall script for this example should look as follows:
-
-
-
-
- ```py filename="broadcast-agent.py"
- from uagents import Agent, Bureau, Context, Model, Protocol
-
- ethan = Agent(name="ethan", seed="ethan recovery phrase", port=8000, endpoint=["http://127.0.0.1:8000/submit"])
- olivia = Agent(name="olivia", seed="olivia recovery phrase", port=8001, endpoint=["http://127.0.0.1:8001/submit"])
- liam = Agent(name="liam", seed="liam recovery phrase", port=8002, endpoint=["http://127.0.0.1:8002/submit"])
-
- class BroadcastExampleRequest(Model):
- pass
-
- class BroadcastExampleResponse(Model):
- text: str
-
- proto = Protocol(name="proto", version="1.0")
-
- @proto.on_message(model=BroadcastExampleRequest, replies=BroadcastExampleResponse)
- async def handle_request(ctx: Context, sender: str, _msg: BroadcastExampleRequest):
- await ctx.send(
- sender, BroadcastExampleResponse(text=f"Hello from {ctx.agent.name}")
- )
-
- ethan.include(proto)
- olivia.include(proto)
-
- @liam.on_interval(period=5)
- async def say_hello(ctx: Context):
- status_list = await ctx.broadcast(proto.digest, message=BroadcastExampleRequest())
- ctx.logger.info(f"Trying to contact {len(status_list)} agents.")
-
- @liam.on_message(model=BroadcastExampleResponse)
- async def handle_response(ctx: Context, sender: str, msg: BroadcastExampleResponse):
- ctx.logger.info(f"Received response from {sender}: {msg.text}")
-
- bureau = Bureau(port=8000, endpoint="http://localhost:8000/submit")
- bureau.add(ethan)
- bureau.add(olivia)
- bureau.add(liam)
-
- if __name__ == "__main__":
- bureau.run()
-
- ```
-
-
-
-We are now ready to run the script: `python broadcast-agent.py`
-
-The output would be:
-
- ```
- INFO: [ethan]: Registration on Almanac API successful
- INFO: [ethan]: Registering on almanac contract...
- INFO: [ethan]: Registering on almanac contract...complete
- INFO: [olivia]: Registration on Almanac API successful
- INFO: [olivia]: Registering on almanac contract...
- INFO: [olivia]: Registering on almanac contract...complete
- INFO: [ liam]: Registration on Almanac API successful
- INFO: [ liam]: Registering on almanac contract...
- INFO: [ liam]: Registering on almanac contract...complete
- INFO: [bureau]: Starting server on http://0.0.0.0:8000 (Press CTRL+C to quit)
- INFO: [ liam]: Trying to contact 2 agents.
- INFO: [ liam]: Received response from agent1q2hdqe8hxa6g0awspktktgc5furywq5jur5q9whh9hzyffxsm9ka6c2dmhz: Hello from olivia
- INFO: [ liam]: Received response from agent1qff9zl5cehj2z68zef7q68uw76jjslh2r8xda93avayedqajzjwwyce8pt9: Hello from ethan
-
- ```
\ No newline at end of file
diff --git a/pages/guides/agents/intermediate/bureau.mdx b/pages/guides/agents/intermediate/bureau.mdx
deleted file mode 100644
index 3e46bd8e1..000000000
--- a/pages/guides/agents/intermediate/bureau.mdx
+++ /dev/null
@@ -1,174 +0,0 @@
-import {CodeGroup, DocsCode} from "components/code";
-
-# Bureau
-
-## Introduction
-
-The `Bureau` is a powerful orchestration component that allows multiple agents to operate together within a shared environment. It manages the lifecycle of agents, including their communication, task handling, and external integrations. The Bureau simplifies the process of running agents in a collaborative and coordinated fashion, whether they need to exchange messages internally or interact with external systems.
-
-Let's get started!
-
-## Prerequisites
-
-Make sure you have read the following resources before going on with this guide:
-
- - [Quick Start Guide for uAgents Framework ↗️](/guides/agents/quickstart)
- - [Creating your first agent ↗️](/guides/agents/getting-started/create-a-uagent)
- - [Agents address ↗️](/guides/agents/getting-started/getting-uagent-address)
- - [Agent Handlers ↗️](/guides/agents/intermediate/handlers)
- - [Almanac contract ↗️](/concepts/fetch-network/almanac)
- - [Register in Almanac ↗️](/guides/agents/register-in-almanac)
-
-## Imports needed
-
- - [uAgents ↗️](https://pypi.org/project/uagents/)
-
-## Walk-through
-
-This walk-through will guide you through the process of setting up and running Agents using the Bureau, demonstrating its key functionalities, including agent management, message handling, and external communication via endpoints.
-
-### Step 1: Setting Up Agents
-
-To begin, you need to create and define your Agents. Each Agent will have specific tasks and behaviors that can be scheduled or triggered by messages.
-
-```py copy filename="agent-bureau.py"
-
-from uagents import Agent, Context, Model
-
-class Message(Model):
- message: str
-
-agent_a = Agent(name="agent_a", seed="agent_a recovery phrase")
-agent_b = Agent(name="agent_b", seed="agent_b recovery phrase")
-
-```
-
-### Step 2: Defining Agent Behavior
-
-Next, define the behavior of each Agent, such as sending and receiving messages. This is done using decorators like `on_interval` to perform scheduled tasks and `on_message` to respond to incoming messages. Check out the [Agent Handlers ↗️](/guides/agents/intermediate/handlers) for additional information on Agent Handlers and their usage.
-
-```py copy filename="agent-bureau.py"
-
-@agent_a.on_interval(period=3.0)
-async def send_message(ctx: Context):
- await ctx.send(agent_b.address, Message(message="Hello from agent_a"))
-
-# Handle received messages in agent_a
-@agent_a.on_message(model=Message)
-async def agent_a_message_handler(ctx: Context, sender: str, msg: Message):
- ctx.logger.info(f"Received message from {sender}: {msg.message}")
-
-# Handle received messages in agent_b
-@agent_b.on_message(model=Message)
-async def agent_b_message_handler(ctx: Context, sender: str, msg: Message):
- ctx.logger.info(f"Received message from {sender}: {msg.message}")
- await ctx.send(agent_a.address, Message(message="Reply from agent_b"))
-
-```
-
-### Step 3: Creating the Bureau
-
-Once the Agents are set up, you can create a Bureau instance to manage them. The Bureau is responsible for running the Agents, handling communication, and orchestrating tasks.
-
-#### Arguments the Bureau Takes:
-
-The Bureau can be customized through a few important arguments when instantiated:
-
-- `agents` (Optional[List[Agent]]): A list of Agents to be managed by the Bureau. If you don't add Agents during initialization, you can always add them later using the `add()` method.
-
-- `port` (Optional[int]): The port number on which the Bureau's ASGI server will run. This is crucial if your Agents need to expose REST APIs for external communication. The default port is `8000`, but you can specify any available port.
-
-- `endpoint` (Optional[Union[str, List[str], Dict[str, dict]]]): Configuration for the Agent endpoints. You can specify how Agents communicate with external systems via REST. This could be a string, a list of strings, or a dictionary defining more complex configurations. If you want Agents external to the bureau to be able to communicate with the Agents within the Bureau this must be defined.
-
-- `loop` (Optional[asyncio.AbstractEventLoop]): The event loop used for managing asynchronous tasks. The Bureau creates one by default if none is provided.
-
-- `log_level` (Optional[Union[int, str]]): Sets the logging level, such as `INFO`, `DEBUG`, or `ERROR` to control the verbosity of execution logs.
-
-```py
-from uagents import Bureau
-
-bureau = Bureau()
-
-or
-# Initialize the Bureau, optionally specifying port, agents, and other configurations
-bureau = Bureau(port=8000, agents=[agent_a, agent_b], endpoint="http://localhost:8000/submit")
-
-bureau.add(agent_a)
-bureau.add(agent_b)
-
-```
-
-### Step 4: Running the Bureau
-
-After adding your Agents, it's time to run the Bureau. The Bureau will ensure that the Agents communicate seamlessly and handle tasks like message delivery and API management if necessary.
-
-```py copy
-
-if __name__ == "__main__":
- bureau.run()
-
-```
-
-Step 5: Message Handling and Communication
-
-In this setup, `agent_a` sends a message to `agent_b` every 3 seconds. When `agent_b` receives the message, it replies to `agent_a`.
-
-The Bureau handles the coordination and message passing between the Agents. You'll see logs indicating the messages sent and received by each Agent.
-
-The overall script for this example should look as follows:
-
-
-
- ```py filename="agent-bureau.py"
- from uagents import Agent, Bureau, Context, Model
-
- class Message(Model):
- message: str
-
- agent_a = Agent(name="agent_a", seed="agent_a recovery phrase")
- agent_b = Agent(name="agent_b", seed="agent_b recovery phrase")
-
- @agent_a.on_interval(period=3.0)
- async def send_message(ctx: Context):
- await ctx.send(agent_b.address, Message(message="Hello from agent_a"))
-
- @agent_a.on_message(model=Message)
- async def agent_a_message_handler(ctx: Context, sender: str, msg: Message):
- ctx.logger.info(f"Received message from {sender}: {msg.message}")
-
- @agent_b.on_message(model=Message)
- async def agent_b_message_handler(ctx: Context, sender: str, msg: Message):
- ctx.logger.info(f"Received message from {sender}: {msg.message}")
- await ctx.send(agent_a.address, Message(message="Reply from agent_b"))
-
- bureau = Bureau()
-
- # if we want our bureau agents to receive messages from external agents:
- # bureau = Bureau(port=8000, agents=[agent_a, agent_b], endpoint="http://localhost:8000/submit")
-
- bureau.add(agent_a)
- bureau.add(agent_b)
-
- if __name__ == "__main__":
- bureau.run()
-
- ```
-
-
-
-We are now ready to run the script: `python agent-bureau.py`
-
-The output would be:
-
- ```
- WARNING: [agent_a]: No endpoints provided. Skipping registration: Agent won't be reachable.
- WARNING: [agent_b]: No endpoints provided. Skipping registration: Agent won't be reachable.
- INFO: [agent_b]: Received message from agent1q2n33nmfscfscnz49a9e6nj4054d7r46v7x7522g4zh798tcwgs5q855p6q: Hello from agent_a
- INFO: [bureau]: Starting server on http://0.0.0.0:8000 (Press CTRL+C to quit)
- INFO: [agent_a]: Received message from agent1q07ypwau2gv0y005m0ltycx7vpt3hpajsvvnltpu50wpgk87zzkmwc005ga: Reply from agent_b
- INFO: [agent_b]: Received message from agent1q2n33nmfscfscnz49a9e6nj4054d7r46v7x7522g4zh798tcwgs5q855p6q: Hello from agent_a
- INFO: [agent_a]: Received message from agent1q07ypwau2gv0y005m0ltycx7vpt3hpajsvvnltpu50wpgk87zzkmwc005ga: Reply from agent_b
- INFO: [agent_b]: Received message from agent1q2n33nmfscfscnz49a9e6nj4054d7r46v7x7522g4zh798tcwgs5q855p6q: Hello from agent_a
- INFO: [agent_a]: Received message from agent1q07ypwau2gv0y005m0ltycx7vpt3hpajsvvnltpu50wpgk87zzkmwc005ga: Reply from agent_b
-
- ```
diff --git a/pages/guides/agents/intermediate/chat-proto.mdx b/pages/guides/agents/intermediate/chat-proto.mdx
deleted file mode 100644
index 0c4220e3b..000000000
--- a/pages/guides/agents/intermediate/chat-proto.mdx
+++ /dev/null
@@ -1,570 +0,0 @@
-# Chat Protocol Using AI Agents
-
-## Introduction
-
-The Chat Protocol enables seamless communication between autonomous agents in the uAgents ecosystem. It standardizes message formats, session handling, and content types for efficient exchanges. Supporting text communication, resource sharing, metadata exchange, and AI-driven responses which simplifies integration for developers.
-
-## Chat Protocol Overview
-
-The Chat Protocol comprises several essential elements:
-
-### Content Types
-
-The protocol supports multiple content types, enabling flexible communication between agents:
-
-- **TextContent**: Standard text-based messages.
-- **ResourceContent**: Messages containing resources such as files, images, or videos.
-- **MetadataContent**: Extra metadata associated with messages.
-- **StartSessionContent**: Marks the beginning of a communication session.
-- **EndSessionContent**: Marks the end of a communication session.
-- **StartStreamContent**: Indicates the start of a streaming session.
-- **EndStreamContent**: Indicates the end of a streaming session.
-
-### Message Structures
-
-The protocol defines structured message formats to ensure consistency:
-
-- **ChatMessage**: A container for messages, including a timestamp, unique message ID, and a list of content elements.
-- **ChatAcknowledgement**: Acknowledges message receipt, including the timestamp and the ID of the received message.
-
-```python copy
-class ChatMessage(Model):
-
- # the timestamp for the message, should be in UTC
- timestamp: datetime
-
- # a unique message id that is generated from the message instigator
- msg_id: UUID4
-
- # the list of content elements in the chat
- content: list[AgentContent]
-
-
-class ChatAcknowledgement(Model):
-
- # the timestamp for the message, should be in UTC
- timestamp: datetime
-
- # the msg id that is being acknowledged
- acknowledged_msg_id: UUID4
-
- # optional acknowledgement metadata
- metadata: dict[str, str] | None = None
-```
-
-## Detailed Explanation of Key Functions
-
-### `create_text_chat`
-
-This function is responsible for creating a `ChatMessage` object with a simple text-based content. It:
-- Assigns a current timestamp.
-- Generates a unique message ID.
-- Wraps the text in a `TextContent` model.
-
-```python
-def create_text_chat(text: str) -> ChatMessage:
- return ChatMessage(
- timestamp=datetime.now(),
- msg_id=uuid4(),
- content=[TextContent(type="text", text=text)],
- )
-```
-
-### `chat_proto` Definition
-
-Here, a protocol instance named `AgentChatProtocol` is defined. This protocol facilitates communication between agents by handling structured messages.
-
-```python
-chat_proto = Protocol(name="AgentChatProtocol", version="0.2.1")
-```
-
-### Handling Incoming Chat Messages
-
-The `handle_message` function processes incoming chat messages. It:
-1. Logs the received message.
-2. Stores the sender information.
-3. Sends a `ChatAcknowledgement` to confirm receipt.
-4. Calls the AI-powered `get_completion` function to generate a reply.
-5. Sends back the AI-generated response as a new chat message.
-
-```python
-@chat_proto.on_message(ChatMessage)
-async def handle_message(ctx: Context, sender: str, msg: ChatMessage):
- ctx.logger.info(f"Got a message from {sender}: {msg.content[0].text}")
- ctx.storage.set(str(ctx.session), sender)
- await ctx.send(
- sender,
- ChatAcknowledgement(timestamp=datetime.now(), acknowledged_msg_id=msg.msg_id),
- )
-
- completion = get_completion(context="", prompt=msg.content[0].text)
- await ctx.send(sender, create_text_chat(completion))
-```
-
-### Handling Acknowledgements
-
-The `handle_ack` function processes incoming `ChatAcknowledgement` messages. It logs a confirmation message indicating that a particular message has been acknowledged by the recipient.
-
-```python
-@chat_proto.on_message(ChatAcknowledgement)
-async def handle_ack(ctx: Context, sender: str, msg: ChatAcknowledgement):
- ctx.logger.info(f"Got an acknowledgement from {sender} for {msg.acknowledged_msg_id}")
-```
-
-
-## Full Chat Protocol Script
-
-```python
-from typing import Any, Literal, TypedDict
-from datetime import datetime
-from pydantic.v1 import UUID4
-from uagents import Model, Protocol, Context
-from uuid import uuid4
-
-from ai import get_completion
-
-
-class Metadata(TypedDict):
-
- # primarily used with hte `Resource` model. This field specifies the mime_type of
- # resource that is being referenced. A full list can be found at `docs/mime_types.md`
- mime_type: str
-
- # the role of the resource
- role: str
-
-
-class TextContent(Model):
- type: Literal["text"]
-
- # The text of the content. The format of this field is UTF-8 encoded strings. Additionally,
- # markdown based formatting can be used and will be supported by most clients
- text: str
-
-
-class Resource(Model):
-
- # the uri of the resource
- uri: str
-
- # the set of metadata for this resource, for more detailed description of the set of
- # fields see `docs/metadata.md`
- metadata: dict[str, str]
-
-
-class ResourceContent(Model):
- type: Literal["resource"]
-
- # The resource id
- resource_id: UUID4
-
- # The resource or list of resource for this content. typically only a single
- # resource will be sent, however, if there are accompanying resources like
- # thumbnails and audo tracks these can be additionally referenced
- #
- # In the case of the a list of resources, the first element of the list is always
- # considered the primary resource
- resource: Resource | list[Resource]
-
-
-class MetadataContent(Model):
- type: Literal["metadata"]
-
- # the set of metadata for this content, for more detailed description of the set of
- # fields see `docs/metadata.md`
- metadata: dict[str, str]
-
-
-class StartSessionContent(Model):
- type: Literal["start-session"]
-
-
-class EndSessionContent(Model):
- type: Literal["end-session"]
-
-
-class StartStreamContent(Model):
- type: Literal["start-stream"]
-
- stream_id: UUID4
-
-
-class EndStreamContent(Model):
- type: Literal["start-stream"]
-
- stream_id: UUID4
-
-
-# The combined agent content types
-AgentContent = (
- TextContent
- | ResourceContent
- | MetadataContent
- | StartSessionContent
- | EndSessionContent
- | StartStreamContent
- | EndStreamContent
-)
-
-
-class ChatMessage(Model):
-
- # the timestamp for the message, should be in UTC
- timestamp: datetime
-
- # a unique message id that is generated from the message instigator
- msg_id: UUID4
-
- # the list of content elements in the chat
- content: list[AgentContent]
-
-
-class ChatAcknowledgement(Model):
-
- # the timestamp for the message, should be in UTC
- timestamp: datetime
-
- # the msg id that is being acknowledged
- acknowledged_msg_id: UUID4
-
- # optional acknowledgement metadata
- metadata: dict[str, str] | None = None
-
-
-def create_text_chat(text: str) -> ChatMessage:
- return ChatMessage(
- timestamp=datetime.now(),
- msg_id=uuid4(),
- content=[TextContent(type="text", text=text)],
- )
-
-
-chat_proto = Protocol(name="AgentChatProtcol", version="0.2.1")
-
-
-@chat_proto.on_message(ChatMessage)
-async def handle_message(ctx: Context, sender: str, msg: ChatMessage):
- ctx.logger.info(f"Got a message from {sender}: {msg.content[0].text}")
- ctx.storage.set(str(ctx.session), sender)
- await ctx.send(
- sender,
- ChatAcknowledgement(timestamp=datetime.now(), acknowledged_msg_id=msg.msg_id),
- )
-
- completion = get_completion(context="", prompt=msg.content[0].text)
-
- await ctx.send(sender, create_text_chat(completion))
-
-
-@chat_proto.on_message(ChatAcknowledgement)
-async def handle_ack(ctx: Context, sender: str, msg: ChatAcknowledgement):
- ctx.logger.info(f"Got an acknowledgement from {sender} for {msg.acknowledged_msg_id}")
-```
-
-
-## AI Integration
-
-The AI integration provides a function `get_completion`, which is responsible for generating intelligent responses using OpenAI's GPT models. It:
-1. Configures API settings and model selection using environment variables.
-2. Sends a user prompt and optional context to the AI model.
-3. Handles structured responses if a schema is provided.
-4. Returns the generated content or an error message if an issue occurs.
-
-#### Key Components:
-
-- **API Configuration**: The script sets up API keys and model parameters from environment variables.
-- **`get_completion` Function**: Handles message processing and AI response generation.
-
-Example:
-
-```python filename="ai.py"
-def get_completion(
- context: str,
- prompt: str,
- response_schema: dict[str, Any] | None = None,
- max_tokens: int = MAX_TOKENS,
-) -> str:
- if response_schema is not None:
- response_format = {
- "type": "json_schema",
- "json_schema": {
- "name": response_schema["title"],
- "strict": False,
- "schema": response_schema,
- },
- }
- else:
- response_format = None
-
- try:
- response = client.chat.completions.create(
- model=MODEL_ENGINE,
- messages=[
- {"role": "system", "content": context},
- {"role": "user", "content": prompt},
- ],
- response_format=response_format,
- max_tokens=max_tokens,
- )
- except OpenAIError as e:
- return f"An error occurred: {e}"
-
- return response.choices[0].message.content
-```
-
-This function enables agents to generate AI-driven responses dynamically based on incoming messages, enhancing the interaction experience.
-
-## Chat Protocol with Agents
-
-The Chat Protocol is integrated into agents so they can exchange messages using a standardized format.
-
-### AI Agent: Explanation and Full Code
-
-#### Explanation
-This Agent is set up as an AI-powered agent. It:
-
-- Listens for incoming structured prompts (using ContextPrompt).
-- Processes messages using the AI module via `get_completion` function from `ai.py`.
-- Sends back a response.
-- Integrates the Chat Protocol `chat_proto` alongside additional protocols like quota and health-check mechanisms.
-
-This agent uses a quota protocol to limit the rate of incoming requests and includes health check logic to ensure it remains operational.
-
-```python copy filename="ai-agent.py"
-import json
-import os
-from enum im copyport Enum
-from typing import Any
-
-from ai import get_completion
-from chat_proto import chat_proto
-from uagents import Agent, Context, Model
-from uagents.experimental.quota import QuotaProtocol, RateLimit
-from uagents.models import ErrorMessage
-
-AGENT_SEED = os.getenv("AGENT_SEED", "openai-test-agent")
-AGENT_NAME = os.getenv("AGENT_NAME", "OpenAI Agent")
-
-
-class ContextPrompt(Model):
- context: str
- text: str
-
-
-class Response(Model):
- text: str
-
-class StructuredOutputPrompt(Model):
- prompt: str
- output_schema: dict[str, Any]
-
-class StructuredOutputResponse(Model):
- output: dict[str, Any]
-
-PORT = 8000
-agent = Agent(
- name=AGENT_NAME,
- seed=AGENT_SEED,
- port=PORT,
- endpoint=f"http://localhost:{PORT}/submit",
-)
-
-proto = QuotaProtocol(
- storage_reference=agent.storage,
- name="LLM-Context-Response",
- version="0.1.0",
- default_rate_limit=RateLimit(window_size_minutes=60, max_requests=6),
-)
-
-struct_proto = QuotaProtocol(
- storage_reference=agent.storage,
- name="LLM-Structured-Response",
- version="0.1.0",
- default_rate_limit=RateLimit(window_size_minutes=60, max_requests=6),
-)
-
-@proto.on_message(ContextPrompt, replies={Response, ErrorMessage})
-async def handle_request(ctx: Context, sender: str, msg: ContextPrompt):
- ctx.logger.info(f"Received message {msg.text}")
- response = get_completion(context=msg.context, prompt=msg.text)
- print(response, "response")
- print(sender, "sender")
- await ctx.send(sender, Response(text=f"{response}"))
-
-
-@struct_proto.on_message(
- StructuredOutputPrompt, replies={StructuredOutputResponse, ErrorMessage}
-)
-async def handle_structured_request(
- ctx: Context, sender: str, msg: StructuredOutputPrompt
-):
- ctx.logger.info(f"Received message: {msg.prompt}")
- response = get_completion(
- context="", prompt=msg.prompt, response_schema=msg.output_schema
- )
- await ctx.send(sender, StructuredOutputResponse(output=json.loads(response)))
-
-
-agent.include(proto, publish_manifest=True)
-agent.include(struct_proto, publish_manifest=True)
-agent.include(chat_proto, publish_manifest=True)
-
-
-### Health check related code
-def agent_is_healthy() -> bool:
- \"\"\"Implement the actual health check logic here.
-
- For example, check if the agent can connect to a third party API,
- check if the agent has enough resources, etc.
- \"\"\"\n condition = True # TODO: logic here
- return bool(condition)
-
-
-class HealthCheck(Model):
- pass
-
-class HealthStatus(str, Enum):
- HEALTHY = "healthy"
- UNHEALTHY = "unhealthy"
-
-class AgentHealth(Model):
- agent_name: str
- status: HealthStatus
-
-health_protocol = QuotaProtocol(
- storage_reference=agent.storage, name="HealthProtocol", version="0.1.0"
-)
-
-@health_protocol.on_message(HealthCheck, replies={AgentHealth})
-async def handle_health_check(ctx: Context, sender: str, msg: HealthCheck):
- status = HealthStatus.UNHEALTHY
- try:
- if agent_is_healthy():
- status = HealthStatus.HEALTHY
- except Exception as err:
- ctx.logger.error(err)
- finally:
- await ctx.send(sender, AgentHealth(agent_name=AGENT_NAME, status=status))
-
-agent.include(health_protocol, publish_manifest=True)
-
-if __name__ == "__main__":
- agent.run()
-```
-
-### Client Agent: Explanation and Full Code
-
-#### Explanation
-
-Client Agent acts as a client that initiates interactions by sending prompts to AI Agent. Its main roles include:
-
-- Sending a code snippet for debugging and a query for structured output (in this example, querying weather information).
-- Listening for and handling the responses from AI Agent.
-
-```python copy filename"client_agent.py"
-from typing import Any, Literal
-from datetime import datetime
-from pydantic.v1 import UUID4
-from uagents import Agent, Model, Context
-from uuid import uuid4
-from chat_proto import AgentContent, ChatAcknowledgement
-
-class ContextPrompt(Model):
- context: str
- text: str
-
-
-class Response(Model):
- text: str
-
-
-class StructuredOutputPrompt(Model):
- prompt: str
- output_schema: dict[str, Any]
-
-
-class StructuredOutputResponse(Model):
- output: dict[str, Any]
-
-class TextContent(Model):
- type: Literal["text"]
-
- # The text of the content. The format of this field is UTF-8 encoded strings. Additionally,
- # markdown based formatting can be used and will be supported by most clients
- text: str
-
-class ChatMessage(Model):
-
- # the timestamp for the message, should be in UTC
- timestamp: datetime
-
- # a unique message id that is generated from the message instigator
- msg_id: UUID4
-
- # the list of content elements in the chat
- content: list[AgentContent]
-
-agent = Agent(name="agent-2", port=8001, seed="agent-2" , endpoint="http://localhost:8001/submit")
-
-
-AI_AGENT_ADDRESS = "agent1q09xe6rk6lqcnchdrkcn92ma4wlmjyty3v2yzxlxdx4jylq2fcfa2rv458x"
-
-code = """
- def do_something():
- for i in range(10)
- pass
- """
-
-
-class Location(Model):
- city: str
- country: str
- temperature: float
-
-
-prompts = [
- ContextPrompt(
- context="Find and fix the bug in the provided code snippet",
- text=code,
- ),
- StructuredOutputPrompt(
- prompt="How is the weather in London today?",
- output_schema=Location.schema(),
- ),
- ChatMessage(
- timestamp=datetime.now(),
- msg_id=uuid4(),
- content=[TextContent(type="text", text="who is president of US")],
- )
-
-]
-
-
-@agent.on_interval(period=10.0)
-async def send_message(ctx: Context):
- for prompt in prompts:
- await ctx.send(AI_AGENT_ADDRESS, prompt)
-
-
-@agent.on_message(Response)
-async def handle_response_ai(ctx: Context, sender: str, msg: Response):
- ctx.logger.info(f"Received response from {sender}: {msg.text}")
-
-
-@agent.on_message(StructuredOutputResponse)
-async def handle_structured_output_response(ctx: Context, sender: str, msg: StructuredOutputResponse):
- ctx.logger.info(f"[Received response from ...{sender[-8:]}]:")
- response = Location.parse_obj(msg.output)
- ctx.logger.info(response)
-
-@agent.on_message(ChatAcknowledgement)
-async def handle_ack(ctx: Context, sender: str, msg: ChatAcknowledgement):
- ctx.logger.info(f"Got an acknowledgement from {sender} for {msg.acknowledged_msg_id}")
-
-@agent.on_message(ChatMessage)
-async def handle_ack(ctx: Context, sender: str, msg: ChatMessage):
- ctx.logger.info(f"Received request from {sender} for {msg.content[0].text}")
-
-if __name__ == "__main__":
- agent.run()
-```
\ No newline at end of file
diff --git a/pages/guides/agents/intermediate/chat-protocol.mdx b/pages/guides/agents/intermediate/chat-protocol.mdx
deleted file mode 100644
index 746bea281..000000000
--- a/pages/guides/agents/intermediate/chat-protocol.mdx
+++ /dev/null
@@ -1,208 +0,0 @@
-import { Callout } from 'nextra/components'
-
-# Agent Chat Protocol
-
-This guide walks you through the implementation of agent-to-agent communication using protocols. It includes registering protocols in an Almanac contract and understanding their metadata, which is stored as manifests.
-
-## What is Protocol?
-
-A protocol is a self-contained collection of message handlers. Its digest ensures that the protocol reliably supports the intended messages, serving as a unique identifier for the specific implementation.
-
-### When to Use Protocols
-
-Protocols are designed for modular and reusable communication behavior. They are essential for scaling ecosystems by enabling interoperability.
-
-- **Reusable Communication**: Support predefined message structures to connect with existing systems effortlessly.
-- **Compatibility**: Following protocols ensures seamless communication between agents.
-- **Scalability**: Standardized interactions allow the ecosystem to grow and integrate new agents easily.
-
-## What Are Chat Protocols?
-
-Agent chat protocols define the rules and structure for communication between agents. They ensure that messages exchanged between agents are well-structured, predictable, and interoperable. In the context of agent-based systems, chat protocols specify:
-
-- The types of messages agents can send and receive.
-- The sequence of interactions between agents.
-- How messages are processed and responded to.
-
- In a multi-agent system, agents are identified by their interactive behavior—what output they provide in response to given input. Code unrelated to interactions is irrelevant, as it does not affect observable behavior. Therefore, only protocols have manifests, not agents.
-
-## Overview
-
-In this implementation, two agents, `InitiatorAgent` and a `ResponderAgent`, communicate using predefined protocols. The agents exchange messages, and their protocols and models are registered in an Almanac contract. The metadata is stored as a manifest describing the protocol, models, and interactions.
-
-## Protocols and Communication
-
-### Message Models
-
-- `RequestMessage`: Represents the request initiated by the sender.
-- `ResponseMessage`: Represents the response sent back by the receiver.
-- Both models ensure structured and predictable data exchange.
-
-```py copy
-class RequestMessage(Model):
- text: str
-
-class ResponseMessage(Model):
- text: str
-```
-
-### Initialize Agents
-
-Two agents, `InitiatorAgent` and ResponderAgent, are created with unique seeds for identity.
-
-```py copy
-initiator_agent = Agent(
- name="InitiatorAgent",
- seed="initiator recovery phrase",
-)
-
-responder_agent = Agent(
- name="ResponderAgent",
- seed="responder recovery phrase",
-)
-```
-
-### Define Chat Protocols
-
-Protocols specify how agents interact. The `SimpleProtocol_Initiator` is for the initiator, and `SimpleProtocol_Responder` is for the responder.
-
-```py copy
-initiator_protocol = Protocol(name="SimpleProtocol_Initiator", version="0.1.0")
-responder_protocol = Protocol(name="SimpleProtocol_Responder", version="0.1.0")
-```
-
-### Implement Protocol Handlers
-Handlers define the interaction logic:
-1. Initiator Sends a Message Periodically:
-
-```py copy
-@initiator_protocol.on_interval(period=3.0)
-async def initiator_send_message(ctx: Context):
- await ctx.send(responder_agent.address, RequestMessage(text="Hello there from Initiator!"))
-```
-
-2. Responder Handles the Request and Replies:
-
-```py copy
-@responder_protocol.on_message(RequestMessage, replies=ResponseMessage)
-async def responder_handle_message(ctx: Context, sender: str, msg: RequestMessage):
- ctx.logger.info(f"Received message from {sender}: {msg.text}")
- await ctx.send(sender, ResponseMessage(text="Hello there from Responder!"))
-```
-
-3. Initiator Handles the Response:
-
-```py copy
-@initiator_protocol.on_message(model=ResponseMessage)
-async def initiator_handle_response(ctx: Context, sender: str, msg: ResponseMessage):
- ctx.logger.info(f"Received response from {sender}: {msg.text}")
-```
-
-### Bureau Initialization
-The `Bureau` facilitates the agents' execution and connects them via an endpoint.
-
-```py copy
-bureau = Bureau(endpoint=["http://127.0.0.1:8000/submit"])
-bureau.add(initiator_agent)
-bureau.add(responder_agent)
-```
-
-### Main Function
-Agents include their respective protocols and register their metadata manifest with the Almanac contract.
-
-```py copy
-if __name__ == '__main__':
- initiator_agent.include(initiator_protocol, publish_manifest=True)
- responder_agent.include(responder_protocol, publish_manifest=True)
- bureau.run()
-```
-
-## Metadata Manifest
-This is a registered manifest for agents in the Almanac system, defining communication protocols between the initiator and responder. It specifies message models for both requests and responses.
-When protocols are registered, metadata is stored in the Almanac as a manifest , Published Protocol Manifest looks something like this
-
-- for `initiator_agent` published manifest looks like:
-```json
-{
- "version": "1.0",
- "metadata": {
- "name": "SimpleProtocol_Initiator",
- "version": "0.1.0",
- "digest": "proto:2a34b5504c58f43b2932cdd73358cebe0b668ea10e6796abba3dec8a4c50f25b"
- },
- "models": [
- {
- "digest": "model:465d2d900b616bb4082d4d7fcd9cc558643bb1b9b45660a7f546d5b5b5c0aba5",
- "schema": {
- "properties": {
- "text": {
- "title": "Text",
- "type": "string"
- }
- },
- "required": [
- "text"
- ],
- "title": "ResponseMessage",
- "type": "object"
- }
- }
- ],
- "interactions": []
-}
-```
-- for `responder_agent` published manifest looks like:
-
-```json
-{
- "version": "1.0",
- "metadata": {
- "name": "SimpleProtocol_Responder",
- "version": "0.1.0",
- "digest": "proto:c93ed21a1091272c178c4f6b05619405204e6458294b4a6ee080299bf20e619a"
- },
- "models": [
- {
- "digest": "model:ae2de187153cc7a80641a52927aa2852a820cd56bbbdb8671a0d1e643472f9b7",
- "schema": {
- "properties": {
- "text": {
- "title": "Text",
- "type": "string"
- }
- },
- "required": [
- "text"
- ],
- "title": "RequestMessage",
- "type": "object"
- }
- },
- {
- "digest": "model:465d2d900b616bb4082d4d7fcd9cc558643bb1b9b45660a7f546d5b5b5c0aba5",
- "schema": {
- "properties": {
- "text": {
- "title": "Text",
- "type": "string"
- }
- },
- "required": [
- "text"
- ],
- "title": "ResponseMessage",
- "type": "object"
- }
- }
- ],
- "interactions": [
- {
- "type": "normal",
- "request": "model:ae2de187153cc7a80641a52927aa2852a820cd56bbbdb8671a0d1e643472f9b7",
- "responses": [
- "model:465d2d900b616bb4082d4d7fcd9cc558643bb1b9b45660a7f546d5b5b5c0aba5"
- ]
- }
- ]
-}
-```
\ No newline at end of file
diff --git a/pages/guides/agents/intermediate/communicating-with-other-agents.mdx b/pages/guides/agents/intermediate/communicating-with-other-agents.mdx
deleted file mode 100644
index 4fc65c113..000000000
--- a/pages/guides/agents/intermediate/communicating-with-other-agents.mdx
+++ /dev/null
@@ -1,724 +0,0 @@
-import {Callout} from 'nextra/components'
-import { CodeGroup, CodeSegment, DocsCode, GithubCodeSegment } from "../../../../components/code";
-
-# Communicating with other agents
-
-## Introduction
-
-Communication is an essential feature within any agents network. Communication allows agents to work together, exchange information, and forms an organic marketplace.
-
-In this guide, we will explore two methods of communication between agents:
-
- - **Local communication**.
- - **Remote communication** via the [Almanac Contract ↗️](/references/contracts/uagents-almanac/almanac-overview).
-
-Let's start with **local communication**. This is the first step you would need to undertake to familiarize yourself with the code syntax we will be using in the **remote communication** section.
-
-
-## Prerequisites
-
-Make sure you have read the following resources before going on with this guide:
-
- - [Quick Start Guide for uAgents Framework ↗️](/guides/agents/quickstart)
- - [Creating your first agent ↗️](/guides/agents/getting-started/create-a-uagent)
- - [Agents address ↗️](/guides/agents/getting-started/getting-uagent-address)
- - [Almanac contract ↗️](/concepts/fetch-network/almanac)
- - [Register in Almanac ↗️](/guides/agents/register-in-almanac)
-
-## Imports needed
-
- - [uAgents ↗️](https://pypi.org/project/uagents/)
-
-## Agents: Local Communication
-
-### Walk-through
-
-The first step to better understand how agents communicate is to introduce how 2 agents perform a local communication. Let's consider a basic example in which two agents say hello to each other.
-
-1. First of all, let's create a Python script for this task:
-
-
-
- ```py copy filename="mac"
- touch agents_communication.py
- ```
-
-
-
- ```py copy filename="windows"
- echo. > agents_communication.py
- ```
-
-
-
- ```py copy filename="ubuntu"
- touch agents_communication.py
- ```
-
-
-
-2. Then, we import `Agent`, `Context`, `Bureau`, and `Model` from the uagents library and we then define the message structure for messages to be exchanged between the agents using the class `Model`:
-
-
-
-
-
-
-
- ```py copy filename="agent_communication.py"
-
- from uagents import Agent, Bureau, Context, Model
-
- class Message(Model):
- message: str
-
-```
-
-
-
-
-
-
- The `Message` class defines the structure of message we can receive. In this example it's just a string, but it could be a simple integer, or a complex object too.
-
-3. Now we create two agent instances, `sigmar` and `slaanesh`, with `name` and `seed` parameters:
-
-
-
-
-
-
-
- ```py copy filename="agent_communication.py"
-
- sigmar = Agent(name="sigmar", seed="sigmar recovery phrase", port=8000, endpoint=["http://localhost:8000/submit"])
- slaanesh = Agent(name="slaanesh", seed="slaanesh recovery phrase", port=8001, endpoint=["http://localhost:8001/submit"])
-
-```
-
-
-
-
-
-
- In this example we're running multiple agents from one file.
-
-4. Let's now define `sigmar`'s behaviors. We need to define a function for `sigmar` to send messages to `slaanesh` periodically:
-
-
-
-
-
-
-
- ```py copy filename="agent_communication.py"
-
- @sigmar.on_interval(period=3.0)
- async def send_message(ctx: Context):
- await ctx.send(slaanesh.address, Message(message="hello there slaanesh"))
-
-```
-
-
-
-
-
-
- We can use the `.on_interval()` decorator to define a coroutine `send_message()` function that will be called every 3 seconds. The coroutine function sends a message to `slaanesh` using the `ctx.send()` method of the `Context` object.
-
-5. We then need to define a `sigmar_message_handler()` function for `sigmar` to manage incoming messages:
-
-
-
-
-
-
-
- ```py copy filename="agent_communication.py"
-
- @sigmar.on_message(model=Message)
- async def sigmar_message_handler(ctx: Context, sender: str, msg: Message):
- ctx.logger.info(f"Received message from {sender}: {msg.message}")
-
-```
-
-
-
-
-
-
- This defines the coroutine function `sigmar_message_handler()` that serves as a message handler for `sigmar`. It is triggered whenever `sigmar` receives a message of type `Message`.
-
-6. Let's now define the behavior of our second agent, `slaanesh`:
-
-
-
-
-
-
-
- ```py copy filename="agent_communication.py"
-
- @slaanesh.on_message(model=Message)
- async def slaanesh_message_handler(ctx: Context, sender: str, msg: Message):
- ctx.logger.info(f"Received message from {sender}: {msg.message}")
-
-```
-
-
-
-
-
-
- Same as `sigmar` however, we make `slaanesh` compose a response message to be sent back using the `ctx.send()` method with `sigmar.address` as the recipient address and an instance of the `Message` model as the message payload.
-
- It would also be valid to respond to the sender:
-
-
-
-
-
-
-
- ```py copy filename="agent_communication.py"
-
- await ctx.send(sigmar.address, Message(message="hello there sigmar"))
-
-```
-
-
-
-
-
-
-7. Let's then use the `Bureau` class to create a `Bureau` object. This will allow us to run agents together in the same script:
-
-
-
-
-
-
-
- ```py copy filename="agent_communication.py"
-
- bureau = Bureau()
- bureau.add(sigmar)
- bureau.add(slaanesh)
-
- if __name__ == "__main__":
- bureau.run()
-
-```
-
-
-
-
-
-
-8. Save the script.
-
-The complete script should be looking as follows:
-
-
-
-
-
-
-
- ```py copy filename="agent_communication.py"
-
- from uagents import Agent, Bureau, Context, Model
-
- class Message(Model):
- message: str
-
- sigmar = Agent(name="sigmar", seed="sigmar recovery phrase", port=8000, endpoint=["http://localhost:8000/submit"])
- slaanesh = Agent(name="slaanesh", seed="slaanesh recovery phrase", port=8001, endpoint=["http://localhost:8001/submit"])
-
- @sigmar.on_interval(period=3.0)
- async def send_message(ctx: Context):
- await ctx.send(slaanesh.address, Message(message="hello there slaanesh"))
-
- @sigmar.on_message(model=Message)
- async def sigmar_message_handler(ctx: Context, sender: str, msg: Message):
- ctx.logger.info(f"Received message from {sender}: {msg.message}")
-
- @slaanesh.on_message(model=Message)
- async def slaanesh_message_handler(ctx: Context, sender: str, msg: Message):
- ctx.logger.info(f"Received message from {sender}: {msg.message}")
- await ctx.send(sigmar.address, Message(message="hello there sigmar"))
-
- bureau = Bureau()
- bureau.add(sigmar)
- bureau.add(slaanesh)
-
- if __name__ == "__main__":
- bureau.run()
-
-```
-
-
-
-
-
-
-We are now ready to run the script: `python agents_communication.py`
-
-The output would be:
-
- ```
- WARNING: [sigmar]: No endpoints provided. Skipping registration: Agent won't be reachable.
- WARNING: [slaanesh]: No endpoints provided. Skipping registration: Agent won't be reachable.
- INFO: [bureau]: Starting server on http://0.0.0.0:8000 (Press CTRL+C to quit)
- INFO: [sigmar]: Received message from agent1q0mau8vkmg78xx0sh8cyl4tpl4ktx94pqp2e94cylu6haugt2hd7j9vequ7: hello there sigmar
- INFO: [slaanesh]: Received message from agent1qww3ju3h6kfcuqf54gkghvt2pqe8qp97a7nzm2vp8plfxflc0epzcjsv79t: hello there slaanesh
- INFO: [sigmar]: Received message from agent1q0mau8vkmg78xx0sh8cyl4tpl4ktx94pqp2e94cylu6haugt2hd7j9vequ7: hello there sigmar
- INFO: [slaanesh]: Received message from agent1qww3ju3h6kfcuqf54gkghvt2pqe8qp97a7nzm2vp8plfxflc0epzcjsv79t: hello there slaanesh
- INFO: [sigmar]: Received message from agent1q0mau8vkmg78xx0sh8cyl4tpl4ktx94pqp2e94cylu6haugt2hd7j9vequ7: hello there sigmar
- ```
-
-However, these agents can only communicate with each other on their local network, let's next see how we can register these agents to be able to communicate with many other agents in the open network.
-
-## Agents Remote Communication: the Almanac Contract
-
-An agent must register to the [Almanac contract ↗️](/references/contracts/uagents-almanac/almanac-overview) to communicate, to search for other agents or be found. Agents can query this contract to retrieve an HTTP endpoint for a recipient agent. [Registration in the Almanac ↗️](/guides/agents/register-in-almanac) requires paying a small fee, so make sure to have enough funds to allow for this. You can query the Almanac now, by using the search feature on [Agentverse ↗️](https://agentverse.ai/).
-
-Whenever an agent registers in the Almanac, it must specify the service [endpoints ↗️](/references/contracts/uagents-almanac/endpoints) alongside a weight parameter for each endpoint provided. Agents trying to communicate with your agent will choose the service endpoints using a weighted random selection.
-
-Here, we show you how to create two agents and make them remotely communicate by registering and using the Almanac Contract.
-
-### Walk-through
-
-The first step would be to create two different Python scripts for this task, each one representing a remote agent:
-
- Slaanesh:
-
-
-
- ```py copy filename="mac"
- touch remote_agents_slaanesh.py
- ```
-
-
-
- ```py copy filename="windows"
- echo. > remote_agents_slaanesh.py
- ```
-
-
-
- ```py copy filename="ubuntu"
- touch remote_agents_slaanesh.py
- ```
-
-
-
- Sigmar:
-
-
-
- ```py copy filename="mac"
- touch remote_agents_sigmar.py
- ```
-
-
-
- ```py copy filename="windows"
- echo. > remote_agents_sigmar.py
- ```
-
-
-
- ```py copy filename="ubuntu"
- touch remote_agents_sigmar.py
- ```
-
-
-
-Let's start by defining the script for **sigmar**.
-
-#### Sigmar
-
-1. In `remote_agents_sigmar.py` script, we would need to import the necessary classes from the `uagents` (`Agent`, `Context`, and `Model`). We then need to define the message structure for messages to be exchanged between agents using the class `Model`, as well as the `RECIPIENT_ADDRESS` (slaanesh's address). Note that if you don't know slaanesh's address yet, you can use `print(slaanesh.address)` after defining agent `slaanesh` to get this information. This is the address towards which `sigmar` will send messages:
-
-
-
-
-
-
-
- ```py copy filename="remote_agents_sigmar.py"
-
- from uagents import Agent, Context, Model
-
- class Message(Model):
- message: str
-
- RECIPIENT_ADDRESS = "agent1qvm7v76zs6w2x90xvq99yc5xh7c2thjtm44zc09me556zxnra627gkf4zum"
-
-
-```
-
-
-
-
-
-
-2. Let's now create our agent, `sigmar`, by providing `name`, `seed`, `port`, and `endpoint`:
-
-
-
-
-
-
-
- ```py copy filename="remote_agents_sigmar.py"
-
- sigmar = Agent(
- name="sigmar",
- port=8000,
- seed="sigmar secret phrase",
- endpoint=["http://127.0.0.1:8000/submit"],
- )
-
-```
-
-
-
-
-
-
-3. We are ready to define `sigmar`'s behaviors. Let's start with a function for `sigmar` to send messages:
-
-
-
-
-
-
-
- ```py copy filename="remote_agents_sigmar.py"
-
- @sigmar.on_interval(period=2.0)
- async def send_message(ctx: Context):
- await ctx.send(RECIPIENT_ADDRESS, Message(message="hello there slaanesh"))
-
-
-```
-
-
-
-
-
-
- Here, the `.on_interval()` decorator schedules the `send_message()` function to be run every 2 seconds. Inside the function, there is an asynchronous call indicated by the `ctx.send()` method. This call sends a message with the content `"hello there slaanesh"` to the `RECIPIENT_ADDRESS`.
-
-4. We then need to define a function for `sigmar` to handle incoming messages from other agents:
-
-
-
-
-
-
-
- ```py copy filename="remote_agents_sigmar.py"
-
- @sigmar.on_message(model=Message)
- async def message_handler(ctx: Context, sender: str, msg: Message):
- ctx.logger.info(f"Received message from {sender}: {msg.message}")
-
- if __name__ == "__main__":
- sigmar.run()
-
-```
-
-
-
-
-
-
- Here, we have used the `.on_message()` decorator to register the `message_handler()` coroutine function as a handler for incoming messages of type `Message`.
-
- The `message_handler()` function takes three arguments: `ctx`, `sender`, and `msg`. Inside this function, we call the `ctx.logger.info()` method to log information about the received message, including the sender and message content.
-
-5. We can now save the script.
-
-The overall script for sigmar agent should be looking as follows:
-
-
-
-
-
-
-
- ```py copy filename="remote_agents_sigmar.py"
-
- from uagents import Agent, Context, Model
-
- class Message(Model):
- message: str
-
- RECIPIENT_ADDRESS = "agent1qvm7v76zs6w2x90xvq99yc5xh7c2thjtm44zc09me556zxnra627gkf4zum"
-
- sigmar = Agent(
- name="sigmar",
- port=8000,
- seed="sigmar secret phrase",
- endpoint=["http://127.0.0.1:8000/submit"],
- )
-
- @sigmar.on_interval(period=2.0)
- async def send_message(ctx: Context):
- await ctx.send(RECIPIENT_ADDRESS, Message(message="hello there slaanesh"))
-
- @sigmar.on_message(model=Message)
- async def message_handler(ctx: Context, sender: str, msg: Message):
- ctx.logger.info(f"Received message from {sender}: {msg.message}")
-
- if __name__ == "__main__":
- sigmar.run()
-
-```
-
-
-
-
-
-
-Remember that you need to provide the `name`, `seed`, `port`, `endpoint` and `RECIPIENT_ADDRESS` parameters to correctly run this code.
-
-We can now proceed by writing the script for agent `slaanesh`.
-
-#### Slaanesh
-
-1. In `remote_agents_slaanesh.py` script, import the necessary classes from the `uagents`. Then, define the message structure for messages to be exchanged between the agents using the `Model` class, as well as our second uAgent, `slaanesh`, by providing `name`, `seed`, `port`, and `endpoint`:
-
-
-
-
-
-
-
- ```py copy filename="remote_agents_slaanesh.py"
-
- from uagents import Agent, Context, Model
-
- class Message(Model):
- message: str
-
- slaanesh = Agent(
- name="slaanesh",
- port=8001,
- seed="slaanesh secret phrase",
- endpoint=["http://127.0.0.1:8001/submit"],
- )
-
-
-```
-
-
-
-
-
-
-2. Let's now define a function for `slaanesh` to handle incoming messages and answering back to the sender:
-
-
-
-
-
-
-
- ```py copy filename="remote_agents_slaanesh.py"
-
- @slaanesh.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 sigmar"))
-
- if __name__ == "__main__":
- slaanesh.run()
-
-```
-
-
-
-
-
-
- Here, we have defined an asynchronous `message_handler()` function for slaanesh to handle incoming messages from other uAgents. The function is decorated with `.on_message()`, and it is triggered whenever a message of type `Message` is received by `slaanesh`. When a message is received, the handler function logs the sender's address and the content of the message. It then sends a response back to the sender using the `ctx.send()` with a new message. The response message contains the `Message` data model with a `"hello there sigmar"` message.
-
-3. Save the script.
-
-The overall script for `slaanesh` should be looking as follows:
-
-
-
-
-
-
-
- ```py copy filename="remote_agents_slaanesh.py"
-
- from uagents import Agent, Context, Model
-
- class Message(Model):
- message: str
-
- slaanesh = Agent(
- name="slaanesh",
- port=8001,
- seed="slaanesh secret phrase",
- endpoint=["http://127.0.0.1:8001/submit"],
- )
-
- @slaanesh.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 sigmar"))
-
- if __name__ == "__main__":
- slaanesh.run()
-
-```
-
-
-
-
-
-
-Remember that you need to provide the `name`, `seed`, `port` and `endpoint` parameters to correctly run this code.
-
-#### Run the scripts
-
-In different terminal windows, first run `slaanesh` and then `sigmar`. They will register automatically in the Almanac contract using their funds. The received messages will print out in each terminal:
-
- Terminal 1: `python remote_agents_slaanesh.py`
-
- Terminal 2: `python remote_agents_sigmar.py`
-
-The output will depend on the terminal:
-
-- **Sigmar**:
-
- ```
- INFO: [sigmar]: Registration on Almanac API successful
- INFO: [sigmar]: Registering on almanac contract...
- INFO: [sigmar]: Registering on almanac contract...complete
- INFO: [sigmar]: Agent inspector available at https://agentverse.ai/inspect/?uri=http%3A//127.0.0.1%3A8000&address=agent1qvwqu6a0km09mq4f6j6kmke9smswmgcergmml9a54av9449rqtmmxy4qwe6
- INFO: [sigmar]: Starting server on http://0.0.0.0:8000 (Press CTRL+C to quit)
- INFO: [sigmar]: Received message from agent1qvm7v76zs6w2x90xvq99yc5xh7c2thjtm44zc09me556zxnra627gkf4zum: hello there sigmar
- INFO: [sigmar]: Received message from agent1qvm7v76zs6w2x90xvq99yc5xh7c2thjtm44zc09me556zxnra627gkf4zum: hello there sigmar
- INFO: [sigmar]: Received message from agent1qvm7v76zs6w2x90xvq99yc5xh7c2thjtm44zc09me556zxnra627gkf4zum: hello there sigmar
- ```
-
-- **Slaanesh**:
-
- ```
- INFO: [slaanesh]: Registration on Almanac API successful
- INFO: [slaanesh]: Registering on almanac contract...
- INFO: [slaanesh]: Registering on almanac contract...complete
- INFO: [slaanesh]: Agent inspector available at https://agentverse.ai/inspect/?uri=http%3A//127.0.0.1%3A8001&address=agent1qvm7v76zs6w2x90xvq99yc5xh7c2thjtm44zc09me556zxnra627gkf4zum
- INFO: [slaanesh]: Starting server on http://0.0.0.0:8001 (Press CTRL+C to quit)
- INFO: [slaanesh]: Received message from agent1qvwqu6a0km09mq4f6j6kmke9smswmgcergmml9a54av9449rqtmmxy4qwe6: hello there slaanesh
- INFO: [slaanesh]: Received message from agent1qvwqu6a0km09mq4f6j6kmke9smswmgcergmml9a54av9449rqtmmxy4qwe6: hello there slaanesh
- INFO: [slaanesh]: Received message from agent1qvwqu6a0km09mq4f6j6kmke9smswmgcergmml9a54av9449rqtmmxy4qwe6: hello there slaanesh
- ```
-
-### Before we go on...
-
-As we touched on before in [Register in Almanac ↗️](/guides/agents/register-in-almanac), when the agent uses `.run()` function this tells the `uagents` library to register the agent to the Almanac. It's simple, agents initialize themselves, and register to a service which acts as a search engine for agents (the Almanac) then, when agents receive messages they can respond.
-
-## Conclusion
-
-In this guide, we explored two different methods of communication for Agents using the `uagents` library:
-
- - **Local communication**.
- - **Remote communication** via the Almanac Contract.
-
-For _local communication_, we learned how to use the `uagents` library to create two agents, `sigmar` and `slaanesh`, and enable them to exchange messages with one another. We defined the message structure using the `Model` class and implemented message handlers for both agents. By running the script we observed their real-time message exchange.
-
-Next, we delved into _remote communication_, which facilitates interaction between agents through the Almanac Contract. This method requires registering the agents in the Almanac Contract and querying for **HTTP endpoints** for communication. By running the scripts separately, we could observe the real-time messages exchange, fostering a decentralized network of interacting agents.
-
-With this, we suspect you're ready to start building agents, as part of multi agent system the Almanac allows; awesome. If you want to go further though, take a look at the [message verification ↗️](/guides/agents/message-verification) and [sending tokens ↗️](/guides/agents/send-tokens), after-all you do want to be sure you are speaking to who you think you are, and agents getting paid is awesome.
diff --git a/pages/guides/agents/intermediate/handlers.mdx b/pages/guides/agents/intermediate/handlers.mdx
deleted file mode 100644
index 2acb696cf..000000000
--- a/pages/guides/agents/intermediate/handlers.mdx
+++ /dev/null
@@ -1,863 +0,0 @@
-import { Callout } from 'nextra/components'
-import { CodeGroup, CodeSegment, DocsCode, GithubCodeSegment } from "../../../../components/code";
-
-# Agent Handlers
-
-## Introduction
-
-Within the uAgents Framework, functions can be decorated with handlers, to only be triggered on a condition caught by the uAgents library.
-
-Below, we show how to use the following different event handlers:
-
- 1. **Interval tasks**: `.on_interval()`
- 2. **Handle messages**: `.on_message()`
- 3. **Answer queries**: `.on_query()`
- 4. **Triggered by event**: `on_event()`
-
-## Creating an interval task with `on_interval()` handler
-
-Sometimes an agent will need to perform a task periodically. To do this we can use the `on_interval()` decorator which periodically repeats a given function for the agent. For instance, an agent could send a message every 2 seconds to another agent.
-
-**Let's get started and create our first interval task!**
-
-## Prerequisites
-
-Make sure you have read the following resources before going on with this guide:
-
- - [Quick Start Guide for uAgents Framework ↗️](/guides/agents/quickstart)
- - [Creating your first agent ↗️](/guides/agents/getting-started/create-a-uagent)
- - [Agents address ↗️](/guides/agents/getting-started/getting-uagent-address)
- - [Communicating with other agents ↗️](/guides/agents/intermediate/communicating-with-other-agents)
-
-## Imports needed
-
- - [uAgents ↗️](https://pypi.org/project/uagents/)
- - [FastAPI ↗️](https://pypi.org/project/fastapi/)
-
-### Walk-through
-
-1. Let's create a Python script for this task, and name it:
-
-
-
- ```py copy filename="mac"
- touch interval_task.py
- ```
-
-
-
- ```py copy filename="windows"
- echo. > interval_task.py
- ```
-
-
-
- ```py copy filename="ubuntu"
- touch interval_task.py
- ```
-
-
-
-2. Then import the necessary classes from `uagents` library, `Agent` and `Context`, and create our agent:
-
-
-
-
-
-
-
- ```py copy filename="interval-task.py"
-
- from uagents import Agent, Context
-
- agent = Agent(name="alice", seed="alice recovery phrase", port=8000, endpoint=["http://localhost:8000/submit"])
-
-```
-
-
-
-
-
-
-3. Create a function to handle the startup event, which will introduce the agent:
-
-
-
-
-
-
-
- ```py copy filename="interval-task.py"
-
- @agent.on_event("startup")
- async def introduce_agent(ctx: Context):
- ctx.logger.info(f"Hello, I'm agent {agent.name} and my address is {agent.address}.")
-
-```
-
-
-
-
-
-
-4. We can now define our agent's interval behavior. We want our agent to log a message every 2 seconds using the `on_interval` decorator:
-
-
-
-
-
-
-
- ```py copy filename="interval-task.py"
-
- @agent.on_interval(period=2.0)
- async def say_hello(ctx: Context):
- ctx.logger.info("Hello!")
-
- if __name__ == "__main__":
- agent.run()
-
-```
-
-
-
-
-
-
- The output will be printed out using the `ctx.logger.info()` method.
-
-5. Save the script.
-
-The overall script should look as follows:
-
-
-
-
-
-
-
- ```py copy filename="interval-task.py"
-
- from uagents import Agent, Context
-
- agent = Agent(name="alice", seed="alice recovery phrase", port=8000, endpoint=["http://localhost:8000/submit"])
-
- @agent.on_event("startup")
- async def introduce_agent(ctx: Context):
- ctx.logger.info(f"Hello, I'm agent {agent.name} and my address is {agent.address}.")
-
- @agent.on_interval(period=2.0)
- async def say_hello(ctx: Context):
- ctx.logger.info("Hello!")
-
- if __name__ == "__main__":
- agent.run()
-
-```
-
-
-
-
-
-
-### Run the script
-
-Run the script: `python interval_task.py`
-
-The output should be as follows:
-
- ```
- INFO: [alice]: Registration on Almanac API successful
- INFO: [alice]: Registering on almanac contract...
- INFO: [alice]: Registering on almanac contract...complete
- INFO: [alice]: Agent inspector available at https://agentverse.ai/inspect/?uri=http%3A//127.0.0.1%3A8000&address=agent1qww3ju3h6kfcuqf54gkghvt2pqe8qp97a7nzm2vp8plfxflc0epzcjsv79t
- INFO: [alice]: Starting server on http://0.0.0.0:8000 (Press CTRL+C to quit)
- INFO: [alice]: Hello, I'm agent alice and my address is agent1qww3ju3h6kfcuqf54gkghvt2pqe8qp97a7nzm2vp8plfxflc0epzcjsv79t.
- INFO: [alice]: Hello!
- INFO: [alice]: Hello!
- INFO: [alice]: Hello!
- ```
-
-## Handle messages using the `on_message()` handler
-
-We now showcase a scenario where three agents, named `alice`, `bob`, and `charles`, use a custom [protocol ↗️](/references/uagents/uagents-protocols/agent-protocols) to communicate. In the example, Alice and Bob support the protocol, whereas Charles attempts to send broadcast messages to all agents using the protocol. Agents use the `on_message()` handler which allows them to handle messages matching specific data models.
-
-**Let's get started!**
-
-### Walk-through
-
-1. First of all, let's create a Python script for this task, and name it:
-
-
-
- ```py copy filename="mac"
- touch broadcast.py
- ```
-
-
-
- ```py copy filename="windows"
- echo. > broadcast.py
- ```
-
-
-
- ```py copy filename="ubuntu"
- touch broadcast.py
- ```
-
-
-
-2. We then need to import the `Agent`, `Bureau`, `Context`, `Model`, and `Protocol` classes from the `uagents` library. Then, let's create the 3 different agents using the class `Agent`. Each agent is initialized with a unique name and a seed phrase for wallet recovery.
-
-
-
-
-
-
-
- ```py copy filename="broadcast.py"
-
- from uagents import Agent, Bureau, Context, Model, Protocol
-
- # create agents
- # alice and bob will support the protocol
- # charles will try to reach all agents supporting the protocol
- alice = Agent(name="alice", seed="alice recovery phrase", port=8000, endpoint=["http://127.0.0.1:8000/submit"])
- bob = Agent(name="bob", seed="bob recovery phrase", port=8001, endpoint=["http://127.0.0.1:8001/submit"])
- charles = Agent(name="charles", seed="charles recovery phrase", port=8002, endpoint=["http://127.0.0.1:8002/submit"])
-
-```
-
-
-
-
-
-
- It is optional but useful to include a `seed` parameter when creating an agent to set fixed [addresses ↗️](/guides/agents/getting-uagent-address). Otherwise, random addresses will be generated every time you run the agent.
-
-3. Let's then define the message data models to specify the type of messages being handled and exchanged by the agents. We define a `BroadcastExampleRequest` and a `BroadcastExampleResponse` data models. Finally, create a `protocol` named `proto` with version `1.0`:
-
-
-
-
-
-
-
- ```py copy filename="broadcast.py"
-
- class BroadcastExampleRequest(Model):
- pass
-
-
- class BroadcastExampleResponse(Model):
- text: str
-
-
- # define protocol
- proto = Protocol(name="proto", version="1.0")
-
-```
-
-
-
-
-
-
-4. Let's now define a message handler function for incoming messages of type `BroadcastExampleRequest` in the protocol:
-
-
-
-
-
-
-
- ```py copy filename="broadcast.py"
-
- @proto.on_message(model=BroadcastExampleRequest, replies=BroadcastExampleResponse)
- async def handle_request(ctx: Context, sender: str, _msg: BroadcastExampleRequest):
- await ctx.send(
- sender, BroadcastExampleResponse(text=f"Hello from {ctx.agent.name}")
- )
-
-```
-
-
-
-
-
-
- Here we defined a `handle_request()` function which is used whenever a request is received. This sends a response back to the sender. This function is decorated with the `.on_message()` decorator indicating that this function is triggered whenever a message of type `BroadcastExampleRequest` is received. The function sends a response containing a greeting message with the name of the agent that sent the request in the first place.
-
-5. Now, we need to include the `protocol` into the agents. Specifically, the protocol is included in both `alice` and `bob` agents. This means they will follow the rules defined in the protocol when communicating:
-
-
-
-
-
-
-
- ```py copy filename="broadcast.py"
-
- alice.include(proto)
- bob.include(proto)
-
-```
-
-
-
-
-
-
-
- After the first registration in the [Almanac ↗️](/references/contracts/uagents-almanac/almanac-overview) smart contract, it will take about 5 minutes before the agents can be found through the protocol.
-
-
-6. It is now time to define the behavior and function of `charles` agent:
-
-
-
-
-
-
-
- ```py copy filename="broadcast.py"
-
- @charles.on_interval(period=5)
- async def say_hello(ctx: Context):
- status_list = await ctx.broadcast(proto.digest, message=BroadcastExampleRequest())
- ctx.logger.info(f"Trying to contact {len(status_list)} agents.")
-
-
- @charles.on_message(model=BroadcastExampleResponse)
- async def handle_response(ctx: Context, sender: str, msg: BroadcastExampleResponse):
- ctx.logger.info(f"Received response from {sender}: {msg.text}")
-
-```
-
-
-
-
-
-
- In the first part, we use the `.on_interval()` decorator to define an interval behavior for this agent when the script is being run. In this case, the agent will execute the `say_hello()` function every 5 seconds. The `Context` object is a collection of data and functions related to the agent. Inside the `say_hello()` function, the agent uses the `ctx.broadcast()` method to send a broadcast message. The message is of type `BroadcastExampleRequest()` and it is being sent using the protocol's digest (`proto.digest`).
-
- Then, we defined a `.on_message()` decorator which decorates `handle_response()` function. This function handles all incoming messages of type `BroadcastExampleResponse` from other agents. When a response is received, it logs the information. Inside the `handle_response()` function, the agent logs an informational message using `ctx.logger.info()` method to print the sender and the content of the message. The message includes the sender's name and the text content of the response message.
-
-7. We are now ready to set up a `Bureau` object for agents to be run together at the same time, and we add `alice`, `bob`, and `charles` to it using the `bureau.add()` method:
-
-
-
-
-
-
-
- ```py copy filename="broadcast.py"
-
- bureau = Bureau(port=8000, endpoint="http://localhost:8000/submit")
- bureau.add(alice)
- bureau.add(bob)
- bureau.add(charles)
-
- if __name__ == "__main__":
- bureau.run()
-
-```
-
-
-
-
-
-
- The bureau is assigned to listen on `port=8000` and specifies an `endpoint` at `"http://localhost:8000/submit"` for submitting data.
-
-8. Save the script.
-
-The overall script should look as follows:
-
-
-
-
-
-
-
- ```py copy filename="broadcast.py"
-
- from uagents import Agent, Bureau, Context, Model, Protocol
-
- # create agents
- # alice and bob will support the protocol
- # charles will try to reach all agents supporting the protocol
- alice = Agent(name="alice", seed="alice recovery phrase", port=8000, endpoint=["http://127.0.0.1:8000/submit"])
- bob = Agent(name="bob", seed="bob recovery phrase", port=8001, endpoint=["http://127.0.0.1:8001/submit"])
- charles = Agent(name="charles", seed="charles recovery phrase", port=8002, endpoint=["http://127.0.0.1:8002/submit"])
-
-
- class BroadcastExampleRequest(Model):
- pass
-
-
- class BroadcastExampleResponse(Model):
- text: str
-
-
- # define protocol
- proto = Protocol(name="proto", version="1.0")
-
-
- @proto.on_message(model=BroadcastExampleRequest, replies=BroadcastExampleResponse)
- async def handle_request(ctx: Context, sender: str, _msg: BroadcastExampleRequest):
- await ctx.send(
- sender, BroadcastExampleResponse(text=f"Hello from {ctx.agent.name}")
- )
-
-
- # include protocol
- # Note: after the first registration on the almanac smart contract, it will
- # take about 5 minutes before the agents can be found through the protocol
- alice.include(proto)
- bob.include(proto)
-
-
- # let charles send the message to all agents supporting the protocol
- @charles.on_interval(period=5)
- async def say_hello(ctx: Context):
- status_list = await ctx.broadcast(proto.digest, message=BroadcastExampleRequest())
- ctx.logger.info(f"Trying to contact {len(status_list)} agents.")
-
-
- @charles.on_message(model=BroadcastExampleResponse)
- async def handle_response(ctx: Context, sender: str, msg: BroadcastExampleResponse):
- ctx.logger.info(f"Received response from {sender}: {msg.text}")
-
-
- bureau = Bureau(port=8000, endpoint="http://localhost:8000/submit")
- bureau.add(alice)
- bureau.add(bob)
- bureau.add(charles)
-
- if __name__ == "__main__":
- bureau.run()
-
-```
-
-
-
-
-
-
-### Run the script
-
-Make sure to have activated your virtual environment correctly.
-
-Run the script: `python broadcast.py`
-
-The output would be:
-
- ```
- INFO: [alice]: Registration on Almanac API successful
- INFO: [alice]: Registering on almanac contract...
- INFO: [alice]: Registering on almanac contract...complete
- INFO: [ bob]: Registration on Almanac API successful
- INFO: [ bob]: Registering on almanac contract...
- INFO: [ bob]: Registering on almanac contract...complete
- INFO: [charles]: Registration on Almanac API successful
- INFO: [charles]: Registration on Almanac API successful
- INFO: [charles]: Registering on almanac contract...
- INFO: [bureau]: Starting server on http://0.0.0.0:8000 (Press CTRL+C to quit)
- INFO: [charles]: Trying to contact 2 agents.
- INFO: [charles]: Received response from agent1q0mau8vkmg78xx0sh8cyl4tpl4ktx94pqp2e94cylu6haugt2hd7j9vequ7: Hello from bob
- INFO: [charles]: Received response from agent1qww3ju3h6kfcuqf54gkghvt2pqe8qp97a7nzm2vp8plfxflc0epzcjsv79t: Hello from alice
- ```
-
-## Answer queries with `on_query()` handler
-
-The `on_query()` handler is used to register a [Function ↗️](/guides/agents/intermediate/agent-functions) as a handler for incoming queries that match a specified `Model`. This decorator enables the agent to respond to queries in an event-driven manner.
-
-### Walk-through
-
-#### Agent's script
-
-For the agent, the script sets up an agent to handle incoming queries. It defines two models: `TestRequest` and `Response`. Upon startup, it logs the agent's details. The core functionality lies in the `query_handler`, decorated with `@agent.on_query()`, which processes received queries and sends back a predefined response. This demonstrates creating responsive agents within the `uagents` Framework, showcasing how they can interact with other agents or functions in an asynchronous, event-driven architecture.
-
-
-
-
-
-
-
- ```py copy filename="agent.py"
-
- from uagents import Agent, Context, Model
-
- class TestRequest(Model):
- message: str
-
- class Response(Model):
- text: str
-
- # Initialize the agent with its configuration.
- agent = Agent(
- name="your_agent_name_here",
- seed="your_agent_seed_here",
- port=8001,
- endpoint="http://localhost:8001/submit",
- )
-
- @agent.on_event("startup")
- async def startup(ctx: Context):
- ctx.logger.info(f"Starting up {agent.name}")
- ctx.logger.info(f"With address: {agent.address}")
- ctx.logger.info(f"And wallet address: {agent.wallet.address()}")
-
- # Decorator to handle incoming queries.
- @agent.on_query(model=TestRequest, replies={Response})
- async def query_handler(ctx: Context, sender: str, _query: TestRequest):
- ctx.logger.info("Query received")
- try:
- # do something here
- await ctx.send(sender, Response(text="success"))
- except Exception:
- await ctx.send(sender, Response(text="fail"))
-
- # Main execution block to run the agent.
- if __name__ == "__main__":
- agent.run()
-
-```
-
-
-
-
-
-
-The agent is created using the `Agent` class from `uagents` library. You can initialize it by providing it with a `name`, `seed`, `port`, and `endpoint`. It defines an `on_event()` handler for the `startup` event, where it logs information about the agent's initialization. It defines an `on_query()` handler for handling queries of type `TestRequest`. Upon receiving a query, it processes it and sends back a `Response`. The agent is then set to run.
-
-#### Proxy
-
-The proxy is implemented using `FastAPI`. It sets up two routes: `"/"` for a simple root message and `"/endpoint"` for receiving requests. When a `POST` request is made to `"/endpoint"` with a JSON payload containing a `TestRequest`, it triggers the `make_agent_call` function. Inside `make_agent_call`, it calls `agent_query` to communicate with the agent. The agent receives the query, processes it, and sends back a response. The proxy receives the response from the agent and sends back a success message along with the response text.
-
-Let's explore the Proxy code script step-by-step:
-
-1. First of all navigate to directory where you want to create your project.
-2. Create a Python script name `on_query.py` by running:
-
-
-
- ```py copy filename="mac"
- touch on_query.py
- ```
-
-
-
- ```py copy filename="windows"
- echo. > on_query.py
- ```
-
-
-
- ```py copy filename="ubuntu"
- touch on_query.py
- ```
-
-
-
-3. We need to import `json`, `fastapi`, `uagent`'s `Model` and `query`. Then we would need to define the query format using the `TestRequest` class as a subclass of `Model`:
-
-
-
-
-
-
-
- ```py copy filename="on_query.py"
-
- import json
-
- from fastapi import FastAPI, Request
- from uagents import Model
- from uagents.query import query
- from uagents.envelope import Envelope
-
- AGENT_ADDRESS = "agent1qt6ehs6kqdgtrsduuzslqnrzwkrcn3z0cfvwsdj22s27kvatrxu8sy3vag0"
-
- class TestRequest(Model):
- message: str
-
-```
-
-
-
-
-
-
-4. Create `agent_query()` function to send query to agent and decode the response received.
-
-
-
-
-
-
-
- ```py copy filename="on_query.py"
-
- async def agent_query(req):
- response = await query(destination=AGENT_ADDRESS, message=req, timeout=15)
- if isinstance(response, Envelope):
- data = json.loads(response.decode_payload())
- return data["text"]
- return response
-
-```
-
-
-
-
-
-
-5. Initialize a `FastAPI` app:
-
-
-
-
-
-
-
- ```py copy filename="on_query.py"
-
- app = FastAPI()
-
-```
-
-
-
-
-
-
-6. Define a root endpoint to test the server:
-
-
-
-
-
-
-
- ```py copy filename="on_query.py"
-
- @app.get("/")
- def read_root():
- return "Hello from the Agent controller"
-
-```
-
-
-
-
-
-
-7. Define an endpoint to make agent calls:
-
-
-
-
-
-
-
- ```py copy filename="on_query.py"
-
- @app.post("/endpoint")
- async def make_agent_call(req: Request):
- model = TestRequest.parse_obj(await req.json())
- try:
- res = await agent_query(model)
- return f"successful call - agent response: {res}"
- except Exception:
- return "unsuccessful agent call"
-
-```
-
-
-
-
-
-
-8. Save the script. Remember that you need to provide the `AGENT_ADDRESS` parameter to correctly run this code.
-
-The overall script should look as follows:
-
-
-
-
-
-
-
- ```py copy filename="on_query.py"
-
- import json
-
- from fastapi import FastAPI, Request
- from uagents import Model
- from uagents.query import query
- from uagents.envelope import Envelope
-
- AGENT_ADDRESS = "agent1qt6ehs6kqdgtrsduuzslqnrzwkrcn3z0cfvwsdj22s27kvatrxu8sy3vag0"
-
- class TestRequest(Model):
- message: str
-
- async def agent_query(req):
- response = await query(destination=AGENT_ADDRESS, message=req, timeout=15)
- if isinstance(response, Envelope):
- data = json.loads(response.decode_payload())
- return data["text"]
- return response
-
-
- app = FastAPI()
-
- @app.get("/")
- def read_root():
- return "Hello from the Agent controller"
-
- @app.post("/endpoint")
- async def make_agent_call(req: Request):
- model = TestRequest.parse_obj(await req.json())
- try:
- res = await agent_query(model)
- return f"successful call - agent response: {res}"
- except Exception:
- return "unsuccessful agent call"
-
-```
-
-
-
-
-
-
-#### Run the example
-
-In separate terminals:
-
-1. Run the **FastAPI proxy**: `uvicorn proxy:app`
-
-2. Run the **agent**: `python agent.py`
-
-3. Query the agent via the proxy: `curl -d '{"message": "test"}' -H "Content-Type: application/json" -X POST http://localhost:8000/endpoint`
-
-## Catching events with `on_event()` handler
-
-During startup, and shutdown there are two events that are caught by the uAgents library, `startup` and `shutdown`.
-
-Here's an example:
-
-### on_event("startup")
-
-```python copy
- @agent.on_event("startup")
- async def introduce_agent(ctx: Context):
- ctx.logger.info(f"Hello, I'm agent {agent.name} and my address is {agent.address}.")
- ...
-
-```
-
-### on_event("shutdown")
-
-```python copy
- @agent.on_event("shutdown")
- async def introduce_agent(ctx: Context):
- ctx.logger.info(f"Hello, I'm agent {agent.name} and I am shutting down")
- ...
-
-```
-
diff --git a/pages/guides/agents/intermediate/hosted-agent.mdx b/pages/guides/agents/intermediate/hosted-agent.mdx
deleted file mode 100644
index 72fc84454..000000000
--- a/pages/guides/agents/intermediate/hosted-agent.mdx
+++ /dev/null
@@ -1,82 +0,0 @@
-import { Callout } from 'nextra/components'
-import { CodeGroup, CodeSegment, DocsCode, GithubCodeSegment } from "../../../../components/code";
-
-
-This article is a work-in-progress. It will be expanded rapidly.
-
-
-# Agents running on Agentverse
-
-Agents running on [Agentverse ↗️](https://agentverse.ai/) act as [Functions ↗️](/guides/agents/intermediate/agent-functions); they do this by having an orchestrator in the background that calls functions on the agent when a routine should execute, or a message is called. This helps us keep hosted agents costs down which are passed on to the user.
-
-However, you should be aware of how state works in a hosted agent. A global variable in agentverse will always have the value of the initialized value you set. Updating this value from a function will not work outside the scope of that function call, as the variable is set when the agent is loaded into the Orchestrator which does not load up the entire agent for each call, a global variable will always have the initial set value. To have values persist you must store this values in storage.
-
-Let's show this with an example:
-
-
-
-
-
-
-
- ```py copy filename="storage_agent_example.py"
-
- from uagents import Agent, Context
-
- agent = Agent(name="Hosted", seed="your_seed_phrase", port=8000, endpoint=["http://127.0.0.1:8000/submit"])
-
- global_counter = 0
-
- @agent.on_interval(period=1.0)
- async def on_interval(ctx: Context):
- global global_counter
-
- # increment the global counter - bad!
- global_counter += 1
-
- current_count = int(ctx.storage.get("count") or 0)
- current_count += 1
-
- ctx.logger.info(f"My count is: {current_count}")
- ctx.logger.info(f"My global is: {global_counter}")
-
- ctx.storage.set("count", current_count)
-
- if __name__ == "__main__":
- agent.run()
-
-```
-
-
-
-
-
-
-Output in Agentverse would be:
-
- ```
- WARNING: [Hosted]: No endpoints provided. Skipping registration: Agent won't be reachable.
- INFO: [Hosted]: Agent inspector available at https://agentverse.ai/inspect/?uri=http%3A//127.0.0.1%3A8000&address=agent1qv9h2wymp8l4vg2ezeszxkllz6lkmh9uhz7rvfyamy0wslhlaxh65fmemgt
- INFO: [Hosted]: Starting server on http://0.0.0.0:8000 (Press CTRL+C to quit)
- INFO: [Hosted]: My count is: 1
- INFO: [Hosted]: My global is: 1
- INFO: [Hosted]: My count is: 2
- INFO: [Hosted]: My global is: 2
- INFO: [Hosted]: My count is: 3
- INFO: [Hosted]: My global is: 3
- INFO: [Hosted]: My count is: 4
- INFO: [Hosted]: My global is: 4
- ```
-
-You can see from this output, **global is never updated**.
-
-To learn more about Agents storage and how it works in Agentverse, take a look at [Storage Functions ↗️](/guides/agents/intermediate/storage-function).
-
-
- Your hosted Agent requires periodic activity to remain active. To prevent automatic suspension, make sure to log in at least once every 30 days. If you don't, your agent may be paused or deactivated!
-
diff --git a/pages/guides/agents/intermediate/langchain-rag-agent.mdx b/pages/guides/agents/intermediate/langchain-rag-agent.mdx
deleted file mode 100644
index f1066cf37..000000000
--- a/pages/guides/agents/intermediate/langchain-rag-agent.mdx
+++ /dev/null
@@ -1,598 +0,0 @@
-import {Callout} from 'nextra/components'
-import PackageVersion from 'components/package-version'
-import { CodeGroup, CodeSegment, DocsCode, GithubCodeSegment } from "../../../../components/code";
-
-# Build a RAG Agent with uAgents and Langchain
-
-## Introduction
-
-In this guide, we'll walk through how to create [Agents ↗️](/guides/agents/getting-started/whats-an-agent) capable of answering questions based on any provided document using the Fetch.ai **uAgents** and **AI Engine** Python libraries as well as **OpenAI** and **Cohere**. The aim is to assist you in building a **LangChain Retrieval-Augmented Generation (RAG) Agent**!
-
-
- Also, rememeber that you can have a look and eventually download the source code used within this guide from Github [here ↗️](https://github.com/fetchai/uAgent-Examples/tree/main/1-uagents/docs_examples/intermediate/langchain-rag/src).
-
-
-The uAgents and AI Engine libraries offer a decentralized and modular framework for creating RAG Agents, improving the process of creating them. These tools streamline the integration of AI models like OpenAI and Cohere, enabling more efficient and scalable development of intelligent Agents. With enhanced interoperability, security, and resource management, this framework allows developers to quickly build and deploy sophisticated Agents that can effectively answer questions based on any provided document, making the entire process faster and more robust.
-
-
- Check out the [AI Engine package ↗️](https://pypi.org/project/uagents-ai-engine/) and [uAgents ↗️](https://pypi.org/project/uagents/) packages to download them and start integrating this tools within your Agents project!
-
- Current version of the AI Engine package is .
- Current version of the uAgents package is .
-
-
-**Let's dive into the LangChain RAG Agents development!**
-
-## Prerequisites
-
-Make sure you have read the following resources before going on with this guide:
-
- - [Creating an Agent ↗️](/guides/agents/create-a-uagent)
- - [Creating an interval task ↗️](/guides/agents/interval-task)
- - [Communicating with other Agents ↗️](/guides/agents/communicating-with-other-agents)
- - [Agent handlers ↗️](/guides/agents/intermediate/handlers)
- - [Almanac Contract ↗️](/references/contracts/uagents-almanac/almanac-overview)
- - [Register in Almanac ↗️](/guides/agents/register-in-almanac)
- - [Mailbox ↗️](/guides/agents/intermediate/mailbox)
- - [Utilising the Agentverse Mailroom service ↗️](/guides/agentverse/utilising-the-mailbox)
- - [Agents protocols ↗️](/guides/agents/intermediate/protocols)
- - [Agentverse Functions ↗️](/guides/agents/intermediate/agent-functions)
- - [Register an Agent Function on the Agentverse ↗️](/guides/agentverse/agentverse-functions/registering-agent-services)
-
-### LangChain and Cohere Overview
-
-#### LangChain
-
-In the context of a RAG agent, LangChain helps by:
-
-- **Document Loading and Parsing**: it processes and structures data from web pages.
-- **Vector Storage**: LangChain indexes documents into vectors, making it easier to perform similarity searches.
-- **Question Answering**: it generates answers by querying the indexed data, providing context-aware responses.
-
-#### Cohere
-
-Cohere offers **advanced NLP models** that assist in refining the answers generated by LangChain:
-
-- **Contextual Compression**: it filters and prioritizes data based on relevance, ensuring that the Agent focuses on the most important information.
-- **Enhanced Accuracy**: Cohere's NLP models improve the quality of the generated answers by understanding the context of the query more effectively.
-
-#### How These Work Together in a RAG Agent
-
-By combining **LangChain** for document retrieval and **Cohere** for NLP enhancement, this setup allows our Agents to process complex queries with context-aware responses, improving accuracy and user experience. LangChain handles the heavy lifting of document parsing and information retrieval, while Cohere fine-tunes the response to ensure high-quality, relevant answers.
-
-## API KEYs
-
-You will need **two API keys** to correctly go through this guide:
-
- 1. One from **OpenAI**
- 2. One from **Cohere**.
-
-Follow the steps provided below to obtain them:
-
-### OpenAI API Key
-
-1. Visit the [OpenAI website ↗️](https://openai.com/).
-2. Sign up or log in to your account.
-3. Navigate to the **API** section.
-4. Generate or retrieve your API key.
-
-### Cohere API Key
-
-1. Visit the [Cohere website ↗️](https://dashboard.cohere.com/).
-2. Sign up or log in to your account.
-3. Go to the **API Keys** section.
-4. Copy an existing key or create a new one.
-
-## Project structure and overview
-
-### Project structure
-
-The project is structured as follows:
-
- ```
- langchain-rag/
- .
- ├── poetry.lock
- ├── pyproject.toml
- └── src
- ├── agents
- │ ├── langchain_rag_agent.py
- │ └── langchain_rag_user.py
- ├── main.py
- └── messages
- └── requests.py
- ```
-
- The source code directory (`src`) contains the following directories and files:
-
- - `agents`: contains the scripts for the LangChain Agents.
- - `langchain_rag_agent.py`: it is the script for the RAG agent (retrieves info, finds documents, generates answers).
- - `langchain_rag_user.py`: Script for the User agent (asks questions, handles responses).
- - `main.py`: Starts both the RAG and user agents.
- - `messages`: Defines custom message models.
- - `requests.py`: Defines the RagRequest message model (question, URL, optional deep read).
-
-### Environment variables
-
-You'll need to set up environment variables for your project to run correctly. These variables include your API keys, which should be stored in a `.env` file within the `src` directory.
-
-To do this, navigate to the `src` directory. Here, create and source the `.env` file. Within this one, add the following:
-
- ```
- export COHERE_API_KEY="YOUR_COHERE_API_KEY"
- export OPENAI_API_KEY="YOUR_OPENAI_API_KEY"
- ```
-
-## Langchain RAG setup
-
-### Project dependencies
-
-You'll need several Python packages for the project. These can be managed efficiently using [Poetry ↗️](https://python-poetry.org/). The following dependencies are required for the correct development of the Langchain RAG Agent project:
-
- ```
- [tool.poetry.dependencies]
- python = ">=3.10,<3.12"
- uagents = "^0.17.1"
- requests = "^2.31.0"
- langchain = "^0.3.7"
- openai = "^1.54.5"
- langchain-openai = "^0.2.9"
- tiktoken = "^0.8.0"
- cohere = "^5.11.4"
- faiss-cpu = "^1.9.0.post1"
- validators = "^0.34.0"
- uagents-ai-engine = "^0.6.0"
- unstructured = "^0.16.5"
- langchain-community = "^0.3.7"
- ```
-
-## Messages Data Model
-
-### RagRequest Model
-
-We now need to define the `requests.py` file under the `messages` folder in the project:
-
-
-
- ```py copy filename="mac"
- touch requests.py
- ```
-
-
-
- ```py copy filename="windows"
- echo. > requests.py
- ```
-
-
-
- ```py copy filename="ubuntu"
- touch requests.py
- ```
-
-
-
-The script looks like the following:
-
-
-
-
-
-
-
- ```py copy filename="requests.py"
-
- from typing import Optional
- from uagents import Model, Field
-
-
- class RagRequest(Model):
- question: str = Field(
- description="The question that the user wants to have an answer for."
- )
- url: str = Field(description="The url of the docs where the answer is.")
- deep_read: Optional[str] = Field(
- description="Specifies weather all nested pages referenced from the starting URL should be read or not. The value should be yes or no.",
- default="no",
- )
-
-
-```
-
-
-
-
-
-
- Here's a breakdown of the `RagRequest` message data model:
-
- - `question (str)`: it is the user's question that needs to be answered based on the provided website URL.
- - `url (str)`: it is the URL of the website where the answer should be found.
- - `deep_read (Optional[str], default="no")`: this optional field allows you to specify whether the RAG Agent should follow and read nested pages (i.e., pages linked from the starting URL). Valid values are `"yes"` or `"no"`. By `default`, it is set to `"no"`, meaning that the Agent only will focus on the initial page linked to the URL.
-
-## Agents
-
-### LangChain RAG Agent
-
-This step involves setting up the **LangChain Retrieval-Augmented Generation (RAG) Agent** which can scrape web content, retrieve relevant documents, and generate answers to user queries based on the retrieved content.
-
-Let's start by creating the file within the `agents` directory, under `src` directory of our project, and name it `langchain_rag_agent.py` by using the following command:
-
-
-
- ```py copy filename="mac"
- touch langchain_rag_agent.py
- ```
-
-
-
- ```py copy filename="windows"
- echo. > langchain_rag_agent.py
- ```
-
-
-
- ```py copy filename="ubuntu"
- touch langchain_rag_agent.py
- ```
-
-
-
-The Agent is defined as a [local agent with a Mailbox ↗️](/guides/agents/intermediate/options-for-running-local-agents#run-a-local-agent-using-a-mailbox) and it can answer questions by fetching and summarizing information from a given website URL.
-
-The script for this Agent looks as follows:
-
-
-
-
-
-
-
- ```py copy filename="langchain_rag_agent.py"
- import traceback
- from uagents import Agent, Context, Protocol
- import validators
- from messages.requests import RagRequest
- import os
- from langchain_openai import ChatOpenAI
- from langchain.prompts import ChatPromptTemplate
- from langchain_community.document_loaders import UnstructuredURLLoader
- import requests
- from bs4 import BeautifulSoup
- from urllib.parse import urlparse
- from langchain_openai import OpenAIEmbeddings
- from langchain_community.vectorstores import FAISS
- from langchain.retrievers import ContextualCompressionRetriever
- from langchain.retrievers.document_compressors import CohereRerank
- from ai_engine import UAgentResponse, UAgentResponseType
- import nltk
- from uagents.setup import fund_agent_if_low
-
- nltk.download("punkt")
- nltk.download("averaged_perceptron_tagger")
-
- LANGCHAIN_RAG_SEED = "YOUR_LANGCHAIN_RAG_SEED"
-
- agent = Agent(
- name="langchain_rag_agent",
- seed=LANGCHAIN_RAG_SEED,
- mailbox=True,
- )
-
- fund_agent_if_low(agent.wallet.address())
-
- docs_bot_protocol = Protocol("DocsBot")
-
- PROMPT_TEMPLATE = """
- Answer the question based only on the following context:
-
- {context}
-
- ---
-
- Answer the question based on the above context: {question}
- """
-
-
- def create_retriever(
- ctx: Context, url: str, deep_read: bool
- ) -> ContextualCompressionRetriever:
- def scrape(site: str):
- if not validators.url(site):
- ctx.logger.info(f"Url {site} is not valid")
- return
-
- r = requests.get(site)
- soup = BeautifulSoup(r.text, "html.parser")
-
- parsed_url = urlparse(url)
- base_domain = parsed_url.scheme + "://" + parsed_url.netloc
-
- link_array = soup.find_all("a")
- for link in link_array:
- href: str = link.get("href", "")
- if len(href) == 0:
- continue
- current_site = f"{base_domain}{href}" if href.startswith("/") else href
- if (
- ".php" in current_site
- or "#" in current_site
- or not current_site.startswith(url)
- or current_site in urls
- ):
- continue
- urls.append(current_site)
- scrape(current_site)
-
- urls = [url]
- if deep_read:
- scrape(url)
- ctx.logger.info(f"After deep scraping - urls to parse: {urls}")
-
- try:
- loader = UnstructuredURLLoader(urls=urls)
- docs = loader.load_and_split()
- db = FAISS.from_documents(docs, OpenAIEmbeddings())
- compression_retriever = ContextualCompressionRetriever(
- base_compressor=CohereRerank(), base_retriever=db.as_retriever()
- )
- return compression_retriever
- except Exception as exc:
- ctx.logger.error(f"Error happened: {exc}")
- traceback.format_exception(exc)
-
-
- @docs_bot_protocol.on_message(model=RagRequest, replies={UAgentResponse})
- async def answer_question(ctx: Context, sender: str, msg: RagRequest):
- ctx.logger.info(f"Received message from {sender}, session: {ctx.session}")
- ctx.logger.info(
- f"input url: {msg.url}, question: {msg.question}, is deep scraping: {msg.deep_read}"
- )
-
- parsed_url = urlparse(msg.url)
- if not parsed_url.scheme or not parsed_url.netloc:
- ctx.logger.error("invalid input url")
- await ctx.send(
- sender,
- UAgentResponse(
- message="Input url is not valid",
- type=UAgentResponseType.FINAL,
- ),
- )
- return
- base_domain = parsed_url.scheme + "://" + parsed_url.netloc
- ctx.logger.info(f"Base domain: {base_domain}")
-
- retriever = create_retriever(ctx, url=msg.url, deep_read=msg.deep_read == "yes")
-
- compressed_docs = retriever.get_relevant_documents(msg.question)
- context_text = "\n\n---\n\n".join([doc.page_content for doc in compressed_docs])
- prompt_template = ChatPromptTemplate.from_template(PROMPT_TEMPLATE)
- prompt = prompt_template.format(context=context_text, question=msg.question)
-
- model = ChatOpenAI(model="gpt-4o-mini")
- response = model.predict(prompt)
- ctx.logger.info(f"Response: {response}")
- await ctx.send(
- sender, UAgentResponse(message=response, type=UAgentResponseType.FINAL)
- )
-
-
- agent.include(docs_bot_protocol, publish_manifest=True)
-
- if __name__ == "__main__":
- agent.run()
- ```
-
-
-
-
-
- The Agent fetches and processes information from specified URLs to answer users' questions.
-
- Let's explore the script above in more detail. We start by importing multiple modules, including tools for making HTTP requests, parsing HTML, and handling Natural Language Processing (NLP). The Agent uses **OpenAI's GPT-4o-mini model** to generate answers based on the retrieved documents. We then create an Agent called `langchain_rag_agent()` with a unique `seed`. Check out the [Mailbox ↗️](/guides/agents/intermediate/mailbox) guide for additional information on how to set up Mailboxes for your Agents. **Make sure to have enough funds in the Agent's wallet for it to correctly register in the [Almanac contract ↗️](/references/contracts/uagents-almanac/almanac-overview)**. You can use the `fund_agent_if_low` function on the testnet to add funds to your Agent's wallet if needed.
-
- Next, we define the `DocsBot` [protocol ↗️](/guides/agents/intermediate/protocols) using the `Protocol` class of the `uagents` library to handle message interactions. This protocol uses a predefined prompt template to structure the questions and context for the language model.
-
- The `create_retriever()` function is responsible for fetching and parsing web pages. If necessary, it can perform deep scraping, which involves gathering all linked pages within the same domain. The function validates URLs, retrieves HTML content, and uses `BeautifulSoup` to parse the HTML and find links. The documents are then loaded and split using LangChain's `UnstructuredURLLoader`, indexed with `FAISS`, and compressed with `Cohere`, creating a retriever that can extract relevant information.
-
- The `answer_question()` function, decorated with the `.on_message()` [handler ↗️](/guides/agents/intermediate/handlers), is triggered when the Agent receives a message matching the `RagRequest` message data model. The function validates the input URL and creates a retriever to fetch relevant documents based on the question. The context alongside with the question are then used to create a prompt for the language model (`ChatOpenAI`), which generates the final answer.
-
- The generated answer is then sent back to the user.
-
- Finally, the Agent is set to include the `DocsBot` protocol. We can then run the Agent's script; it will start the Agent and allow it to receive and process incoming messages.
-
- **To correctly run the code, you need to provide the `name`, `seed`, `mailbox`, `LANGCHAIN_RAG_SEED`, `PROMPT_TEMPLATE` and `AGENT_MAILBOX_KEY` parameters.**
-
-### LangChain User Agent
-
-We are now ready to define the **LangChain User Agent** which interacts with the LangChain RAG Agent we defined above to ask a question based on documents found at specified URLs. The user Agent request the RAG Agent to retrieve and process information from the web page and then to handle the response. The Agent is defined as a [local Agent with an endpoint ↗️](https://fetch.ai/docs/guides/agents/intermediate/options-for-running-local-agents#run-a-local-agent-with-an-endpoint).
-
-Create a file for this Agent:
-
-
-
- ```py copy filename="mac"
- touch langchain_rag_user.py
- ```
-
-
-
- ```py copy filename="windows"
- echo. > langchain_rag_user.py
- ```
-
-
-
- ```py copy filename="ubuntu"
- touch langchain_rag_user.py
- ```
-
-
-
-The script looks as follows:
-
-
-
-
-
-
-
- ```py copy filename="langchain_rag_user.py"
-
- from uagents import Agent, Context, Protocol
- from messages.requests import RagRequest
- from ai_engine import UAgentResponse
- from uagents.setup import fund_agent_if_low
-
-
- QUESTION = "How to install uagents using pip"
- URL = "https://fetch.ai/docs/guides/agents/installing-uagent"
- DEEP_READ = (
- "no"
- )
-
- RAG_AGENT_ADDRESS = "YOUR_LANGCHAIN_RAG_AGENT_ADDRESS"
-
- user = Agent(
- name="langchain_rag_user",
- port=8000,
- endpoint=["http://127.0.0.1:8000/submit"],
- )
- fund_agent_if_low(user.wallet.address())
- rag_user = Protocol("LangChain RAG user")
-
-
- @rag_user.on_interval(60, messages=RagRequest)
- async def ask_question(ctx: Context):
- ctx.logger.info(
- f"Asking RAG agent to answer {QUESTION} based on document located at {URL}, reading nested pages too: {DEEP_READ}"
- )
- await ctx.send(
- RAG_AGENT_ADDRESS, RagRequest(question=QUESTION, url=URL, deep_read=DEEP_READ)
- )
-
-
- @rag_user.on_message(model=UAgentResponse)
- async def handle_data(ctx: Context, sender: str, data: UAgentResponse):
- ctx.logger.info(f"Got response from RAG agent: {data.message}")
-
-
- user.include(rag_user)
-
- if __name__ == "__main__":
- rag_user.run()
-
-
-```
-
-
-
-
-
-
- Here, we create the User Agent which interacts with the LangChain RAG Agent we previously defined. The User Agent periodically asks the RAG Agent a predefined question and then handles the response.
-
- After importing all required modules and classes, a specific `QUESTION` is provided: `"How to install uagents using pip"`. We also provide the `URL` for the web page where the relevant information can be found to answer the question. The `DEEP_READ` variable is set to `no`; this indicates that the Agent should only read the main page.
-
- The `RAG_AGENT_ADDRESS` variable holds the address of the RAG Agent responsible of retrieving and processing the web page content to answer the user's question.
-
- We can then define the User Agent. We create the `langchain_rag_user` with a specific `port` and `endpoint`; this last one is essential to allow for communication with the RAG Agent. **Make sure your Agent has enough funds to register in the Almanac contract**. On the Testnet, you can use the `fund_agent_if_low()` function to fund your Agent's wallet if needed.
-
- We then proceed and define the [protocol ↗️](/references/uagents/uagents-protocols/agent-protocols). A protocol named `LangChain RAG user` is created using the `Protocol` class from the `uagents` library to handle the Agent's interactions. This protocol contains two important functions:
-
- 1. The `ask_question()` function, which is decorated with the `.on_interval()` [handler ↗️](/guides/agents/intermediate/handlers) and which is set to run at 60-second intervals. This function sends a `RagRequest` message to the LangChain RAG Agent, asking it to answer the `QUESTION` based on the specified `URL`. It then logs the `QUESTION` and `URL` details for debugging purposes.
-
- 2. The `handle_data()` function is decorated with the `.on_message()` handler and it handles incoming messages from the LangChain RAG Agent. When a response is received, it logs the response message.
-
- Finally, the LangChain RAG user protocol is included using the `.include()` method into the Agent which is then run by calling `rag_user.run()` in the main block.
-
- **Remember to provide the `QUESTION`, `URL`, `DEEP_READ`, `RAG_AGENT_ADDRESS`, `name`, `seed` and `endpoint` parameters to correctly run this code.**
-
-## Main script
-
-We are now ready to define the main script for our project. In the `src` folder of the project, we create a Python script named `main.py` using the following command:
-
-
-
- ```py copy filename="mac"
- touch main.py
- ```
-
-
-
- ```py copy filename="windows"
- echo. > main.py
- ```
-
-
-
- ```py copy filename="ubuntu"
- touch main.py
- ```
-
-
-
-We can now write the code for it.
-
-It will look as follows:
-
-
-
-
-
-
-
- ```py copy filename="main.py"
-
- from uagents import Bureau
- from agents.langchain_rag_agent import agent
- from agents.langchain_rag_user import user
-
-
- if __name__ == "__main__":
- bureau = Bureau(endpoint="http://127.0.0.1:8000/submit", port=8000)
- print(f"Adding RAG agent to Bureau: {agent.address}")
- bureau.add(agent)
- print(f"Adding user agent to Bureau: {user.address}")
- bureau.add(user)
- bureau.run()
-
-```
-
-
-
-
-
-
-Cool! All scripts are now set up! You will need to [connect the local Agent to the Agentverse using a Mailbox ↗️](/guides/agents/intermediate/options-for-running-local-agents#run-a-local-agent-using-a-mailbox). The Mailbox enables your Agents to be retrievable for communication and interaction with any other registered Agent on the Almanac contract and ASI Network. In this example, the `langchain_rag_agent` will be connected to the Agentverse using a [Mailbox ↗️](/guides/agents/intermediate/mailbox). The `langchain_rag_user` Agent is used as a testing Agent for the RAG Agent being registered on the Agentverse and made subsequently available on DeltaV for queries.
-
-By creating an [Agent Function ↗️](/guides/agents/intermediate/agent-functions) and [registering it ↗️](/guides/agentverse/agentverse-functions/registering-agent-services) via the Agentverse, you will make it retrievable to the [AI Engine ↗️](/concepts/ai-engine/ai-engine-intro) for interaction with users via natural language queries made on [DeltaV ↗️](/concepts/ai-engine/deltav).
-
-The `langchain_rag_user` Agent is used as a testing Agent for the RAG Agent being registered on the Agentverse and made subsequently available on DeltaV for queries.
-
-### Expected output
-
-The expected output for this example should be similar to the following one. Here, we questioned the **RAG Agent** with the question `How to install uagents using pip` from the **RAG User** Agent:
-
-
diff --git a/pages/guides/agents/intermediate/local-agent-inspector.mdx b/pages/guides/agents/intermediate/local-agent-inspector.mdx
deleted file mode 100644
index 122336d6f..000000000
--- a/pages/guides/agents/intermediate/local-agent-inspector.mdx
+++ /dev/null
@@ -1,91 +0,0 @@
-import { Callout } from 'nextra/components'
-import { CodeGroup, CodeSegment, DocsCode, GithubCodeSegment } from "../../../../components/code";
-
-# Local Agent Inspector
-
-The Local Agent Inspector is a developer tool on Agentverse designed to streamline debugging and monitoring for [Agents running on a local infrastructure ↗️](/guides/agents/intermediate/agent-types#local-agents). It helps developers track real-time Agents behavior, whether connected to Agentverse or not, offering detailed insights into performance and interactions.
-
-
- Local Agents can communicate and interact with other Agents and Functions connected to the Agentverse and ASI Network through a Mailbox. For more information on Mailbox and how to connect local Agents and their Functions to the Agentverse, have a look at these guides:
-
- - [Agent Mailbox ↗️](/guides/agents/intermediate/mailbox).
- - [Hosted, Local, and Mailbox Agents ↗️](/guides/agents/intermediate/agent-types).
- - [Options for running local Agents ↗️](/guides/agents/intermediate/options-for-running-local-agents)
- - [Agent Functions ↗️](/guides/agents/intermediate/agent-functions).
- - [Agentverse Functions: register your Agents Functions on the Agentverse! ↗️](/guides/agentverse/agentverse-functions/registering-agent-services).
-
-
-Developers can view key details such as the local Agent's address, endpoints, message types, and sender-recipient data. This visualization simplifies communication optimization and troubleshooting for Agents handling local processing or resource management.
-
-The Inspector displays message data in a list, with options to view payloads, and provides an overview of all running Agents. Future updates will include support for Bureau-managed Agents and direct connections to Agentverse, further enhancing management and monitoring capabilities.
-
-## How to access the Local Agent Inspector
-
-You can access the Local Agent Inspector by first coding and defining your Agent.
-
-For instance, consider the following simple local Agent:
-
-
-
-
-
-
-
- ```py copy filename="agent_inspector_example.py"
-
- 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()
-
-```
-
-
-
-
-
-
-Once you successfully run your local Agent and register it into the Almanac (**Make sure your Agent has enough funds to do so!**), you will be able to access the Inspector via the terminal log, which provides a dedicated link to the Inspector page.
-
-By running the above Agent, the output you get should be similar to the following:
-
- ```
- Your agent's address is: agent1qvrapvpxltu54tt3qnud5mlkul9y9d9tfn7xfpq4ec74cq4mkym6yl3jkdw
- INFO: [ Bob]: Registration on Almanac API successful
- INFO: [ Bob]: Registering on almanac contract...
- INFO: [ Bob]: Registering on almanac contract...complete
- INFO: [ Bob]: Agent inspector available at https://agentverse.ai/inspect/?uri=http%3A//127.0.0.1%3A8001&address=agent1q2kxet3vh0scsf0sm7y2erzz33cve6tv5uk63x64upw5g68kr0chkv7hw50
- INFO: [ Bob]: Starting server on http://0.0.0.0:8001 (Press CTRL+C to quit)
- ```
-
-By clicking on the dedicated link depicted here, you will then be redirected to the **Inspector Dashboard**. A pop-up message will appear saying that your Agent was connected successfully.
-
-
-
-Here you can view all the information about your local Agent, including details about all messages sent and received by the Agent. Additionally, you can connect you local Agent directly via the Inspector UI, by clicking the **Connect** button and following the steps required. For a better representation of the process, have a look at the following guide [here ↗️](/guides/agents/intermediate/mailbox)
diff --git a/pages/guides/agents/intermediate/mailbox.mdx b/pages/guides/agents/intermediate/mailbox.mdx
deleted file mode 100644
index 2d8d1e598..000000000
--- a/pages/guides/agents/intermediate/mailbox.mdx
+++ /dev/null
@@ -1,237 +0,0 @@
-import { Callout } from 'nextra/components'
-import { CodeGroup, CodeSegment, DocsCode, GithubCodeSegment } from "../../../../components/code";
-
-# Agent Mailboxes
-
-## Introduction
-
-Agents can't always be online; internet loss will cut your agent off from the network, or perhaps your agent is
-behind a firewall meaning you cannot accept inbound requests. To get around online requirements we created
-the **Mailbox** feature on [Agentverse ↗️](https://agentverse.ai). A Mailbox is a
-middleman that acts as a mailbox for all communication to your agent. Messages are stored within the mailbox and your
-agents will collect them (calls for these in [uAgents library ↗️](https://github.com/fetchai/uAgents/blob/55fd0f1bd14d4d5fdaaa3dae82e4d6c6c5b9a3cd/python/src/uagents/mailbox.py#L65)) when they're online
-again.
-
-Let's create a local Agent and connect it to the Agentverse via a Mailbox.
-
-## Prerequisites
-
-Make sure you have read the following resources before going on with this guide:
-
- - [Quick Start Guide for uAgents Framework ↗️](/guides/agents/quickstart)
- - [Creating your first agent ↗️](/guides/agents/getting-started/create-a-uagent)
- - [Agents address ↗️](/guides/agents/getting-started/getting-uagent-address)
- - [Agent Handlers ↗️](/guides/agents/intermediate/handlers)
- - [Almanac contract ↗️](/concepts/fetch-network/almanac)
- - [Register in Almanac ↗️](/guides/agents/register-in-almanac)
-
-## Imports needed
-
- - [uAgents ↗️](https://pypi.org/project/uagents/)
-
-## Local agent setup
-
-
-
-
-
-
-
- ```py copy filename="mailbox_agent.py"
-
- from uagents import Agent, Context, Model
-
-
- class Message(Model):
- message: str
-
-
- SEED_PHRASE = "put_your_seed_phrase_here"
-
- # Now your agent is ready to join the agentverse!
- agent = Agent(
- name="alice",
- seed=SEED_PHRASE,
- port=8000,
- mailbox=True
- )
-
- # Copy the address shown below
- print(f"Your agent's address is: {agent.address}")
-
- if __name__ == "__main__":
- agent.run()
- ```
-
-
-
-
-
-
-Importantly, you need to provide the `SEED_PHRASE`, `name`, `seed` and `port` parameters to correctly run this example. You also need to set `mailbox=True` to correctly connect your Agent to the Agentverse through the Mailbox.
-
-You should get something similar within your terminal output:
-
- ```
- INFO: [Alice]: Starting agent with address: agent1qw8jn3nfl2fyyhe7v4x8pfmsge4hs9zqrqw9eq7h7hluzmd0da8z7j0uacx
- INFO: [Alice]: Agent inspector available at https://agentverse.ai/inspect/?uri=http%3A//127.0.0.1%3A8002&address=agent1qw8jn3nfl2fyyhe7v4x8pfmsge4hs9zqrqw9eq7h7hluzmd0da8z7j0uacx
- INFO: [Alice]: Starting server on http://0.0.0.0:8002 (Press CTRL+C to quit)
- INFO: [Alice]: Starting mailbox client for https://agentverse.ai
- INFO: [Alice]: Mailbox access token acquired
- INFO: [Alice]: Registration on Almanac API successful
- INFO: [Alice]: Registering on almanac contract...
- INFO: [Alice]: Registering on almanac contract...complete
-
- ```
-
-## Create a Mailbox in Agentverse
-
-Now that we defined our local Agent and have successfully run it, we can go on and connect it to the [Agentverse ↗️](https://agentverse.ai) via a Mailbox. To do so, make sure your Agent is running. Then, click on the [Local Agent Inspector ↗️](/guides/agents/intermediate/local-agent-inspector) URL provided in your terminal output. You will be redirected towards the Inspector UI and will be able to see multiple details about this local Agent.
-
-Here, click the **Connect** button.
-
-
-
-You will be presented with 3 different choices: **Mailbox**, **Proxy** and **Custom**. Select **Mailbox**.
-
-
-
-You will then see some code details available for the Agent. You do not need to do anything, just click on **Finish**.
-
-
-
-
-
-You should now be able to see an additional line within your terminal output like shown below:
-
- ```
- INFO: [Alice]: Starting agent with address: agent1qw8jn3nfl2fyyhe7v4x8pfmsge4hs9zqrqw9eq7h7hluzmd0da8z7j0uacx
- INFO: [Alice]: Agent inspector available at https://agentverse.ai/inspect/?uri=http%3A//127.0.0.1%3A8002&address=agent1qw8jn3nfl2fyyhe7v4x8pfmsge4hs9zqrqw9eq7h7hluzmd0da8z7j0uacx
- INFO: [Alice]: Starting server on http://0.0.0.0:8002 (Press CTRL+C to quit)
- INFO: [Alice]: Starting mailbox client for https://agentverse.ai
- INFO: [Alice]: Mailbox access token acquired
- INFO: [Alice]: Registration on Almanac API successful
- INFO: [Alice]: Registering on almanac contract...
- INFO: [Alice]: Registering on almanac contract...complete
- INFO: [mailbox]: Successfully registered as mailbox agent in Agentverse
- ```
-
-You can view your recently connected local Agent by heading to the **Agentverse My Agents** tab and by clicking on **Local Agents**.
-You will see a box for the local Agent recently connected.
-
-
-
-Cool! You have correctly set up a mailbox for the Agent. You can additionally add some further details to the local Agent such as the `README.md` file. To do so, create a file in your local Agent folder and name it `README.md` (You can instead provide the path towards it if you wish). In the file, add all the needed details and save it. Then, add the following bits to your local Agent code:
-
- ```py copy
-
- agent = Agent(
- name="Alice",
- seed=SEED_PHRASE,
- port=8000,
- mailbox=True,
- readme_path="README.md",
- publish_agent_details=True
- )
-
- ```
-
-Then, run the Agent once again and head over to the Inspector UI and connect the Agent again through the Mailbox as we previously showed. Once you do so, you can the head over to the **Local Agents tab** under Agentverse My Agents page and click on the local Agent box. You should be able to see the `README.md` file opening up with the content you provided locally:
-
-
-
-## Creating a second Agent
-
-Let's create and run a second Agent to message Alice every 3 seconds. You need to provide the `ALICE_ADDRESS`, `name` and `seed` parameters to correctly run this code:
-
-
-
-
-
-
-
- ```py copy filename="test_agent.py"
-
- from uagents import Agent, Bureau, Context, Model
- from datetime import datetime
-
-
- class Message(Model):
- message: str
-
-
- agent_2 = Agent(name="agent_2", seed="agent_2 recovery phrase", port=8001, endpoint="http://localhost:8001/submit")
-
- ALICE_ADDRESS = "add_address_of_alice_agent"
-
-
- @agent_2.on_interval(period=3.0)
- async def send_message(ctx: Context):
- await ctx.send(ALICE_ADDRESS, Message(message=f"hello {datetime.today().date()}"))
-
-
- if __name__ == "__main__":
- agent_2.run()
-
-```
-
-
-
-
-
-
-## Testing
-
-With both `alice` and `agent_2` running, stop `alice` and let `agent_2` run for a further 20 seconds, or so.
-
-The output should be similar to the following, depending on the terminal window:
-
-- Alice:
-
- ```
- INFO: [Alice]: Starting agent with address: agent1qw8jn3nfl2fyyhe7v4x8pfmsge4hs9zqrqw9eq7h7hluzmd0da8z7j0uacx
- INFO: [Alice]: Agent inspector available at https://agentverse.ai/inspect/?uri=http%3A//127.0.0.1%3A8002&address=agent1qw8jn3nfl2fyyhe7v4x8pfmsge4hs9zqrqw9eq7h7hluzmd0da8z7j0uacx
- INFO: [Alice]: Starting server on http://0.0.0.0:8002 (Press CTRL+C to quit)
- INFO: [Alice]: Starting mailbox client for https://agentverse.ai
- INFO: [Alice]: Mailbox access token acquired
- INFO: [Alice]: Registration on Almanac API successful
- INFO: [Alice]: Registering on almanac contract...
- INFO: [Alice]: Registering on almanac contract...complete
- INFO: [mailbox]: Successfully registered as mailbox agent in Agentverse
- INFO: [Alice]: Received message from agent1qvzc3svtjv6dt9pql8ec7sfeuwfjmdg6ptafs9zc55ppvdwl5fe82j5m70v: hello 2024-12-18
- INFO: [Alice]: Sending message to bob
- INFO: [Alice]: Received message from agent1qvzc3svtjv6dt9pql8ec7sfeuwfjmdg6ptafs9zc55ppvdwl5fe82j5m70v: hello 2024-12-18
- INFO: [Alice]: Sending message to bob
- INFO: [Alice]: Received message from agent1qvzc3svtjv6dt9pql8ec7sfeuwfjmdg6ptafs9zc55ppvdwl5fe82j5m70v: hello 2024-12-18
- INFO: [Alice]: Sending message to bob
- ```
-
-- Agent 2:
-
- ```
- 2024-12-18 16:16:38 Info System Interval 0 period set to 5
- 2024-12-18 16:16:38 Debug System Envelope sent to agent1qw8jn3nfl2fyyhe7v4x8pfmsge4hs9zqrqw9eq7h7hluzmd0da8z7j0uacx
- 2024-12-18 16:16:40 Debug System Processing envelope from agent1qw8jn3nfl2fyyhe7v4x8pfmsge4hs9zqrqw9eq7h7hluzmd0da8z7j0uacx...
- ```
-
- **You can now restart your agent!**
-
-You will see a bunch of messages being displayed by `alice` which are sent by `agent_2`.
-
-
- Whenever working with mulitple local Agents, you need a different dedicated Mailbox for each one of them!
-
-
-Now your Agent doesn't need to be running all the time as messages will be waiting when it comes back online.
-
-**Great! You correctly enrolled your local Agent on the Agentverse using the Mailbox feature!**
diff --git a/pages/guides/agents/intermediate/options-for-running-local-agents.mdx b/pages/guides/agents/intermediate/options-for-running-local-agents.mdx
deleted file mode 100644
index 9851f5ec4..000000000
--- a/pages/guides/agents/intermediate/options-for-running-local-agents.mdx
+++ /dev/null
@@ -1,211 +0,0 @@
-import { Callout } from 'nextra/components'
-import PackageVersion from 'components/package-version'
-import { CodeGroup, CodeSegment, DocsCode, GithubCodeSegment } from "../../../../components/code";
-
-# Options for running your Agents
-
-## Run a local Agent with an endpoint
-
-In some scenarios, you may want to run an agent on your own hardware or infrastructure; luckily this is very easy to do on any system that supports **Python 3.10**.
-
-This system is pretty simple, as to get you started as quickly as possible. We're going to run this Agent on any device you'd like, in this scenario we're running on a VM, but you could run this on your laptop, raspberry pi or tweak for Agentverse. On startup our script will register our Agent to the [Almanac ↗️](/references/contracts/uagents-almanac/almanac-overview), and then our Agent will be available to communicate with other Agents.
-
-## Prerequisites
-
-Make sure you have read the following resources before going on with this guide:
-
- - [Quick Start Guide for uAgents Framework ↗️](/guides/agents/quickstart)
- - [Creating your first Agent ↗️](/guides/agents/getting-started/create-a-uagent)
- - [Agents address ↗️](/guides/agents/getting-started/getting-uagent-address)
- - [Almanac contract ↗️](/concepts/fetch-network/almanac)
- - [Register in Almanac ↗️](/guides/agents/register-in-almanac)
- - [Agents protocols ↗️](/guides/agents/intermediate/protocols)
- - [Exchange protocol ↗️](/references/uagents/uagents-protocols/exchange-protocol)
- - [Agent Functions ↗️](/guides/agents/intermediate/agent-functions)
- - [Agent Mailboxes ↗️](/guides/agents/intermediate/mailbox)
- - [Make your Agents AI Engine compatible ↗️](/guides/agents/intermediate/ai-engine-compatible-agent)
-
-## Imports needed
-
- - [uAgents ↗️](https://pypi.org/project/uagents/)
- - [AI Engine ↗️](https://pypi.org/project/uagents-ai-engine/)
-
-### The Agent
-
-Consider the following Agent:
-
-
-
-
-
-
-
- ```py copy filename="agent_endpoint.py"
-
- from uagents import Agent, Context, Protocol, Model
- import random
- from uagents import Field
- from ai_engine import UAgentResponse, UAgentResponseType
- import sys
-
- agent = Agent(
- name="dungeonsanddragonsdiceroll",
- port=6145,
- seed="RANDOM STRINGS",
- endpoint=["http://YOUR_IP:6145/submit"],
- )
-
-
- @agent.on_event("startup")
- async def hi(ctx: Context):
- ctx.logger.info(agent.address)
-
-
- class Request(Model):
- dice_sides: int = Field(description="How many sides does your dice need?")
-
-
- dice_roll_protocol = Protocol("DungeonsAndDragonsDiceRoll")
-
-
- @dice_roll_protocol.on_message(model=Request, replies={UAgentResponse})
- async def roll_dice(ctx: Context, sender: str, msg: Request):
- result = str(random.randint(1, msg.dice_sides))
- message = f"Dice roll result: {result}"
- await ctx.send(
- sender, UAgentResponse(message=message, type=UAgentResponseType.FINAL)
- )
-
-
- agent.include(dice_roll_protocol, publish_manifest=True)
-
- agent.run()
-
-```
-
-
-
-
-
-
-To correctly run this code, you must provide the `name`, `seed`, `port`, and `endpoint` parameters. Ensure the Agent has sufficient funds to register with the Almanac contract.
-
-The Agent must run on infrastructure that allows opening a `port`. In this example, we use port `6145` and an `endpoint`.
-
-The Agent is initialized with an endpoint and a port to receive messages and allow other Agents to communicate with it. The `protocol`, defined as an `int`, is specified in the `Request` object.
-
-The `on_message()` function processes incoming messages and returns a random number between 1 and the specified `dice_sides` from the message. The response must use the `UAgentResponse` type, which is essential for communication with [DeltaV ↗️](/concepts/ai-engine/deltav). Check out this guide [here ↗️](/guides/agents/intermediate/ai-engine-compatible-agent) to understand how to make your Agents AI Engine compatible.
-
-Finally, `.run()` starts the Agent.
-
-We can now run our Agent with the following command: `python agent_endpoint.py`
-
-**Expected output**:
-
- ```
- INFO: [dungeonsanddragonsdiceroll]: Manifest published successfully: DungeonsAndDragonsDiceRoll
- INFO: [dungeonsanddragonsdiceroll]: Registration on Almanac API successful
- INFO: [dungeonsanddragonsdiceroll]: Registering on almanac contract...
- INFO: [dungeonsanddragonsdiceroll]: Registering on almanac contract...complete
- INFO: [dungeonsanddragonsdiceroll]: Agent inspector available at https://agentverse.ai/inspect/?uri=http%3A//127.0.0.1%3A6145&address=agent1qvwk0ntr38yyghccrg530hnnm88r5uske4hdcalsa7gqp7sjgx42k4mp62r
- INFO: [dungeonsanddragonsdiceroll]: Starting server on http://0.0.0.0:6145 (Press CTRL+C to quit)
- ```
-
-
- Check out the [AI Engine package ↗️](https://pypi.org/project/uagents-ai-engine/) to download it and start integrating your Agents with this tool!
-
- Current version of the package is .
-
-
-## Run a local Agent using a Mailbox
-
-Through the **Agentverse** you can set up [Mailboxes ↗️](/guides/agents/intermediate/mailbox) for your local Agents, allowing them to communicate with other Agents registered on the ASI Network without the need to be constantly online and without requiring your constant presence to operate.
-
-### Local Agent setup
-
-Let's start by creating a local Agent named `alice` with a `handle_message()` function using an `@agent.on_message()` decorator to handle messages received by other Agents and matching the `Message` class:
-
-
-
-
-
-
-
- ```py copy filename="agent_mailbox.py"
-
- 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,
- port=8000,
- 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()
- ```
-
-
-
-
-
-
-To correctly run this code, you need to provide the `SEED_PHRASE`, `name`, `seed` and `mailbox` parameters.
-
-You can now connect your local Agent to the Agentverse using a **Mailbox**. To do so, run the local Agent and head over to the Inspector UI by clicking the dedicated link showing up within your terminal output.
-
-
-
-Then, click the **Connect** button and follow the steps required. Choose **Mailbox**:
-
-
-
-Move on until you reach the end. Once you finalize the steps required, you should be seeing something similar to the following in your terminal output:
-
- ```
- 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=agent1qfa53drat8rzau90u4494gx5mhj3v87tm4t5cuzkd7gkegxcm5vx5pku7kf
- 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]: Mailbox access token acquired
- INFO: [Alice]: Registration on Almanac API successful
- INFO: [Alice]: Registering on almanac contract...
- INFO: [Alice]: Registering on almanac contract...complete
- INFO: [mailbox]: Successfully registered as mailbox agent in Agentverse
- ```
-
-Now your Agent doesn't need to run all the time as their messages will be waiting for them for when they come back online!
-
-
- You can find additional information on the Agentverse Mailbox feature [here ↗️](/guides/agentverse/agentverse-mailbox/utilising-the-mailbox). This resource shows how to setup two Agents, one locally and one on the Agentverse, and make them establish a two-way communication line between both Agents sending a message to one another on an interval.
-
diff --git a/pages/guides/agents/intermediate/primary-secondary-functions.mdx b/pages/guides/agents/intermediate/primary-secondary-functions.mdx
deleted file mode 100644
index 25cffdf4b..000000000
--- a/pages/guides/agents/intermediate/primary-secondary-functions.mdx
+++ /dev/null
@@ -1,368 +0,0 @@
-import { Callout } from 'nextra/components'
-import PackageVersion from 'components/package-version'
-import { CodeGroup, CodeSegment, DocsCode, GithubCodeSegment } from "../../../../components/code";
-
-# Multi-file agent pipeline for AI Engine: Hugging face API to create a multi agent pipeline
-
-## Introduction
-
-It's time to build an example of secondary functions in use.
-
-The **Hugging Face Inference API** allows access to thousands of models for specific tasks. In this tutorial, we will integrate the Hugging Face API with the Agentverse Agent, enabling users to select their preferred **text-classification** model. Users can choose from the top downloaded models and make queries to them. This system consists of multiple layers of primary and secondary functions, with the Hugging Face system as the main objective and Hugging Face request and model list as secondary functions.
-
-For a better understanding of the workflow, please refer to the documentation below.
-
-## Prerequisites
-
-Make sure you have read the following resources before going on with this guide:
-
- - [Quick Start Guide for uAgents Framework ↗️](/guides/agents/quickstart)
- - [Creating your first Agent ↗️](/guides/agents/getting-started/create-a-uagent)
- - [Agents address ↗️](/guides/agents/getting-started/getting-uagent-address)
- - [Using Agents storage function ↗️](/guides/agents/intermediate/storage-function)
- - [Almanac contract ↗️](/concepts/fetch-network/almanac)
- - [Register in Almanac ↗️](/guides/agents/register-in-almanac)
- - [Agents protocols ↗️](/guides/agents/intermediate/protocols)
- - [Exchange protocol ↗️](/references/uagents/uagents-protocols/exchange-protocol)
- - [Agent Functions ↗️](/guides/agents/intermediate/agent-functions)
- - [Make your Agents AI Engine compatible ↗️](/guides/agents/intermediate/ai-engine-compatible-agent)
- - [Field descriptions for DeltaV ↗️](/guides/agentverse/agentverse-functions/field-descriptions-for-deltav)
-
-## Imports needed
-
- - [uAgents ↗️](https://pypi.org/project/uagents/)
- - [AI Engine ↗️](https://pypi.org/project/uagents-ai-engine/)
-
-## Hugging face Inference API
-
-Login to [Hugging Face ↗️](https://huggingface.co/settings/profile) and get your API key by logging in and going to account settings.
-
-Create news [access token ↗️](https://huggingface.co/settings/tokens) in settings for reading access type. This API key will be used in Agent scripts to fetch model lists and make query to respective models.
-
-## Setting up the agents
-
-For setting up Hugging Face function we need to create different Agents as listed below.
-
-### Hugging Face System Agent
-
-This Agent helps users with their queries for a text-classification model of their choosing. The agent always prioritizes Hugging Face request secondary function. Below is the script for creating our agent on [Agentverse ↗️](https://agentverse.ai/) using the **+New Agent** button.
-
-
-
-
-
-
-
- ```py copy filename="hugging_face_system_agent.py"
-
- # Here we demonstrate how we can create a hugging face system agent that is compatible with DeltaV.
-
- # After running this agent, it can be registered to DeltaV on Agentverse. For registration you will have to use the agent's address.
-
- # Importing required libraries
- import requests
- from ai_engine import UAgentResponse, UAgentResponseType
-
-
- # Define a model class for the Hugging Face agent's expected message format
- class HF(Model):
- response: str # This class has a single attribute 'response' that holds the string response from the subtask.
-
-
- # Create a protocol for the Hugging Face (HF) agent, specifying its interactions_and_interval_task protocol
- hf_protocol = Protocol("Hugging Face")
-
-
- # Define a handler for the Hugging face protocol
- @hf_protocol.on_message(model=HF, replies=UAgentResponse)
- async def on_hf_request(ctx: Context, sender: str, msg: HF):
- # Log the receipt of a response, including the sender and the message prompt
- ctx.logger.info(f"Received hugging face request from {sender} with prompt: {msg.response}")
-
- # Format a response message incorporating the received message
- message = f'Response to your query from model is \n {msg.response}'
- # Asynchronously send a response back to the sender with the processed message
- await ctx.send(sender, UAgentResponse(message=message, type=UAgentResponseType.FINAL))
-
-
- # Include the Hugging Face protocol in your agent
- agent.include(hf_protocol)
-
-```
-
-
-
-
-
-
-Within the above code snippet, we defined an Agent which is able to handle specific message types and respond to them accordingly. First, the `requests` library and classes from `ai_engine` are imported to manage Agent responses. The `HF` model class is then defined, with a single attribute response that stores the response string expected from Hugging Face.
-
-A `Protocol` instance, `hf_protocol`, is created, representing the communication protocol for the Hugging Face Agent. Within this protocol, a message handler `on_hf_request` is set up to respond to messages that match the `HF` model format. This handler is triggered asynchronously on receiving a message, logging details about the sender and the prompt provided. The handler formats a response by embedding the received message content into a reply and sends it back to the sender. Finally, the `hf_protocol` protocol is included in the Agent.
-
-After creating and running this Agent, it can be registered to DeltaV on Agentverse using its unique address.
-
-### Hugging Face Request Agent
-
-This Agent helps Hugging Face system to handle hugging face request to user and calculates the response. The Agent has two fields, i.e. `model_id` (towards which the query has to be made) and `query` (question needed to be asked to the model). For `model_id` this task always prioritizes `Model List` secondary function to get list of available model of a specific type.
-
-
-
-
-
-
-
- ```py copy filename="hugging_face_request_agent.py"
-
- # Here we demonstrate how we can create a hugging face request agent that is compatible with DeltaV.
-
- # After running this agent, it can be registered to DeltaV on Agentverse Services tab. For registration you will have to use the agent's address.
-
- # Importing required libraries.
- import requests
- import json
- from ai_engine import UAgentResponse, UAgentResponseType
-
-
- # Define a model class for the Hugging Face Request agent's expected message format.
- class Search(Model):
- model_id: str
- query: str
-
-
- # Define a function to handle query from user using model_id and query provided by user.
- async def handle_query(model_id, query):
- Model_ID = model_id
- API_URL = f'https://api-inference.huggingface.co/models/{Model_ID}' # hugging face url
- API_TOKEN = 'YOUR TOKEN HERE' # hugging face API token
-
- headers = {"Authorization": f"Bearer {API_TOKEN}"}
-
- # Make request to hugging face API with model_id and query.
- response = requests.post(API_URL, headers=headers, json=query).json()
- return response
-
-
- # Create a protocol for the Hugging Face Request(HF) agent, specifying its interactions_and_interval_task protocol.
- hfprotocol = Protocol(name='Hugging Face protocol')
-
-
- # Define a handler for the Hugging face request protocol.
- @hfprotocol.on_message(model=Search, replies=UAgentResponse)
- async def handle_message(ctx: Context, sender: str, msg: Search):
- # Log the model_id and query provided by user.
- ctx.logger.info(f'Message sent from {sender} : {msg.model_id}')
- ctx.logger.info(f'Message sent from subtask : {msg.query}')
-
- # Calling handle_query function to get response from API.
- response = await handle_query(msg.model_id, msg.query)
- # sending response to hugging face agent
- await ctx.send(sender, UAgentResponse(message=str(response), type=UAgentResponseType.FINAL))
-
-
- # Include the Hugging Face protocol in your agent.
- agent.include(hfprotocol, publish_manifest=True)
-
-```
-
-
-
-
-
-
-Within this code snippet, we create a Hugging Face request Agent that can interact with DeltaV and which can be registered on the Agentverse using the Agent's address. The code first imports the necessary libraries:
-
- - `requests` for handling HTTP requests;
- - `json` for data handling;
- - `UAgentResponse` and `UAgentResponseType` from `ai_engine` to make Agents AI Engine compatible.
-
-The `Search` model class is then defined to represent the expected message format, containing two fields: `model_id`, which specifies the Hugging Face model, and `query`, which represents the user’s request.
-
-The function `handle_query` is then created to make an API call to the Hugging Face model specified by `model_id` using the user's query. This function builds the API endpoint URL, authenticates with an API token (`API_TOKEN`), and sends the query as a JSON object. The function returns the JSON response from Hugging Face.
-
-Next, a protocol `hfprotocol` is created to define the interactions for the Hugging Face request Agent. The handler `handle_message` is associated with this protocol and is triggered whenever a message of type `Search` is received. This handler logs the `model_id` and query details for reference, calls `handle_query` to retrieve the API response, and then sends the formatted response back to the original sender.
-
-Finally, `hfprotocol` is included in the Agent, with the option `publish_manifest=True` to make this protocol available for registration and use in DeltaV.
-
-Remember that you need to provide the `API_URL` and `API_TOKEN` parameters in order to correctly run this code.
-
-### Model List Agent
-
-This agent helps user to look for specific model with search keyword. The Agent queries Hugging Face URL to get top 5 downloaded model related to search keyword. The Agent returns list of models and users can select the one they need.
-
-
-
-
-
-
-
- ```py copy filename="model_list_agent.py"
-
- # Here we demonstrate how we can create a model list agent that is compatible with DeltaV
-
- # After running this agent, it can be registered to DeltaV on Agentverse Services tab. For registration you will have to use the agent's address
-
- # Importing required libraries
- import requests
- from ai_engine import UAgentResponse, UAgentResponseType
- import json
-
-
- # Define a model class for the Model List agent's expected message format
- class Search(Model):
- search: str # This is a keyword for which user wants to search model
-
-
- # Create a protocol for the Model List agent, specifying its interactions_and_interval_task protocol
- model_list_protocol = Protocol(name='Model List protocol')
-
-
- # Define a function to handle query from user using search keyword provided by user
- async def handle_query(search):
- url = "https://huggingface.co/api/models"
-
- params = {
- "search": search,
- "filter": "text-classification",
- "sort": "downloads",
- "direction": -1,
- "limit": 5
- } # Search parameters.
-
- models = [] # List of models.
-
- # Make the GET request
- response = requests.get(url, params=params)
-
- # Append models in list
- for model in response.json():
- models.append(model['id'])
-
- return models
-
-
- # Define a handler for the Model list protocol
- @model_list_protocol.on_message(model=Search, replies=UAgentResponse)
- async def handle_message(ctx: Context, sender: str, msg: Search):
- # Log search keyword provided by user.
- ctx.logger.info(f'Message sent from {sender} : {msg.search}')
-
- # Call handle_query to get list of models
- options = handle_query(msg.search)
- # Log model list responded by hugging face request
- ctx.logger.info(f'Message sent from {sender} : {options}')
-
- # Format options in dictionary format to provide options to user
- formatted_options = [{'key': i + 1, 'value': value} for i, value in enumerate(options)]
-
- # Send message to the user
- await ctx.send(sender, UAgentResponse(message=str(formatted_options), type=UAgentResponseType.FINAL))
-
-
- # Include model_list protocol in agent
- agent.include(model_list_protocol, publish_manifest=True)
-
-```
-
-
-
-
-
-
-In the above, we defined a Model List Agent compatible with DeltaV, which, after being run, can be registered on Agentverse using the Agent's address.
-
-We begin by importing the necessary libraries:
-
- - `requests` for making HTTP requests;
- - `UAgentResponse` and `UAgentResponseType` from `ai_engine` to make Agents AI Engine compatible.
-
-The `Search` model class is defined to represent the message format expected by this Agent, containing a single attribute, `search`, which holds the user's keyword for model search.
-
-Next, we defined the function `handle_query` which is created to query the Hugging Face API for models related to the user's search keyword. The API endpoint `"https://huggingface.co/api/models"` is called with parameters specifying that models should be filtered for `"text-classification"`, sorted by download count, and limited to 5 results. The function collects and returns a list of model IDs from the JSON response.
-
-A protocol `model_list_protocol` is then defined to handle interactions for this Agent. Within it, the message handler `handle_message` is set up to process incoming messages of type `Search`. This handler logs the user-provided search keyword, calls `handle_query` to retrieve a list of matching models, and logs this list. It then formats the list into a structured dictionary of options, where each model ID is associated with a numbered key, and sends this formatted response back to the sender.
-
-Finally, `model_list_protocol` is included in the Agent with `publish_manifest=True`, making the protocol accessible for DeltaV registration.
-
-## Setting up functions
-
-Go to [Agentverse ↗️](https://agentverse.ai/) and create new function for all three Agents created [above ↗️](/guides/agents/intermediate/primary-secondary-functions#setting-up-the-agents).
-
-The properties of function for each Agent are listed below.
-
-### Hugging Face System
-
-
-
- - **Function title**: just the name of your function - in this example let's call it **Hugging Face System**.
- - **Description**: super important to be as detailed as you can, as reasoning AI Engine looks at descriptions to understand what your function does - in this example we can specify something like this: _This function helps user to give any query to the selected model and gets the response to their query. Always go for hugging face request secondary function for this objective._
- _Secondary function chronology:_
- _Hugging face system -> Hugging face request -> Model List_
- - **Application**: Primary function.
- - **Protocol** and **Data Model** will be automatically populated based on the source code of [Hugging face system agent ↗️](/guides/agents/intermediate/primary-secondary-functions#setting-up-the-agents).
- - **Field descriptions**: This field is super important to be detailed and is responsible for triggering secondary function. - in this example we can specify something like: _Describes the response to the user query. Always go for Hugging face request secondary function to get this field. Never ask this from user_.
-
-### Hugging Face Request
-
-
-
- - **Function title**: just the name of your function - in this example let's call it **Hugging Face Request**.
- - **Description**: super important to be as detailed as you can, as reasoning AI Engine looks at descriptions to understand what your function does - in this example we can specify something like this: _This function handles the request to help user ask question to a selected model from hugging face. Model_id is always given by Model Lists secondary function_.
- - **Application**: Secondary function.
- - **Protocol** and **Data Model** will be automatically populated based on the source code of [Hugging face system agent ↗️](/guides/agents/intermediate/primary-secondary-functions#hugging-face-request-agent).
- - **Field descriptions**: this field is super important to be detailed and is responsible for triggering secondary functions. In this example we can specify something like:
- - **Model_id**: _Always go for model list secondary function. Never ask this field to user._
- - **query**: _Describes the query user wants to ask to the model Always ask this to user after model_id is given by model list secondary function._
-
-### Model List
-
-
-
- - **Function title**: just the name of your function - in this example let's call it **Model List**.
- - **Description**: super important to be as detailed as you can, as reasoning AI Engine looks at descriptions to understand what your function does - in this example we can specify something like this: _This function helps user to select from different model options available. This always gives list of options to the user. make user select one from these options. Present list of strings as select from option._
- - **Application**: Secondary function.
- - **Protocol** and **Data Model** will be automatically populated based on the source code of [Hugging face system agent ↗️](/guides/agents/intermediate/primary-secondary-functions#model-list-agent)
- - **Field descriptions**: this field is super important to be detailed and is responsible for triggering secondary function. In this example we can specify something like: _This is the search keyword of model user wants to ask answer to. Always ask this to user. This always gives list of options to the user. make user select one from these options._
-
-## Let's find our Function on DeltaV
-
-Now, head to [DeltaV ↗️](https://deltav.agentverse.ai/) and sign in.
-
-Type in **Hugging Face System** and click on `Advanced options`. Select `All Function Groups` and click on `Start` button.
-
-
- Whenever operating on DeltaV, we encourage everyone to select the **Next Generation AI Engine** personality type. This AI Engine personality stands as a significant AI Engine personality type offering _enhanced scalability_, _reliability_, and _flexibility_. The major key features include advanced context understanding, improved function recommendations, and the ability to handle multiple dialogue formats.
-
-
-
-
-Select **Hugging Face System** from options provided by DeltaV and it will initiate Hugging Face Request secondary function.
-Hugging Face secondary function will initiate Model Lists secondary function and ask for **Search keyword** for which you want to search the models for.
-
-
-
-
-
-In this case we will ask for sentiment analysis model. **Model lists** will give us options from top 5 downloaded models and we need to select one option. Hugging face request will ask us for the query and we want to ask to model and send the response to hugging face system.
-
-
-
-After your function has been executed you can see the `Agent Response` message.
-
-
-
-With that, **you have got a hugging face function which can be discovered and contacted with DeltaV. Awesome!**
diff --git a/pages/guides/agents/intermediate/protocols.mdx b/pages/guides/agents/intermediate/protocols.mdx
deleted file mode 100644
index 64e51a517..000000000
--- a/pages/guides/agents/intermediate/protocols.mdx
+++ /dev/null
@@ -1,81 +0,0 @@
-import { Callout } from 'nextra/components'
-import { CodeGroup, DocsCode } from "../../../../components/code";
-
-# Agents protocols
-
-Within the uAgents Framework, `protocols` represent message types and handlers. Protocols are used to facilitate communication and interaction between agents in the Framework.
-
-A `protocol` is built similar to an agent, but it has no identity and cannot be run. Protocols only contains the message types and handlers that define some components of an agent's functionality.
-
-Let's use a _simple restaurant table booking request_ as an example to better understand what a protocol means and how to build one:
-
-1. Let's start by creating a folder for our **protocols**. Then, let's create Python script within it, and name it:
-
- `mkdir protocols`
-
- and
-
-
-
- ```py copy filename="mac"
- touch book.py
- ```
-
-
-
- ```py copy filename="windows"
- echo. > book.py
- ```
-
-
-
- ```py copy filename="ubuntu"
- touch book.py
- ```
-
-
-
-2. We import from `uagents` library the necessary classes `Context`, `Model`, and `Protocol`. Then, need to define the type of messages that the handler will receive and send:
-
- ```py copy
- from uagents import Context, Model, Protocol
-
- class BookTableRequest(Model):
- table_number: int
-
- class BookTableResponse(Model):
- success: bool
- ```
-
- We use the `Model` class from `uagents` library to define `BookTableRequest` and `BookTableResponse` classes for setting up the structure of messages to be exchanged between your agents. The `BookTableRequest` class represents a request to book a table, containing the desired table number, while the `BookTableResponse` class represents the response to that request, indicating whether the booking was successful.
-
-3. Now, we would need to define the booking protocol as `book_proto` and also define the desired logic to determine if the `BookTableResponse` will be successful or not:
-
- ```py copy
- book_proto = Protocol()
-
- @book_proto.on_message(model=BookTableRequest, replies={BookTableResponse})
- async def handle_book_request(ctx: Context, sender: str, msg: BookTableRequest):
- if ctx.storage.has(str(msg.table_number)):
- success = False
- else:
- success = True
- ctx.storage.set(str(msg.table_number), sender)
-
- # send the response
- await ctx.send(sender, BookTableResponse(success=success))
- ```
-
-4. We can then import our booking protocol from into the script we create for our agent, in the following way:
-
- ```py copy
- from protocols.book import book_proto
- ```
-
-5. If your agent is called `restaurant` you can include the protocol in this way:
-
- ```py copy
- restaurant.include(book_proto)
- ```
-
-For a better understanding of these concepts, consider having a look at the [Agents storage ↗️](/references/uagents/uagents-protocols/storage) and [Exchange protocol ↗️](/references/uagents/uagents-protocols/exchange-protocol) resources and consider going through the extensive [How to book a table at a restaurant using agents ↗️](/examples/table-booking-demo) guide in the [Agents guides ↗️](/guides#ai-agents) section. Also, check out the [Agents: broadcast ↗️](/examples/broadcast) guide for an additional implementation of protocols in Agents communication.
diff --git a/pages/guides/agents/intermediate/public-private-agents.mdx b/pages/guides/agents/intermediate/public-private-agents.mdx
deleted file mode 100644
index 0fe8548c8..000000000
--- a/pages/guides/agents/intermediate/public-private-agents.mdx
+++ /dev/null
@@ -1,50 +0,0 @@
-import { Callout } from 'nextra/components'
-import { ImageByTheme } from "components/mdx"
-import PublicAndPrivateAgents from 'src/images/concepts/ai-agents/public_and_private_agents.png'
-import DarkPublicAndPrivateAgents from 'src/images/concepts/ai-agents/dark_public_and_private_agents.svg'
-
-# Public and private agents
-
-## Introduction
-
-Transparency is a fundamental principle in Decentralized Finance (DeFi) and blockchain systems. Within the Fetch.ai network, **users have the ability to determine the amount of information they wish to publish**. This is thanks to the ability for users to create Agents as either **public** or **private**, based on their **introspectivity** and **protocol exposure** through the [Agentverse ↗️](/concepts/agent-services/agentverse-intro).
-
-
-
-This allows users to provide greater flexibility to Agents, creating a balance between transparency and privacy for every operation they perform on the network.
-
-## Defining public and private agents
-
-There are two ways in which an Agent can be classified as public: they define an endpoint and/or, they publish their manifests:
-
- ```python
-
- agent = Agent(
- name="demo agent",
- seed=SEED,
- endpoint=["http://127.0.0.1:8000/submit"],
- )
- agent.include(new_protocol, publish_manifest=True)
- agent.run()
-
- ```
-
-Private Agents can be private in two ways: by hiding a protocol they use from public and/or by not defining an endpoint:
-
- ```python
-
- agent = Agent(
- name="private demo agent",
- seed=SEED,
- )
- agent.include(new_protocol, publish_manifest=False)
- agent.run()
-
- ```
-
-You would need to share the IP of the private Agent you're running to the other Agent you're communicating with.
-
diff --git a/pages/guides/agents/intermediate/rest-endpoints.mdx b/pages/guides/agents/intermediate/rest-endpoints.mdx
deleted file mode 100644
index 029dd8b48..000000000
--- a/pages/guides/agents/intermediate/rest-endpoints.mdx
+++ /dev/null
@@ -1,151 +0,0 @@
-import {Callout} from 'nextra/components'
-import { CodeGroup, CodeSegment, DocsCode, GithubCodeSegment } from "../../../../components/code";
-
-# How to add custom REST endpoints to your Agent
-
-## Introduction
-uAgents now support custom REST endpoints using the `on_rest_get()` and `on_rest_post()` decorators, enabling them to handle HTTP GET and POST requests directly. With this addition, agents can define specific routes, create request and response models, and interact seamlessly with REST clients. This feature enhances the flexibility of agents, allowing them to communicate with external systems using standard web protocols while ensuring that all responses conform to predefined models.
-
-Let's get started!
-
-## Prerequisites
-
-Make sure you have read the following resources before going on with this guide:
-
- - [Quick Start Guide for uAgents Framework ↗️](/guides/agents/quickstart)
- - [Creating your first agent ↗️](/guides/agents/getting-started/create-a-uagent)
- - [Agent Handlers ↗️](/guides/agents/intermediate/handlers)
- - [Almanac contract ↗️](/concepts/fetch-network/almanac)
- - [Register in Almanac ↗️](/guides/agents/register-in-almanac)
- - [Agents protocols ↗️](/guides/agents/intermediate/protocols)
- - [Exchange protocol ↗️](/references/uagents/uagents-protocols/exchange-protocol)
- - [Options for running your Agents ↗️](/guides/agents/intermediate/options-for-running-local-agents)
-
-
- Please note that this feature is only available at the 'agent level', meaning that you cannot add REST endpoints to uAgents protocols.
-
-
-## Usage
-
-To use the new REST API feature in your agent, follow these steps to define custom `GET` and `POST` routes, run the agent, and query the endpoints.
-
-### Define Custom GET and POST Routes
-
-#### GET Endpoint
-
-Use the `@on_rest_get()` decorator to define a custom GET endpoint. You will need to specify the endpoint route and the response model.
-
-```py copy
-@agent.on_rest_get("/custom_get_route", Response)
-async def handle_get(ctx: Context) -> Dict[str, Any]:
- return {
- "field": ,
- }
-
-```
-
-#### POST Endpoint
-
-Use the `@on_rest_post()` decorator to define a custom POST endpoint. You need to provide both a request model (for input) and a response model (for output).
-
- ```py copy
- @agent.on_rest_post("/custom_post_route", Request, Response)
- async def handle_post(ctx: Context, req: Request) -> Response:
- ctx.logger.info(req)
- return Response(...)
- ```
-
-
- For querying the agent you have to make sure that:
-
- - You use the correct REST method ("GET" or "POST")
- - You address the agent endpoint together with its route e.g `http://localhost:8000/custom_route`
-
-
-### Example of custom GET and POST Routes
-
-
-
-
-
-
-
- ```py copy filename="agent.py"
-
- import time
- from typing import Any, Dict
-
- from uagents import Agent, Context, Model
-
- class Request(Model):
- text: str
-
- class Response(Model):
- timestamp: int
- text: str
- agent_address: str
-
- # You can also use empty models to represent empty request/response bodies
- class EmptyMessage(Model):
- pass
-
- agent = Agent(name="Rest API", seed="your_seed_phrase", port=8000, endpoint=["http://localhost:8000/submit"])
-
- @agent.on_rest_get("/rest/get", Response)
- async def handle_get(ctx: Context) -> Dict[str, Any]:
- ctx.logger.info("Received GET request")
- return {
- "timestamp": int(time.time()),
- "text": "Hello from the GET handler!",
- "agent_address": ctx.agent.address,
- }
-
- @agent.on_rest_post("/rest/post", Request, Response)
- async def handle_post(ctx: Context, req: Request) -> Response:
- ctx.logger.info("Received POST request")
- return Response(
- text=f"Received: {req.text}",
- agent_address=ctx.agent.address,
- timestamp=int(time.time()),
- )
-
- if __name__ == "__main__":
- agent.run()
-
-```
-
-
-
-
-
-
-## Run the example
-
-1. Run the agent: `python agent.py`
-2. Query the agent directly through your predefined interfaces:
-
- ```bash
- curl -d '{"text": "test"}' -H "Content-Type: application/json" -X POST http://localhost:8000/rest/post
- ```
-
-### Expected output
-
-- Curl Response:
-
- ```
- {"timestamp": 1725610956, "text": "Received: test", "agent_address": "agent1q2qavahvzm2yw237g2cq40pe8p590ppysclaffp2dd0gtk9evtxag7c8djd"}
- ```
-
-- Agent Logs:
-
- ```
- WARNING: [Rest API]: No endpoints provided. Skipping registration: Agent won't be reachable.
- INFO: [Rest API]: Starting server on http://0.0.0.0:8000 (Press CTRL+C to quit)
- INFO: [Rest API]: Received POST request
- ```
-
diff --git a/pages/guides/agents/intermediate/search-agent.mdx b/pages/guides/agents/intermediate/search-agent.mdx
deleted file mode 100644
index bbc7c2441..000000000
--- a/pages/guides/agents/intermediate/search-agent.mdx
+++ /dev/null
@@ -1,240 +0,0 @@
-import { Callout } from 'nextra/components'
-
-# Fetch.ai SDK Guide: Search Agent
-
-
-This is currently a work in progress and may be subject to further updates and revisions.
-
-
-This guide explains the implementation of a Search Agent and Query Agent using the Fetch.ai SDK. These Agents work together to handle user queries, search the Fetch.ai network for relevant Agents, and return results.
-
-Below, we outline the **Search Function** and the **Complete Agent Implementation** in details.
-
-## Installation
-
-Once you successfully have Python installed, you can start setting up your environment.
-
-Create a new folder; call it `fetchai-search-agent`:
-
- ```
- mkdir fetchai-search-agent && cd fetchai-search-agent
- ```
-
-Then, install the required libraries:
-
- ```
- pip install uagents fetchai openai
- ```
-
-## Search Function
-
-The Search Function is the core of the Search Agent. It interacts with the Fetch.ai network to find Agents matching a specific query and sends them a message.
-
-Here's how it works:
-
-### Functionalities
-
-- **Search the Fetch.ai Network**: The `fetch.ai(query)` method searches for Agents that match the user's query.
-
-- **Set Sender Identity**: Each message is sent using a unique sender identity generated by `Identity.from_seed`.
-
-- **Dynamic Payload**: Uses OpenAI's GPT to generate payload based on the query.
-
-- **Send Messages**: For every matching Agent, a payload is constructed and sent using the `send_message_to_agent` function.
-
-```py copy
-from fetchai import fetch
-from fetchai.crypto import Identity
-from fetchai.communication import send_message_to_agent
-from uuid import uuid4
-
-def search(query):
- # Search for agents matching the query
- available_ais = fetch.ai(query)
-
- # Create sender identity for communication
- sender_identity = Identity.from_seed("search_sender_identity", 0)
-
- for ai in available_ais.get('ais'): # Iterate through discovered agents
-
- prompt = f"""
- you will take the following information: query={query}.
- You must return a results according to the query"""
-
- completion = client.chat.completions.create(
- model="gpt-4o",
- messages=[
- {"role": "user", "content": prompt}
- ]
- )
-
- payload = {
- "Response": completion.choices[0].message.content
- }
-
- other_addr = ai.get("address", "") # Get agent's address
- print(f"Sending a message to an AI agent at address: {other_addr}")
-
- # Send the payload to the discovered agent
- send_message_to_agent(
- sender=sender_identity,
- target=other_addr,
- payload=payload,
- session=uuid4(),
- )
-
- return {"status": "Agent searched"}
-```
-
-## Complete Agent Implementation
-
-The implementation involves two Agents: **Query Agent** and **Search Agent**, which interact with each other as follows:
-
-### Query Agent
-
-- It sends the user's query to the Search Agent on startup.
-- it then waits for a response from the Search Agent.
-
- ```py
- query_agent = Agent(name="query_agent", seed="query_agent recovery phrase")
- ```
-
-### Search Agent
-
--Receives the query, processes it using the `search()` function, and sends a response back to the Query Agent.
-
- ```py
- search_agent = Agent(name="search_agent", seed="search_agent recovery phrase")
- ```
-
-## Overall script
-
-```py copy filename="fetchai-search-agent.py"
-from fetchai import fetch
-from fetchai.crypto import Identity
-from fetchai.communication import (
- send_message_to_agent
-)
-
-from openai import OpenAI
-
-client = OpenAI()
-
-from uuid import uuid4
-from uagents import Agent, Bureau, Context, Model
-
-class Query(Model):
- message: str
-
-class Response(Model):
- status: str
-
-def search(query):
- available_ais = fetch.ai(query)
- sender_identity = Identity.from_seed("whatever i want this to be, but i am searching", 0)
- print(f"[results] available ais : {available_ais} ")
- for ai in available_ais.get('ais'):
-
- prompt = f"""
- you will take the following information: query={query}.
- You must return a results according to the query"""
-
- completion = client.chat.completions.create(
- model="gpt-4o",
- messages=[
- {"role": "user", "content": prompt}
- ]
- )
-
- payload = {
- "Response": completion.choices[0].message.content
- }
-
- other_addr = ai.get("address", "")
-
- print(f"[INFO] Sending message to AI at address: {other_addr}")
-
- send_message_to_agent(
- sender=sender_identity,
- target=ai.get("address", ""),
- payload=payload,
- session=uuid4()
- )
-
- return {"status": "Agent searched"}
-
-query_agent = Agent(name="query_agent", seed="query_agent recovery phrase")
-search_agent = Agent(name="search_agent", seed="search_agent recovery phrase")
-
-user_query = input("Enter your query: ")
-
-@query_agent.on_event("startup")
-async def send_message(ctx: Context):
- ctx.logger.info("[STARTUP] Query agent starting up and sending user query to search agent.")
- await ctx.send(search_agent.address, Query(message=user_query))
-
-@search_agent.on_message(model=Query)
-async def sigmar_message_handler(ctx: Context, sender: str, msg: Query):
- ctx.logger.info(f"[RECEIVED] Query received from {sender}. Message: '{msg.message}'")
- results = search(msg.message)
- ctx.logger.info("[PROCESSING] Searching completed. Sending response back to the query agent.")
- await ctx.send(query_agent.address, Response(status=results["status"]))
-
-@query_agent.on_message(model=Response)
-async def slaanesh_message_handler(ctx: Context, sender: str, msg: Response):
- ctx.logger.info(f"[RECEIVED] Response received from search agent {sender}. Status: '{msg.status}'")
-
-bureau = Bureau()
-bureau.add(query_agent)
-bureau.add(search_agent)
-
-if __name__ == "__main__":
- print("[INFO] Starting Bureau with Query Agent and Search Agent...")
- bureau.run()
-
-```
-
-## Running the Agent
-
-We run `fetchai-search-agent.py` with the following commands:
-
- ```
- python fetchai-search-agent.py
- ```
-
-## Expected output
-
-The expected output from the `fetchai-search-agent` should be similar to the following:
-
-```
-Enter your query: Buy me a pair of shoes
-[INFO] Starting Bureau with Query Agent and Search Agent...
-INFO: [query_agent]: [STARTUP] Query agent starting up and sending user query to search agent.
-INFO: [search_agent]: [RECEIVED] Query received from agent1qdpstehd8x39n3jr0mas3adcy9d7rh4ss8wtw6euch0mq04tqu66kpfcu3q. Message: 'Buy me a pair of shoes'
-INFO:httpx:HTTP Request: POST https://agentverse.ai/v1/search/agents "HTTP/1.1 200 OK"
-[results] available ais : {
- "ais": [
- {
- "address": "agent1qw7802t7qf98kg775k7f5v3f9h864c72eja2r94pumxnvyx3492xyzu8fmg",
- "name": "My AI's Name",
- "readme": "\nUsed for getting the nike shoes\n\n Used to get the nike shoes\n\n\nnike ai shoess\n\n \n question\n to gwt the nike shoese\n \n\n\n",
- "protocols": [
- {
- "name": "",
- "version": "",
- "digest": "proto:a03398ea81d7aaaf67e72940937676eae0d019f8e1d8b5efbadfef9fd2e98bb2"
- }
- ],...
- },...
- ]
-}
-INFO:httpx:HTTP Request: POST https://api.openai.com/v1/chat/completions "HTTP/1.1 200 OK"
-[INFO] Sending message to AI at address: agent1qv5jr3ylluy45hzwftgctt0hnaa75h2m0ehflxdw8rz3720pjmaegy2447r
-{"version":1,"sender":"agent1qdtxzn2e0dg8y2v5y53p7frplt4w6wq36rfapv38g8x9ukgpc28fgfqnjug","target":"agent1qv5jr3ylluy45hzwftgctt0hnaa75h2m0ehflxdw8rz3720pjmaegy2447r","session":"924e26cb-bae2-4442-95a6-02292125c4f4","schema_digest":"model:708d789bb90924328daa69a47f7a8f3483980f16a1142c24b12972a2e4174bc6","protocol_digest":"proto:a03398ea81d7aaaf67e72940937676eae0d019f8e1d8b5efbadfef9fd2e98bb2","payload":"eyJSZXNwb25zZSI6IkNlcnRhaW5seSEgQmFzZWQgb24geW91ciBxdWVyeSB0byBcIkJ1eSBtZSBhIHBhaXIgb2Ygc2hvZXMsXCIgaGVyZSBhcmUgc29tZSBnZW5lcmFsIHN0ZXBzIG9yIHJlc3VsdHMgdGhhdCBjb3VsZCBoZWxwIHlvdSBmdWxmaWxsIHRoaXMgcmVxdWVzdDpcblxuMS4gKipJZGVudGlmeSBZb3VyIFByZWZlcmVuY2VzOioqXG4gICAtIERldGVybWluZSB0aGUgdHlwZSBvZiBzaG9lcyB5b3UgbmVlZCAoZS5nLiwgc25lYWtlcnMsIGRyZXNzIHNob2VzLCBib290cykuXG4gICAtIENvbnNpZGVyIGFueSBzcGVjaWZpYyBicmFuZHMgb3Igc3R5bGVzIHlvdSBwcmVmZXIuXG5cbjIuICoqU2V0IGEgQnVkZ2V0OioqXG4gICAtIERlY2lkZSBob3cgbXVjaCB5b3UncmUgd2lsbGluZyB0byBzcGVuZCBvbiB0aGUgc2hvZXMuXG5cbjMuICoqUmVzZWFyY2g6KipcbiAgIC0gVmlzaXQgb25saW5lIHJldGFpbCB3ZWJzaXRlcyBzdWNoIGFzIEFtYXpvbiwgWmFwcG9zLCBOaWtlLCBvciBzcGVjaWZpYyBicmFuZCBzaXRlcy5cbiAgIC0gQ2hlY2sgZm9yIGFueSBvbmdvaW5nIHNhbGVzIG9yIGRpc2NvdW50cy5cblxuNC4gKipWaXNpdCBQaHlzaWNhbCBTdG9yZXM6KipcbiAgIC0gSWYgeW91IHByZWZlciB0cnlpbmcgc2hvZXMgb24gYmVmb3JlIHB1cmNoYXNpbmcsIHZpc2l0IGxvY2FsIHNob2Ugc3RvcmVzIG9yIGRlcGFydG1lbnQgc3RvcmVzLlxuXG41LiAqKk9ubGluZSBQbGF0Zm9ybXM6KipcbiAgIC0gVXNlIGUtY29tbWVyY2UgcGxhdGZvcm1zIGxpa2UgQW1hem9uLCBlQmF5LCBvciBzcGVjaWFsaXplZCBzaG9lIHJldGFpbGVycy5cblxuNi4gKipSZWFkIFJldmlld3M6KipcbiAgIC0gQ2hlY2sgY3VzdG9tZXIgcmV2aWV3cyBhbmQgcmF0aW5ncyB0byBlbnN1cmUgcXVhbGl0eSBhbmQgZml0LlxuXG43LiAqKkNvbnNpZGVyIFNpemVzOioqXG4gICAtIEVuc3VyZSB5b3Uga25vdyB5b3VyIHNob2Ugc2l6ZS4gQ2hlY2sgaWYgdGhlIHNwZWNpZmljIGJyYW5kIG9yIHR5cGUgb2Ygc2hvZSBmaXRzIHRydWUgdG8gc2l6ZS5cblxuOC4gKipQdXJjaGFzZToqKlxuICAgLSBPbmNlIHlvdSd2ZSBmb3VuZCBhIHBhaXIgdGhhdCBtYXRjaGVzIHlvdXIgcHJlZmVyZW5jZXMgYW5kIGJ1ZGdldCwgZ28gYWhlYWQgYW5kIG1ha2UgdGhlIHB1cmNoYXNlLlxuXG45LiAqKlNoaXBwaW5nIGFuZCBSZXR1cm5zOioqXG4gICAtIENoZWNrIHRoZSBzaGlwcGluZyBvcHRpb25zIGFuZCB0aGUgcmV0dXJuIHBvbGljeSBpbiBjYXNlIHRoZSBzaG9lcyBkbyBub3QgZml0IG9yIG1lZXQgeW91ciBleHBlY3RhdGlvbnMuXG5cbklmIHlvdSBoYXZlIG1vcmUgc3BlY2lmaWMgY3JpdGVyaWEgb3IgcmVxdWlyZSBhc3Npc3RhbmNlIHdpdGggc3BlY2lmaWMgc3RvcmVzIG9yIGJyYW5kcywgZmVlbCBmcmVlIHRvIHByb3ZpZGUgYWRkaXRpb25hbCBkZXRhaWxzISJ9","expires":null,"nonce":null,"signature":"sig1lsc7kttap4utjfuhs0w34vy396vse2tuekyw6aak77hr9sdwj967u3u3u96l9c20yzn25qgsw70pjtd4tn2hgtlmp8x7u39ad9jhurcgaru0n"}
-INFO:fetchai:Got response looking up agent endpoint
-https://staging-api.flockx.io/v1/chats/webhook_agent/
-INFO:fetchai:Sent message to agent
-INFO: [search_agent]: [PROCESSING] Searching completed. Sending response back to the query agent.
-INFO: [bureau]: Starting server on http://0.0.0.0:8000 (Press CTRL+C to quit)
-INFO: [query_agent]: [RECEIVED] Response received from search agent agent1qgj8y2mswcc4jm275tsnq948fa7aqe8d9v0jd78h0nx9ak6v3fnxj6m6pkj. Status: 'Agent searched'
-```
diff --git a/pages/guides/agents/intermediate/send-tokens.mdx b/pages/guides/agents/intermediate/send-tokens.mdx
deleted file mode 100644
index e26bce498..000000000
--- a/pages/guides/agents/intermediate/send-tokens.mdx
+++ /dev/null
@@ -1,357 +0,0 @@
-import { Callout } from 'nextra/components'
-import { CodeGroup, CodeSegment, DocsCode, GithubCodeSegment } from "../../../../components/code";
-
-# How to use agents to send tokens
-
-## Introduction
-
-Within agent-based decentralized systems, efficient communication and secure data exchange are essential. In this guide, we will walk you through the process of setting up two AI Agents utilizing the `uagents` library to establish a dynamic workflow where one agent periodically sends payment requests to another, which in turn processes these requests, executes transactions, and provides transaction information back to sending agent.
-
-Let's get started!
-
-## Prerequisites
-
-Make sure you have read the following resources before going on with this guide:
-
- - [Quick Start Guide for uAgents Framework ↗️](/guides/agents/quickstart)
- - [Creating your first agent ↗️](/guides/agents/getting-started/create-a-uagent)
- - [Agents address ↗️](/guides/agents/getting-started/getting-uagent-address)
- - [Using agents storage function ↗️](/guides/agents/intermediate/storage-function)
- - [Communicating with other agents ↗️](/guides/agents/intermediate/communicating-with-other-agents)
-
-## Imports needed
-
- - [uAgents ↗️](https://pypi.org/project/uagents/)
-
-## Walk-through
-
-1. First of all, create a Python script for this task, and name it:
-
-
-
- ```py copy filename="mac"
- touch sending_tokens.py
- ```
-
-
-
- ```py copy filename="windows"
- echo. > sending_tokens.py
- ```
-
-
-
- ```py copy filename="ubuntu"
- touch sending_tokens.py
- ```
-
-
-
-2. Then, import the necessary modules from `uagents`, `uagents.network`, and `uagents.setup`. Let's then define two data models: `PaymentRequest` and `TransactionInfo`. We then need to set up the values for the `AMOUNT` and `DENOM` variables, which define the default amount and denomination for the payment requests:
-
-
-
-
-
-
-
- ```py copy filename="sending_tokens.py"
-
- from uagents import Agent, Bureau, Context, Model
- from uagents.network import wait_for_tx_to_complete
- from uagents.setup import fund_agent_if_low
-
- class PaymentRequest(Model):
- wallet_address: str
- amount: int
- denom: str
-
- class TransactionInfo(Model):
- tx_hash: str
-
- AMOUNT = 100
- DENOM = "atestfet"
-
-```
-
-
-
-
-
-
- - The `PaymentRequest` model represents a payment request which contains the `wallet_address`, `amount`, and `denom`.
-
- - The `TransactionInfo` model represents information about a transaction and contains a single attribute, `tx_hash`.
-
-3. Let's now define our agents, `alice` and `bob`. Ensure they have enough funds in their wallets to carry out transactions:
-
-
-
-
-
-
-
- ```py copy filename="sending_tokens.py"
-
- alice = Agent(name="alice", seed="alice secret phrase", port=8000, endpoint=["http://127.0.0.1:8000/submit"])
- bob = Agent(name="bob", seed="bob secret phrase", port=8001, endpoint=["http://127.0.0.1:8001/submit"])
-
- fund_agent_if_low(bob.wallet.address(), min_balance=AMOUNT)
-
-```
-
-
-
-
-
-
-4. We can now define our agents behaviour and functions:
-
-
-
-
-
-
-
- ```py copy filename="sending_tokens.py"
-
- @alice.on_interval(period=10.0)
- async def request_funds(ctx: Context):
- await ctx.send(
- bob.address,
- PaymentRequest(
- wallet_address=str(alice.wallet.address()), amount=AMOUNT, denom=DENOM
- ),
- )
-
-```
-
-
-
-
-
-
- This defines an event handler for `alice` using the `.on_interval()` decorator. This event handler is triggered at regular intervals of `10.0` seconds in this case. The event handler function is named `request_funds()` and takes a `ctx` parameter of type `Context`. Within the function, `alice` sends a payment request message to `bob` by using the `ctx.send()` method. The `ctx.send()` method is called with the recipient address, `bob.address`, which specifies that the message should be sent to `bob`. The message is an instance of the `PaymentRequest()` model. It contains `alice`'s wallet address (`alice.wallet.address()`), the amount (`AMOUNT`), and the denomination (`DENOM`).
-
-5. We can now define a `confirm_transaction()` message handler for `alice` to handle incoming messages from `bob` of type `TransactionInfo`:
-
-
-
-
-
-
-
- ```py copy filename="sending_tokens.py"
-
- @alice.on_message(model=TransactionInfo)
- async def confirm_transaction(ctx: Context, sender: str, msg: TransactionInfo):
- ctx.logger.info(f"Received transaction info from {sender}: {msg}")
- tx_resp = await wait_for_tx_to_complete(msg.tx_hash, ctx.ledger)
-
- coin_received = tx_resp.events["coin_received"]
- if (
- coin_received["receiver"] == str(alice.wallet.address())
- and coin_received["amount"] == f"{AMOUNT}{DENOM}"
- ):
- ctx.logger.info(f"Transaction was successful: {coin_received}")
-
-```
-
-
-
-
-
-
- The event handler function is named `confirm_transaction()` and takes three parameters: `ctx`, `sender`, and `msg`. Within the function, `alice` logs an informational message using the `ctx.logger.info()` method, indicating the receipt of transaction information from the sender agent, `bob`, and displaying the `msg` object. The `wait_for_tx_to_complete()` function is used to await the completion of the transaction specified by the `tx_hash` received in the message.
-
- Once the transaction is completed, the code accesses the `coin_received` event from the transaction response using `tx_resp.events[\"coin_received\"]`. It checks if the receiver address matches `alice`'s wallet address (`alice.wallet.address()`) and if the amount received matches the expected amount (`AMOUNT + DENOM`).
-
- If the conditions are met, `alice` logs another informational message indicating the success of the transaction and displaying the details of the received coins.
-
-6. Let's now define an event handler for `bob`. This event handler is triggered when `bob` receives a message of type `PaymentRequest` from `alice`:
-
-
-
-
-
-
-
- ```py copy filename="sending_tokens.py"
-
- @bob.on_message(model=PaymentRequest, replies=TransactionInfo)
- async def send_payment(ctx: Context, sender: str, msg: PaymentRequest):
- ctx.logger.info(f"Received payment request from {sender}: {msg}")
-
- # send the payment
- transaction = ctx.ledger.send_tokens(
- msg.wallet_address, msg.amount, msg.denom, bob.wallet
- )
-
- # send the tx hash so alice can confirm
- await ctx.send(alice.address, TransactionInfo(tx_hash=transaction.tx_hash))
-
-```
-
-
-
-
-
-
- The event handler function is named `send_payment()` and takes three parameters: `ctx`, `sender`, and `msg`. Within the function, `bob` logs an informational message using the `ctx.logger.info()` method, indicating the receipt of a payment request from the sender agent, `bob`, and displaying the `msg` object.
-
- Next, the code performs a payment transaction using the `ctx.ledger.send_tokens()` method. It takes the wallet address (`msg.wallet_address`), amount (`msg.amount`), denomination (`msg.denom`), and `bob.wallet()` as parameters. This method is responsible for sending the requested payment.
-
- Once the transaction is completed, `bob` sends a message back to `alice` to inform her about the transaction, using `ctx.send()`. The message is created using the `TransactionInfo` model with the `tx_hash` obtained from the transaction response. The `ctx.send()` method is used to send this message to alice using her address (`alice.address`).
-
-7. We are now ready to use the Bureau class to create a `bureau` object and add both uAgents to it so for them to be run together:
-
-
-
-
-
-
-
- ```py copy filename="sending_tokens.py"
-
- bureau = Bureau()
- bureau.add(alice)
- bureau.add(bob)
-
- if __name__ == "__main__":
- bureau.run()
-
-```
-
-
-
-
-
-
-The overall script for this example should look as follows:
-
-
-
-
-
-
-
- ```py copy filename="sending_tokens.py"
-
- from uagents import Agent, Bureau, Context, Model
- from uagents.network import wait_for_tx_to_complete
- from uagents.setup import fund_agent_if_low
-
- class PaymentRequest(Model):
- wallet_address: str
- amount: int
- denom: str
-
- class TransactionInfo(Model):
- tx_hash: str
-
- AMOUNT = 100
- DENOM = "atestfet"
-
- alice = Agent(name="alice", seed="alice secret phrase", port=8000, endpoint=["http://127.0.0.1:8000/submit"])
- bob = Agent(name="bob", seed="bob secret phrase", port=8001, endpoint=["http://127.0.0.1:8001/submit"])
-
- fund_agent_if_low(bob.wallet.address(), min_balance=AMOUNT)
-
- @alice.on_interval(period=10.0)
- async def request_funds(ctx: Context):
- await ctx.send(
- bob.address,
- PaymentRequest(
- wallet_address=str(alice.wallet.address()), amount=AMOUNT, denom=DENOM
- ),
- )
-
- @alice.on_message(model=TransactionInfo)
- async def confirm_transaction(ctx: Context, sender: str, msg: TransactionInfo):
- ctx.logger.info(f"Received transaction info from {sender}: {msg}")
- tx_resp = await wait_for_tx_to_complete(msg.tx_hash, ctx.ledger)
-
- coin_received = tx_resp.events["coin_received"]
- if (
- coin_received["receiver"] == str(alice.wallet.address())
- and coin_received["amount"] == f"{AMOUNT}{DENOM}"
- ):
- ctx.logger.info(f"Transaction was successful: {coin_received}")
-
- @bob.on_message(model=PaymentRequest, replies=TransactionInfo)
- async def send_payment(ctx: Context, sender: str, msg: PaymentRequest):
- ctx.logger.info(f"Received payment request from {sender}: {msg}")
-
- # send the payment
- transaction = ctx.ledger.send_tokens(
- msg.wallet_address, msg.amount, msg.denom, bob.wallet
- )
-
- # send the tx hash so alice can confirm
- await ctx.send(alice.address, TransactionInfo(tx_hash=transaction.tx_hash))
-
- bureau = Bureau()
- bureau.add(alice)
- bureau.add(bob)
-
- if __name__ == "__main__":
- bureau.run()
-
-```
-
-
-
-
-
-
-## Run the script
-
-On your terminal, make sure to have activated the virtual environment.
-
-Run the script: `python sending_tokens.py`
-
-The output should be as follows:
-
- ```
- WARNING: [Alice]: No endpoints provided. Skipping registration: Agent won't be reachable.
- WARNING: [ Bob]: No endpoints provided. Skipping registration: Agent won't be reachable.
- INFO: [bureau]: Starting server on http://0.0.0.0:8000 (Press CTRL+C to quit)
- INFO: [ bob]: Received payment request from agent1qdp9j2ev86k3h5acaayjm8tpx36zv4mjxn05pa2kwesspstzj697xy5vk2a: wallet_address='fetch1967p3vkp0yngdfturv4ypq2p4g760ml705wcxy' amount=100 denom='atestfet'
- INFO: [alice]: Received transaction info from agent1q2kxet3vh0scsf0sm7y2erzz33cve6tv5uk63x64upw5g68kr0chkv7hw50: tx_hash='DB662CCF415C7B0C9A02928967BE1817506D02A041AA05CA48DCE5CF87D5A638'
- INFO: [alice]: Transaction was successful: {'receiver': 'fetch1967p3vkp0yngdfturv4ypq2p4g760ml705wcxy', 'amount': '100atestfet'}
- ```
diff --git a/pages/guides/agents/intermediate/storage-function.mdx b/pages/guides/agents/intermediate/storage-function.mdx
deleted file mode 100644
index ba5a5974b..000000000
--- a/pages/guides/agents/intermediate/storage-function.mdx
+++ /dev/null
@@ -1,157 +0,0 @@
-import { CodeGroup, CodeSegment, DocsCode, GithubCodeSegment } from "../../../../components/code";
-
-# Using agents storage function
-
-## Introduction
-
-Agents will need to store data for later use, uAgents has an inbuilt function to store data to json file, this is done with `ctx.storage`. Data is stored in `key:value` format. `ctx` object’s `storage` attribute has different function like `get` and `set` to use agent’s storage.
-
-## Overview
-
-We can store simple integers like :
-
-```python
-ctx.storage.set("Messages_sent", 1)
-```
-
-Or strings:
-
-```python
-ctx.storage.set("Passkey", "#-eiwfwrign")
-```
-
-Complex data can also be stored:
-
-```python
-Record1 = {"name":ctx.name, "address":ctx.address}
-ctx.storage.set("Record1", Record1)
-```
-
-We can access these values like so:
-
-```python
-ctx.logger.info(ctx.storage.get("Record1"))
-ctx.logger.info(ctx.storage.get("Messages_sent"))
-ctx.logger.info(ctx.storage.get("Passkey"))
-```
-
-Expected Output:
-
-```bash
-INFO: [Receiver]: {"name": "Receiver", "address": "agent1qdlcar9glcm6f9rpzway3xqaw4clfltxdhtwflxrjz3ahy98ep5dx7xy6x7"}
-INFO: [Receiver]: 2
-INFO: [Receiver]: "#-eiwfwrign"
-```
-
-Locally, this will be stored as a json file:
-
-```json
-{
-"Messages_sent" : 2,
-"Record1" : {"name" : "Receiver", "address" : "agent1qdlcar9glcm6f9rpzway3xqaw4clfltxdhtwflxrjz3ahy98ep5dx7xy6x7"},
-"Passkey" : "#-eiwfwrign"
-}
-```
-
-Generally, any object that is compatible with pydantic Models will be fine with uAgents.
-
-## Prerequisites
-
-Make sure you have read the following resources before going on with this guide:
-
- - [Creating your first agent ↗️](/guides/agents/getting-started/create-a-uagent)
- - [Agent Handlers ↗️](/guides/agents/intermediate/handlers)
-
-## Imports needed
-
- - [uAgents ↗️](https://pypi.org/project/uagents/)
-
-## Walk-through
-
-In this walkthrough, we want to show how storage functions are called and how to use them. We want to create an agent which gets a value from the storage (starting from 0) every second. Then prints it, and puts the new value back into the storage but increased by 1 unit.
-
-1. To start let's create a Python script and name it `storage.py`, we can do this in terminal with the following command:
-
-
-
- ```py copy filename="mac"
- touch storage.py
- ```
-
-
-
- ```py copy filename="windows"
- echo. > storage.py
- ```
-
-
-
- ```py copy filename="ubuntu"
- touch storage.py
- ```
-
-
-
-2. Then, we need to open the script in the text editor of choice and import the necessary classes, `Agent` and `Context`, from the `uagents` library.
-
-3. Let's then create an agent named `alice` which logs a message every second using the `.on_interval()` decorator, indicating the current count. The `on_interval()` function takes a `Context` object as a parameter: the `Context` object contains a `storage` attribute, which is used to store and retrieve data between method calls:
-
-
-
-
-
-
-
- ```py copy filename="storage.py"
-
- from uagents import Agent, Context
-
- alice = Agent(name="alice", seed="alice recovery phrase", port=8000, endpoint=["http://127.0.0.1:8000/submit"])
-
- @alice.on_interval(period=1.0)
- async def on_interval(ctx: Context):
- current_count = ctx.storage.get("count") or 0
-
- ctx.logger.info(f"My count is: {current_count}")
-
- ctx.storage.set("count", current_count + 1)
-
- if __name__ == "__main__":
- alice.run()
-
-```
-
-
-
-
-
-
- Here, the `on_interval()` function retrieves the current count from the storage attribute using the `ctx.storage.get()` method. It prints the `current_count` value, and then increments it by `1`, and stores the updated count back to the storage attribute using the `ctx.storage.set()` method. The current count is then logged using the `ctx.logger.info()` method.
-
-4. Save the script.
-
-## Run the script
-
-On your terminal, make sure you activated the virtual environment.
-
-Run the script: `python storage.py`
-
-The output should look as follows:
-
- ```
- INFO: [alice]: Registration on Almanac API successful
- INFO: [alice]: Registering on almanac contract...
- INFO: [alice]: Registering on almanac contract...complete
- INFO: [alice]: Agent inspector available at https://agentverse.ai/inspect/?uri=http%3A//127.0.0.1%3A8000&address=agent1qww3ju3h6kfcuqf54gkghvt2pqe8qp97a7nzm2vp8plfxflc0epzcjsv79t
- INFO: [alice]: Starting server on http://0.0.0.0:8000 (Press CTRL+C to quit)
- INFO: [alice]: My count is: 0
- INFO: [alice]: My count is: 1
- INFO: [alice]: My count is: 2
- INFO: [alice]: My count is: 3
- ...
- ```
diff --git a/pages/guides/agents/intermediate/synchronous-communication.mdx b/pages/guides/agents/intermediate/synchronous-communication.mdx
deleted file mode 100644
index 8d9a4e517..000000000
--- a/pages/guides/agents/intermediate/synchronous-communication.mdx
+++ /dev/null
@@ -1,185 +0,0 @@
-import { CodeGroup, DocsCode,GithubCodeSegment,CodeSegment } from "../../../../components/code"
-
-# Synchronous Communication
-
-## Overview
-
-This guide demonstrates how multiple Agents communicate in the uAgents framework using the `send_and_receive()` method to await responses. The example consists of three agents: `Alice`, `Bob`, and `Clyde`. These exchange messages in a structured and sequential manner.
-
-
-
-
-
-
-
-
-
- ```py copy filename="main.py"
- from uagents import Agent, Bureau, Context, Model
-
-
- class Message(Model):
- message: str
-
-
- alice = Agent(name="alice")
- bob = Agent(name="bob")
- clyde = Agent(name="clyde")
-
-
- @alice.on_interval(period=5.0)
- async def send_message(ctx: Context):
- msg = Message(message="Hey Bob, how's Clyde?")
- reply, status = await ctx.send_and_receive(bob.address, msg, response_type=Message)
- if isinstance(reply, Message):
- ctx.logger.info(f"Received awaited response from bob: {reply.message}")
- else:
- ctx.logger.info(f"Failed to receive response from bob: {status}")
-
-
- @bob.on_message(model=Message)
- async def handle_message_and_reply(ctx: Context, sender: str, msg: Message):
- ctx.logger.info(f"Received message: {msg.message}")
- new_msg = Message(message="How are you, Clyde?")
- reply, status = await ctx.send_and_receive(
- clyde.address, new_msg, response_type=Message
- )
- if isinstance(reply, Message):
- ctx.logger.info(f"Received awaited response from clyde: {reply.message}")
- await ctx.send(sender, Message(message="Clyde is doing alright!"))
- else:
- ctx.logger.info(f"Failed to receive response from clyde: {status}")
-
-
- @clyde.on_message(model=Message)
- async def handle_message(ctx: Context, sender: str, msg: Message):
- ctx.logger.info(f"Received message from {sender}: {msg.message}")
- await ctx.send(sender, Message(message="I'm doing alright!"))
-
-
- bureau = Bureau([alice, bob, clyde])
-
- if __name__ == "__main__":
- bureau.run()
- ```
-
-
-
-
-First, we import the necessary components from the uAgents library and then proceed to define the `Message` data model for messages to be exchanged between Agents. This one contains a single field, `message`, which holds a string.
-
-We go on and initialize 3 Agents: `Alice` initiates communication. `Bob` relays messages and awaits `Clyde`'s response. `Clyde` receives messages and responds accordingly.
-
-We then proceed and define the Agents' handlers, so to define their behaviour:
-
-1. `Alice` sends a message to Bob every 5 seconds and awaits a response:
-
-
-
-
-
-
-
-
- ```py copy
- @alice.on_interval(period=5.0)
- async def send_message(ctx: Context):
- msg = Message(message="Hey Bob, how's Clyde?")
- reply, status = await ctx.send_and_receive(bob.address, msg, response_type=Message)
- if isinstance(reply, Message):
- ctx.logger.info(f"Received awaited response from bob: {reply.message}")
- else:
- ctx.logger.info(f"Failed to receive response from bob: {status}")
- ```
-
-
-
-
- This handler is triggered every 5 seconds (as specified by `period=5.0`). It sends a message to Bob asking how Clyde is doing. Alice creates a `Message` object with the content `"Hey Bob, how's Clyde?"`. The `send_and_receivefunction()` sends the message to `Bob`'s address and waits for a response. The `response_type=Message` argument specifies that the expected reply should be of type `Message`. If a valid `Message` is received, `Alice` logs the response. If the reply is not a valid, it logs the failure status.
-
-2. `Bob` receives `Alice`’s message and forwards a new message to `Clyde`, awaiting a response. Once received, `Bob` informs `Alice`:
-
-
-
-
-
-
-
-
- ```py copy
- @bob.on_message(model=Message)
- async def handle_message_and_reply(ctx: Context, sender: str, msg: Message):
- ctx.logger.info(f"Received message: {msg.message}")
- new_msg = Message(message="How are you, Clyde?")
- reply, status = await ctx.send_and_receive(
- clyde.address, new_msg, response_type=Message
- )
- if isinstance(reply, Message):
- ctx.logger.info(f"Received awaited response from clyde: {reply.message}")
- await ctx.send(sender, Message(message="Clyde is doing alright!"))
- else:
- ctx.logger.info(f"Failed to receive response from clyde: {status}")
- ```
-
-
-
-
- Bob listens for incoming messages from `Alice` and, upon receiving one of type `Message`, it logs the received message from Alice. Bob then constructs a new message (`"How are you, Clyde?"`) and sends it to `Clyde` using `send_and_receive()` method. Bob then waits for `Clyde`'s response. If the response is valid, he sends the reply back to `Alice`, informing her that `"Clyde is doing alright!"`.
-
-3. `Clyde` responds to any message received:
-
-
-
-
-
-
-
-
- ```py copy
- @clyde.on_message(model=Message)
- async def handle_message(ctx: Context, sender: str, msg: Message):
- ctx.logger.info(f"Received message from {sender}: {msg.message}")
- await ctx.send(sender, Message(message="I'm doing alright!"))
- ```
-
-
-
-
- `Clyde` listens for incoming messages from other Agents (in this case, from `Bob`). Upon receiving a message of type `Message`, it responds with a simple confirmation message `"I'm doing alright!"` which is sent back to the `sender` using the `send` method.
-
-### Expected output
-
-Run the example script: `python main.py`
-
-By running the above script, you should be able to see something similar within the terminal output:
-
- ```
- INFO: [alice]: Starting agent with address: agent1qwmt0al3dd334n4f4rs3dw496n02cjackcxfg8l3vfl5m0pf7k5nqamf6rx
- INFO: [ bob]: Starting agent with address: agent1qd7uqtycfr00xkhlpqatvkjdcgfrtf0xh93fncaqa8pf6upvn9jdjcuwzjh
- INFO: [clyde]: Starting agent with address: agent1qvnf3qvc7y24gekpmtd8ar2lpskw8jnc5zzakgcjtku3u798e8lg2vugkgv
- INFO: [bureau]: Starting server on http://0.0.0.0:8000 (Press CTRL+C to quit)
- INFO: [ bob]: Received message: Hey Bob, how's Clyde?
- INFO: [clyde]: Received message from agent1qd7uqtycfr00xkhlpqatvkjdcgfrtf0xh93fncaqa8pf6upvn9jdjcuwzjh: How are you, Clyde?
- INFO: [ bob]: Received awaited response from clyde: I'm doing alright!
- INFO: [alice]: Received awaited response from bob: Clyde is doing alright!
- ```
\ No newline at end of file
diff --git a/pages/guides/agents/quickstart.mdx b/pages/guides/agents/quickstart.mdx
deleted file mode 100644
index 5cc2fb147..000000000
--- a/pages/guides/agents/quickstart.mdx
+++ /dev/null
@@ -1,328 +0,0 @@
-import {CodeGroup, CodeSegment, DocsCode, GithubCodeSegment} from "../../../components/code";
-
-# Quick Start Guide for uAgents Framework
-
-This **Quickstart guide** walks you through the installation process of the **uAgents Framework** and helps building a couple of Agents in a few steps.
-
-You can find all supporting code files in our dedicated [GitHub repo ↗️](https://github.com/fetchai/uAgent-Examples/tree/main/5-documentation/guides/agents/quickstart).
-
-Let's get started!
-
-## Installation
-
-### System requirements
-
- - **Python 3.8+**: it is a popular programming language.
- - **PIP**: it is Python package manager for installing libraries.
- - **Operating System**: _Windows_, _MacOS_ or _Ubuntu_.
-
-### Installation steps
-
-1. Let's start and create a **Project Directory** for your Agent project. Open and type the following within your terminal:
-
- ```py copy
- mkdir directory_name
- cd directory_name
- ```
-
-2. Proceed and install the **uAgents Framework** package:
-
- ```py copy
- pip install uagents
- ```
-
-### Troubleshooting
-
-Sometimes you may face errors during installation. Here we list the most common reasons below:
-
-**Problem on MacOS/Python 3.11**: Installing coincurve (17.0.0) fails.
-
-#### Solution
-
-Install the necessary tools:
-
- ```py
- brew install automake autoconf libtool
- ```
-
-## Creating a simple Agent
-
-Let's create a very basic Agent to get started. Here below you can find the most basic Agent application; we want the Agent to perform a task periodically.
-
-First of all, let's create a new Python script for this project. Open terminal and type the following into it:
-
-
-
- ```py copy filename="mac"
- touch interval_task.py
- ```
-
-
- ```py copy filename="windows"
- echo. > interval_task.py
- ```
-
-
-
- ```py copy filename="ubuntu"
- touch interval_task.py
- ```
-
-
-
-
-Then, open the `interval_task.py` file in a text editor of your choice and add the following code:
-
-
-
-
-
-
-
- ```py copy filename="interval_task.py"
-
- from uagents import Agent, Context
-
- # Create an agent named Alice
- alice = Agent(name="alice", seed="YOUR NEW PHRASE", port=8000, endpoint=["http://localhost:8000/submit"])
-
- # Define a periodic task for Alice
- @alice.on_interval(period=2.0)
- async def say_hello(ctx: Context):
- ctx.logger.info(f'hello, my name is {alice.name}')
-
-
- # Run the agent
- if __name__ == "__main__":
- alice.run()
-
-```
-
-
-
-
-
-Be sure to update `seed` with a unique phrase; the seed will need to be wrapped in `"`.
-
-#### Run Script
-
-Run the script to see the output:
-
- ```py copy
- python interval_task.py
- ```
-
-**Expected Output**:
-
- ```
- INFO: [alice]: Starting server on http://0.0.0.0:8000 (Press CTRL+C to quit)
- INFO: hello, my name is alice
- INFO: hello, my name is alice
- INFO: hello, my name is alice
- ```
-
-## Message Handling Example
-
-Let's now explore how Agents handle messages. Let's set up a simple interaction between two Agents: the first will send a message to the second one at regular intervals, and the latter one will handle and log the received messages accordingly.
-
-First, let's create 2 new Python scripts, one for each Agent:
-
-
-
- ```py copy filename="mac"
- touch SenderAgent.py
- ```
-
-
-
- ```py copy filename="windows"
- echo. > SenderAgent.py
- ```
-
-
-
- ```py copy filename="ubuntu"
- touch SenderAgent.py
- ```
-
-
-
-
-
-
- ```py copy filename="mac"
- touch ReceiverAgent.py
- ```
-
-
- ```py copy filename="windows"
- echo. > ReceiverAgent.py
- ```
-
-
-
- ```py copy filename="ubuntu"
- touch ReceiverAgent.py
- ```
-
-
-
-
-Open `SenderAgent.py` in your text editor and add the following code into it:
-
-
-
-
-
-
-
- ```py copy filename="SenderAgent.py"
-
- from uagents import Agent, Context, Model
-
-
- class Message(Model):
- message: str
-
-
- RECIPIENT_ADDRESS = (
- "test-agent://agent1qd8ymq4najh5wycvhvhcw3l5lmkgkvkrqevrs6wpp5ll0khfdq6v2cq6859"
- )
-
- SenderAgent = Agent(
- name="SenderAgent",
- port=8000,
- seed="SenderAgent secret phrase",
- endpoint=["http://127.0.0.1:8000/submit"],
- )
-
- print(SenderAgent.address)
-
-
- @SenderAgent.on_interval(period=2.0)
- async def send_message(ctx: Context):
- await ctx.send(RECIPIENT_ADDRESS, Message(message="Hi there. Let's start our conversation!"))
-
-
- @SenderAgent.on_message(model=Message)
- async def message_handler(ctx: Context, sender: str, msg: Message):
- ctx.logger.info(f"Received message from {sender}: {msg.message}")
-
-
- if __name__ == "__main__":
- SenderAgent.run()
-
-```
-
-
-
-
-Then, open `ReceiverAgent.py` in your text editor and add the following code into it:
-
-
-
-
-
-
-
- ```py copy filename="ReceiverAgent.py"
-
- from uagents import Agent, Context, Model
-
-
- # NOTE: Run ReceiverAgent.py before running SenderAgent.py
-
-
- class Message(Model):
- message: str
-
-
- ReceiverAgent = Agent(
- name="ReceiverAgent",
- port=8001,
- seed="ReceiverAgent secret phrase",
- endpoint=["http://127.0.0.1:8001/submit"],
- )
-
- print(ReceiverAgent.address)
-
-
- @ReceiverAgent.on_message(model=Message)
- async def message_handler(ctx: Context, sender: str, msg: Message):
- ctx.logger.info(f"Received message from {sender}: {msg.message}")
-
- # send the response
- await ctx.send(sender, Message(message="Cool! Let's get started!"))
-
-
- if __name__ == "__main__":
- ReceiverAgent.run()
-
-```
-
-
-
-
-
-Again, be sure to update `seed` with a unique phrase.
-
-#### Run Script
-
-Open two terminal windows, each one for an Agent, and then run the scripts separately to see the Agents communicating:
-
- ```py copy
- python SenderAgent.py
- ```
-
- ```py copy
- python ReceiverAgent.py
- ```
-
-**Expected Output**:
-
-- **SenderAgent**:
-
- ```
- agent1qdw67s95esk0zwn8qxf0ln22e8zah9rqfrqqa4qyda7mjtpf3hsw640wuwr
- INFO: [SenderAgent]: Registering on almanac contract...
- INFO: [SenderAgent]: Registering on almanac contract...complete
- INFO: [SenderAgent]: Received message from agent1qd8ymq4najh5wycvhvhcw3l5lmkgkvkrqevrs6wpp5ll0khfdq6v2cq6859: Cool! Let's get started!
- INFO: [SenderAgent]: Received message from agent1qd8ymq4najh5wycvhvhcw3l5lmkgkvkrqevrs6wpp5ll0khfdq6v2cq6859: Cool! Let's get started!
- INFO: [SenderAgent]: Received message from agent1qd8ymq4najh5wycvhvhcw3l5lmkgkvkrqevrs6wpp5ll0khfdq6v2cq6859: Cool! Let's get started!
- ```
-
-- **ReceiverAgent**:
-
- ```
- agent1qd8ymq4najh5wycvhvhcw3l5lmkgkvkrqevrs6wpp5ll0khfdq6v2cq6859
- INFO: [ReceiverAgent]: Registering on almanac contract...
- INFO: [ReceiverAgent]: Registering on almanac contract...complete
- INFO: [ReceiverAgent]: Starting server on http://0.0.0.0:8001 (Press CTRL+C to quit)
- INFO: [ReceiverAgent]: Received message from agent1qdp9j2ev86k3h5acaayjm8tpx36zv4mjxn05pa2kwesspstzj697xy5vk2a: Hello there bob.
- INFO: [ReceiverAgent]: Received message from agent1qdp9j2ev86k3h5acaayjm8tpx36zv4mjxn05pa2kwesspstzj697xy5vk2a: Hello there bob.
- INFO: [ReceiverAgent]: Received message from agent1qdp9j2ev86k3h5acaayjm8tpx36zv4mjxn05pa2kwesspstzj697xy5vk2a: Hello there bob.
- ```
-
-## Reach out to the Team!
-
-Excellent! You are now ready to start exploring the concepts and resources available to start developing your agents on the ASI Network! if you're keen to skip the more code focused guides, the best next steps would be exploring how [Agents communicate with other Agents ↗️](/guides/agents/intermediate/communicating-with-other-agents).
-
-Note that our Team is available on [Discord ↗️](https://discord.gg/fetchai) for any additional inquiry.
diff --git a/pages/guides/agentverse/_meta.json b/pages/guides/agentverse/_meta.json
deleted file mode 100644
index 3342e8c70..000000000
--- a/pages/guides/agentverse/_meta.json
+++ /dev/null
@@ -1,14 +0,0 @@
-{
- "creating-agentverse-agents": {
- "title": "Agentverse: create and explore Agents on the Agentverse"
- },
- "agentverse-mailbox": {
- "title": "Agentverse: Mailbox"
- },
- "agentverse-functions": {
- "title": "Agentverse: Agent Functions"
- },
- "avctl": {
- "title": "Deploying agents with AVCTL"
- }
-}
diff --git a/pages/guides/agentverse/agentverse-functions/_meta.json b/pages/guides/agentverse/agentverse-functions/_meta.json
deleted file mode 100644
index 1c38360d9..000000000
--- a/pages/guides/agentverse/agentverse-functions/_meta.json
+++ /dev/null
@@ -1,22 +0,0 @@
-{
- "registering-agent-services": {
- "title": "Register Agentverse Functions",
- "tags": ["Intermediate", "Python", "Functions", "Agentverse", "Hosted"],
- "timestamp": true
- },
- "registering-agent-coin-toss": {
- "title": "Agentverse Functions: coin toss agent",
- "tags": ["Intermediate", "Python", "Functions", "Agentverse", "Hosted"],
- "timestamp": true
- },
- "field-descriptions-for-deltav": {
- "title": "Field descriptions for DeltaV",
- "tags": ["Intermediate", "Python", "Functions", "DeltaV"],
- "timestamp": true
- },
- "hyperlinks-and-rich-text-deltav": {
- "title": "Rich Text and Hyperlinks in responses in DeltaV",
- "tags": ["Intermediate", "Python", "Functions", "DeltaV"],
- "timestamp": true
- }
-}
diff --git a/pages/guides/agentverse/agentverse-functions/field-descriptions-for-deltav.mdx b/pages/guides/agentverse/agentverse-functions/field-descriptions-for-deltav.mdx
deleted file mode 100644
index 5e5111b63..000000000
--- a/pages/guides/agentverse/agentverse-functions/field-descriptions-for-deltav.mdx
+++ /dev/null
@@ -1,140 +0,0 @@
-import { Callout } from 'nextra/components'
-
-# Field descriptions for DeltaV
-
-## The importance of describing your fields in Agent Functions
-
-At registration of an Agent Function on the [Agentverse ↗️](https://agentverse.ai/), providing comprehensive information, especially in the description section, is paramount. A detailed Function **description** not only elucidates the functionality of the Agent Function but also aids users in grasping its essence. This clarity fosters effective interactions, empowering users to navigate the system with confidence, knowing precisely what to anticipate.
-
-Similarly, the **field description** of the Agent Function needs to be detailed enough so to provide a clear picture of each data `Model` the Function requires for it to be executable for Objective execution. Hence, these descriptions serve as a guiding beacon for users, developers, and LLM alike. Each field explanation elucidates the purpose, usage, and expected inputs required by each `Model` class, streamlining interactions and facilitating execution. Enhanced understanding of field descriptions enables the AI Engine to interpret user requests accurately, thereby ensuring accurate Agent Functions execution.
-
-For clarity, reinforcing key concepts could be done through repetition of keywords within the description. Such an approach minimizes ambiguity and mitigates the risk of misunderstandings. Whether for users or LLM, a clear and descriptive field description lay the foundation for smooth interactions and reliable Agent Function delivery and execution.
-
-Consider the following Agent Function:
-
-
-
-Providing a detailed field description for the `CoinToss` data `Model` is important to correctly execute the Function. A well written field description enhances the LLM understanding of the type of Function and the user objective requires to be executed. This would help in the accurate interpretation and execution of users' requests.
-
-It is possible to call additional other **Sub-Services** from either **Objective or other Sub-Services** by specifying this within the field description itself. For additional information on Objective Service and Sub-Service, check the following [resource ↗️](/guides/services/services#primary-and-secondary-functions)
-
-For a network of Primary and Secondary Functions, please refer to the below examples.
-
-## Auto-description functionality
-
-It is possible for you to generate **auto-descriptions** for your Functions when it comes to deploy them on Agentverse.
-
-You can make use of this functionality by opening your Agent's details by clicking on the Agent's box within the list of Agents available in **My Agents** tab in Agentverse. Then, head over to the **Deploy** tab as shown below:
-
-
-
-Here, you will need to either create a **New Function** or **edit an existing one**. This way, you will open your Agent's Function editor, and you will be able to provide/edit the description for what that Function does. It is here where you can make use of the auto-description functionality to fill in such field. This functionality is available for the **Function Description** as well as for the **Fields** description.
-
-Check out the following screenshot to have a better idea:
-
-
-
-By clicking the **Refine** button, the [AI Engine ↗️](/concepts/ai-engine/ai-engine-intro) will automatically generate a description based on the Function details you have provided. You can either provide an initial prompt within the **Description** field to be then refined, or you can auto-generate a description from a nothing and the AI Engine will do this for you by itself.
-
-### Example 1: News Reading System
-
-#### Primary Function Field Description
-
-This Function helps user to read news of a specific type. This Function calls a Secondary function to generate news.
-
-
- Remember to always provide a comprehensive description for triggering the Secondary Function in the field description so to ensure that the Secondary Function is always initiated.
-
-
-
-
-The field description for the `news` data model describes the news that will be presented to the user. It should be mentioned that it should be always provided by triggering of Secondary Function. In our case, a good field description would be: **Describes the news which will be generated from the "Generate News" secondary function. Always go for "Generate News" secondary function only never ask this field from user. All the news articles generated are presented as strings**.
-
-#### Secondary Function Field Description
-
-This Function helps task to generate news and send it to task or another Secondary Function. Below, there is an example where the users ask for news category they want to read and provide news to Primary Function. For a better understanding, you can find the overall guide for this example [here ↗️](/examples/news-reading-system).
-
-
-
-The field description for the `category` data model describes the category for which the user wants to read the news. It should be mentioned that it should be always provided by user. In our case, a good field description would be: **Describes the category provided by user about which he wants to get news for. This should always be provided by user in all cases. This primary function responds to "Generate News" secondary function. This should be from options business, entertainment, general, health, science, sports, technology**.
-
-
- _Remember to always include the secondary function trigger in the field description_. This is very important to ensure that the secondary function is being called. When selecting one of multiple secondary functions, you need to use different names for each one of the functions. This way, we avoid confusion for the LLM.
-
-
-### Example 2: Hugging Face Text Classification Models
-
-This Function helps user to choose a text classification model and make a query to that model. This task hugging face system goes for Secondary Functions to get make request to hugging face API which in turn trigger model list Secondary Functions to get list of model related to a search keyword. User can make query to their selected model.
-
-#### Primary Function Field Description
-
-The field description for the `response` describes the response to be provided to the user. The Primary Function always triggers secondary function **Hugging Face Request**. The ideal field description in this case will be like **Describes the response to the user query. Always go for Hugging face request secondary function to get this field. Never ask this from user.**
-
-
-
-#### Secondary Function Field Description
-
-##### Hugging Face Request
-
-**Hugging face request**: This function has two fields `model_id` (to which query is to be made) and `query` (what request you want to make to the model). The `model_id` field again triggers **Model List** secondary function which asks user for `search` keyword to get most downloaded models related to that keyword.
-
-
-
-Ideal field description for this example will be like:
-
-**model_id:** Always go for model list secondary function. Never ask this field to user.
-**query:** Describes the query user wants to ask the model. Always ask this to user after model_id is given by model list secondary function.
-
-
- Remember to always provide a comprehensive description in `query` field that first we should fetch `model_id` using secondary function before asking `query` to user.
-
-
-##### Model List
-
-**Model List**: This secondary function has field `Search` which searches for top 10 downloaded models related to that keyword from hugging face API and lets user selects from provided model id's.
-
-
-
-Ideal field description for this example will be like:
-
-**Search:** This is the type of model user wants to make query to. Always ask this to user. This always gives list of options to the user. Make user select one from these options.
-
-### Example 3: Local Business Finder
-
-This Function helps user to find local businesses in any locality and specified category. This Agent Function returns list of 10 businesses to user and gives information about selected business by the user.
-
-#### Primary Function Field Description
-
-There are 3 fields in this primary function `category` (Type of business which user wants to search), `city` (City in which user wants to look around for business) and `name` (Name of the business which user wants to search).
-
-Ideal field descriptions for this example will be like:
-
-**category:** This describes business category provided for which user wants to search business. Ask this from user.
-**city:** always go for city finder secondary function to get user's city. Ask user if they want to use this city in yes/no question. ['yes': 'use this city', 'no': 'ask for city they want to search for'].
-**name:** Always go for secondary function business finder service's response. Never ask this from user.
-
-
-
-#### Secondary Function Field Description
-
-1. **City Finder**: This secondary function takes user location from DeltaV and looks for their current location. Below given is the ideal description for location.
-
- **location:** This describes the coordinates of the city given in str(lat,long) format.
-
- 
-
-2. **Business Finder**: This secondary function takes category and city from the primary function and looks around for 10 business name in that area. Asks user to select one and then sends back to task as name field.
-
- **category:** This is the category provided by the user for which they want to get businesses in primary function business details service, Use this category for task as well.
-
- **city:** This is the city responded by city finder or one given by user.
-
- 
-
-## Agent Function registration examples
-
-For additional information and guidelines on how to register an Agent Function on the Agentverse and examples of descriptions, head over to our dedicated resources:
-
- - [Agent Functions ↗️](/guides/agents/intermediate/agent-functions)
- - [Register Agentverse Functions ↗️](/guides/agentverse/registering-agent-services).
- - [Register a coin toss agent as a Function ↗️](/guides/agentverse/registering-agent-coin-toss).
diff --git a/pages/guides/agentverse/agentverse-functions/hyperlinks-and-rich-text-deltav.mdx b/pages/guides/agentverse/agentverse-functions/hyperlinks-and-rich-text-deltav.mdx
deleted file mode 100644
index 353003b4d..000000000
--- a/pages/guides/agentverse/agentverse-functions/hyperlinks-and-rich-text-deltav.mdx
+++ /dev/null
@@ -1,162 +0,0 @@
-import { Callout } from 'nextra/components'
-import PackageVersion from 'components/package-version'
-import { CodeGroup, CodeSegment, DocsCode, GithubCodeSegment } from "../../../../components/code";
-
-# Rich Text and Hyperlinks in responses in DeltaV
-
-## Introduction
-
-This guide will help you understand how to utilize **rich text** and **hyperlinks** within responses in your [DeltaV ↗️](/concepts/ai-engine/deltav) application based on a practical example. This is particularly useful for developers who need to generate interactive and informative content.
-
-
- Check out the [AI Engine package ↗️](https://pypi.org/project/uagents-ai-engine/) to download it and start integrating your Agents with this tool!
-
- Current version of the AI Engine package is
-
- Remember to check out the following [guide ↗️](/guides/agents/intermediate/ai-engine-compatible-agent) to make your agents AI Engine and DeltaV compatible!
-
-
-## Understanding Rich Text and Hyperlinks
-
-### Rich Text and Hyperlinks
-
-**Rich Text** is a text format that supports a variety of text styles and formatting options beyond plain text.
-
-These options include:
-
- - Bold, Italic, and Underline styles
- - Headings and Subheadings
- - Lists (bullet points and numbered)
- - Hyperlinks
-
-Rich text makes your content more visually appealing and easier to read, improving the user experience.
-
-**Hyperlinks** are clickable texts or elements that redirect users to another resource, such as a web page or document. Hyperlinks are often used to connect related content or provide additional information.
-
-In DeltaV, you can include hyperlinks in your responses, allowing users to easily navigate to relevant resources.
-
-## Why Rich Text and Hyperlinks?
-
- 1. **Enhanced communication**: Rich text allows for better formatting and structure, making your messages clearer and more effective.
- 2. **Interactive content**: Hyperlinks enable users to access additional information or related content directly from your responses.
- 3. **Improved user experience**: These features make content more engaging and accessible, leading to higher user satisfaction.
-
-## Implementing Rich Text and Hyperlinks in DeltaV responses
-
-In DeltaV, you can integrate rich text and hyperlinks to enhance the responses generated by your agents or automation workflows. Let's look at how you can implement these features. Let's consider a scenario where you want your DeltaV agent to respond with a list of news articles related to a company, with each article presented as a clickable hyperlink.
-
-The script below shows how to integrate external data (e.g., stock symbols or news articles) into a DeltaV agent's response, and how to format that response using rich text, specifically by creating hyperlinks. This approach enhances the communication capabilities of the DeltaV agent, making its responses more dynamic, interactive, and useful for the end-user.
-
-Here's the example of how to do this in:
-
-
-
-
-
-
-
- ```py copy filename="example.py"
-
- import requests
- from ai_engine import UAgentResponse, UAgentResponseType
-
-
- # Define a news content structure using the Model class to represent a news content
- class NewsRequest(Model):
- company_name: str
-
-
- # Create a protocol for the Hugging Face finbert agent
- news_protocol = Protocol("Institute News")
-
-
- async def fetch_symbol(company_name):
- url = f"https://www.alphavantage.co/query?function=SYMBOL_SEARCH&keywords={company_name}&apikey={ALPHA_VANTAGE_API_KEY}"
- response = requests.get(url)
- if response.status_code == 200:
- data = response.json()
- # Typically, the best match will be the first item in the bestMatches list
- if data.get('bestMatches') and len(data['bestMatches']) > 0:
- # Return the symbol of the best match
- symbol = data['bestMatches'][0]['1. symbol']
- return symbol
- return 'No Symbol found'
-
-
- async def analyze_news(company_name):
- """Analyze news sentiment for the company using GNews."""
- url = f"https://gnews.io/api/v4/search?q={company_name}&token={GNEWS_API_KEY}&lang=en"
- response = requests.get(url)
- articles = response.json().get('articles', [])
-
- # Extract URLs and convert them to hyperlinks with titles
- button_list = []
- for article in articles:
- title = article.get("title", "No Title")
- url = article.get("url", "No Url")
- if url != "No Url":
- # Create a clickable button with the title as text
- button_list.append(f'{title}')
-
- # Combine buttons into a single string with line breaks
- buttons_combined = '\n'.join(button_list)
-
- return buttons_combined
-
-
- @news_protocol.on_message(model=NewsRequest, replies=UAgentResponse)
- async def on_institute_news_request(ctx: Context, sender: str, msg: NewsRequest):
- ctx.logger.info(msg.company_name)
- symbol = await fetch_symbol(msg.company_name)
- ctx.logger.info(symbol)
- news_content = await analyze_news(symbol)
- ctx.logger.info(news_content)
- await ctx.send(sender, UAgentResponse(message=news_content, type=UAgentResponseType.FINAL))
-
-
- agent.include(news_protocol)
-
-```
-
-
-
-
-
-
-
- Remember that you need to get a `ALPHA_VANTAGE_API_KEY` Key from [GNews ↗️](https://gnews.io/) to correctly run this example.
-
-
- The script integrates two key concepts: **fetching data from APIs** and **formatting the response with rich text** (specifically, HTML hyperlinks). We first import the needed libraries and then define the `NewsRequest` Data Model. This takes in a `company_name` as input, which will be used to fetch relevant data from GNews. We proceed and define a communication [protocol ↗️](/references/uagents/uagents-protocols/agent-protocols) within the DeltaV agent named `Institute News`. Protocols are used to handle specific types of messages or requests, in this case, news-related requests about a company. We go on and define 3 different functions:
-
- 1. `fetch_symbol()`: Fetches the stock symbol of a company by querying the **Alpha Vantage API** with the company name. The function constructs the API request URL, sends the request, and parses the JSON response to extract the first match from the `bestMatches` list. If no match is found, it returns `No Symbol found`.
- 2. `analyze_news()`: This function fetches news articles related to the company using the **GNews API**. The function processes the list of articles, extracts their URLs, and formats each URL as a clickable hyperlink using the HTML `` tag. The hyperlinks are then combined into a single string, with each link on a new line, and returned.
- 3. `on_news_request()`: This is the main function that handles incoming requests based on the `NewsRequest` model. The flow is:
- - Logs the company name received in the request.
- - Calls `fetch_symbol()` to retrieve the company's stock symbol.
- - Calls `analyze_news()` to fetch and format the news articles into clickable links.
- - Sends the final response containing the news content back to the sender, using the `UAgentResponse` class with a `FINAL` message type.
-
-
- Use HTML tags to format text as rich text. For example, use `` for bold, `` for italics, and `` for underline. Embed hyperlinks using the `` tag.
-
- Example:
-
- ```
- Click here to visit Example.com
- ```
-
- When users click on **Click here to visit Example**, they will be taken to `https://example.com`.
-
-
-
-## Expected output
-
-
-
-This guide details how to enhance DeltaV responses using rich text and hyperlinks. Rich text allows for enhanced formatting of responses, while hyperlinks make content interactive by providing clickable links to additional resources. The example code demonstrates how to fetch data from APIs, format it with HTML links, and handle requests within a DeltaV agent. Proper use of these features improves readability, engagement, and the overall effectiveness of your responses.
diff --git a/pages/guides/agentverse/agentverse-functions/registering-agent-coin-toss.mdx b/pages/guides/agentverse/agentverse-functions/registering-agent-coin-toss.mdx
deleted file mode 100644
index ed52a2e5a..000000000
--- a/pages/guides/agentverse/agentverse-functions/registering-agent-coin-toss.mdx
+++ /dev/null
@@ -1,164 +0,0 @@
-import { Callout } from 'nextra/components'
-import PackageVersion from 'components/package-version'
-import { CodeGroup, CodeSegment, DocsCode, GithubCodeSegment } from "../../../../components/code";
-
-# Agentverse Functions: register a coin toss agent as a Function
-
-## Introduction
-
-In the [Agentverse Functions: register your Functions on the Agentverse! ↗️](/guides/agentverse/registering-agent-services) guide, you have gotten familiar with the creation of an agent that can be registered as a Function and then be used in [DeltaV ↗️](/concepts/ai-engine/deltav).
-
-
- Check out the [Functions ↗️](/guides/agents/intermediate/agent-functions) guide for additional information needed for Agent Functions and their registration on the Agentverse and ASI network.
-
-
-
- Check out the [AI Engine package ↗️](https://pypi.org/project/uagents-ai-engine/) to download it and start integrating your Agents with this tool!
-
- Current version of the AI Engine package is
-
-
-## Prerequisites
-
-Make sure you have read the following resources before going on with this guide:
-
- - [Quick Start Guide for uAgents Framework ↗️](/guides/agents/quickstart)
- - [Creating your first agent ↗️](/guides/agents/getting-started/create-a-uagent)
- - [Agents address ↗️](/guides/agents/getting-started/getting-uagent-address)
- - [Almanac contract ↗️](/concepts/fetch-network/almanac)
- - [Register in Almanac ↗️](/guides/agents/register-in-almanac)
- - [Agent Functions ↗️](/guides/agents/intermediate/agent-functions)
- - [Make your agents AI Engine compatible ↗️](/guides/agents/intermediate/ai-engine-compatible-agent)
- - [Field descriptions for DeltaV ↗️](/guides/agentverse/agentverse-functions/field-descriptions-for-deltav)
-
-## Create your coin toss agent!
-
-For this navigate to the [Agentverse ↗️](https://agentverse.ai/), log in, and head over to the **My Agents** tab. Then, click on the **+ New Agent** button:
-
-
-
-When the dialog is open, select the **Toss a Coin** use case:
-
-
-
-A new agent will be created for you:
-
-
-
-## Run your coin toss agent!
-
-After clicking on the row of your newly created agent, you should be able to see the source code of your coin toss agent in the editor view:
-
-
-
-
-
-
-
- ```py copy filename="agent.py"
-
- """
- This is a simple coin toss agent that is compatible with DeltaV.
- """
-
- from uagents import Agent, Context, Field, Model, Protocol
- from ai_engine import UAgentResponse, UAgentResponseType
- import random
-
- agent = Agent()
-
-
- class CoinToss(Model):
- choice: str = Field(description="The choice. Must be heads or tails.")
-
-
- coin_toss_protocol = Protocol("CoinToss")
-
-
- @coin_toss_protocol.on_message(model=CoinToss, replies={UAgentResponse})
- async def toss_coin(ctx: Context, sender: str, msg: CoinToss):
- """Simulates a coin toss, compares the result to the sender's choice and send back result"""
- random_number = random.randint(0, 1)
- if random_number == 0:
- coin_tossed = "heads"
- else:
- coin_tossed = "tails"
- if coin_tossed == msg.choice:
- message = "You won!"
- else:
- message = "You lost!"
- await ctx.send(
- sender, UAgentResponse(message=message, type=UAgentResponseType.FINAL)
- )
-
-
- # Include protocol in agent
- agent.include(coin_toss_protocol, publish_manifest=True)
-
- if __name__ == "__main__":
- agent.run()
-
-```
-
-
-
-
-
-
-Now click on the **Run** button in the upper right corner of the editor so that you have your coin toss agent up and running!
-
-
-
-## Register your coin toss agent function!
-
-Similar to the this [guide ↗️](/guides/agentverse/agentverse-functions/registering-agent-services#register-your-agents-and-services), let's head over to the [Agentverse ↗️](https://agentverse.ai/) and select the My Agents tab. Here, click on your agent to show the Agent Editor and then click on the **Deploy** tab to start registering your agent function. For Agents build up from a pre-defined Agent, the function will be already available once you build them. Indeed, you will see something similar to:
-
-
-
-Otherwise, if you want to register a newly created Function for your Agent, click the **+ New Function** button. This way, you will need to provide all details required:
-
-
-
- - **Function title**: just the name of your Agent Function. In this example let's call it **Coin toss function**
- - **Description**: Super important to be as detailed as you can, as reasoning engine looks at descriptions to understand what your Function does. In this example we can specify something like this: _Coin toss Function. Takes the "heads" or "tails" input from the user and based on it decides if the user won or lost._
- - **Application**, **Protocol**, **Model** and **Field descriptions** will be automatically populated based on the source code of [your coin toss agent ↗️](/guides/agentverse/agentverse-functions/registering-agent-coin-toss#run-your-coin-toss-agent)
-
-## Let's find our service on DeltaV
-
-Now, head to [DeltaV ↗️](https://deltav.agentverse.ai/) and sign in.
-
-First, in the **What function would you like to assemble?** bar you can provide a predefined objective; let's type `Toss a coin`.
-
-
- We encourage everyone operating on DeltaV to select the **Next Generation** AI Engine personality type. This AI Engine personality stands as a significant personality type offering _enhanced scalability_, _reliability_, and _flexibility_. The major key features include advanced context understanding, improved function recommendations, and the ability to handle multiple dialogue formats.
-
-
-
-
-After being redirected to the chat screen, you will be asked to select an option.
-As your objective task (`Toss a coin`) specified on the previous screen contained words related to the [description of your coin toss agent ↗️](/guides/agentverse/agentverse-functions/registering-agent-coin-toss#run-your-coin-toss-agent), your Coin Toss Function is listed as an option.
-
-Let's select it.
-
-
-
-After selecting the task, you will be asked if you want to pick `heads` or `tails`. The [AI Engine ↗️](/concepts/ai-engine/ai-engine-intro) behind DeltaV asks this question based on the description. The choice must be heads or tails.
-
-Select whichever option you feel like. In this case let's pick `heads`.
-
-
-
-Then, you can confirm or reject the context that the AI Engine is planning to execute. Let's confirm it!
-
-
-
-After your function has been executed you can see the `You won!` or `You lost!` message.
-
-
-
-With that, **you have gotten a Coin Toss Function which can be discovered and contacted with DeltaV. Awesome!**
diff --git a/pages/guides/agentverse/agentverse-functions/registering-agent-services.mdx b/pages/guides/agentverse/agentverse-functions/registering-agent-services.mdx
deleted file mode 100644
index ba8d89280..000000000
--- a/pages/guides/agentverse/agentverse-functions/registering-agent-services.mdx
+++ /dev/null
@@ -1,226 +0,0 @@
-import { Callout } from 'nextra/components'
-import PackageVersion from 'components/package-version'
-import { CodeGroup, CodeSegment, DocsCode, GithubCodeSegment } from "../../../../components/code";
-
-# Agentverse Functions: register your Agents Functions on the Agentverse!
-
-## Introduction
-
-You can enrol your [Agent Functions ↗️](/guides/services/services) on the Agentverse to be discovered by other agents and start interacting with them. This feature aims at connecting multiple agents offering different Functions to enhance users journey, results and development. The potential of this Agentverse feature is unveiled when interacting with [DeltaV ↗️](/concepts/ai-engine/deltav).
-
-
- Check out the [AI Engine package ↗️](https://pypi.org/project/uagents-ai-engine/) to download it and start integrating your Agents with this tool!
-
- Current version of the AI Engine package is
-
-
-## Prerequisites
-
-Make sure you have read the following resources before going on with this guide:
-
- - [Quick Start Guide for uAgents Framework ↗️](/guides/agents/quickstart)
- - [Creating your first agent ↗️](/guides/agents/getting-started/create-a-uagent)
- - [Agents address ↗️](/guides/agents/getting-started/getting-uagent-address)
- - [Almanac contract ↗️](/concepts/fetch-network/almanac)
- - [Register in Almanac ↗️](/guides/agents/register-in-almanac)
- - [Agents protocols ↗️](/references/uagents/uagents-protocols/agent-protocols)
- - [Exchange protocol ↗️](/references/uagents/uagents-protocols/exchange-protocol)
- - [Agent Functions ↗️](/guides/agents/intermediate/agent-functions)
- - [Make your agents AI Engine compatible ↗️](/guides/agents/intermediate/ai-engine-compatible-agent)
- - [Field descriptions for DeltaV ↗️](/guides/agentverse/agentverse-functions/field-descriptions-for-deltav)
-
-## Walk-through
-
-First of all, to proceed with an Agent Function registration on the [Agentverse ↗️](https://agentverse.ai), you will need to start by creating a dedicated [Agent ↗️](/concepts/agents/agents) wrapping up the Agent Function you wish to provide to users. You can create and code your Agent directly on the [Agentverse: My Agents ↗️](/concepts/agent-services/agent-hosting) tab by clicking on dedicated **+ New Agent** button.
-
-You will then need to define the [protocol ↗️](/references/uagents/uagents-protocols/agent-protocols). You can do this by creating a **simple_protocol.py** within the Agent Editor window:
-
-
-
-
-
-
-
- ```py copy filename="simple_protocol.py"
-
- from uagents import Context, Model, Protocol
- from ai_engine import UAgentResponse, UAgentResponseType
-
- simples = Protocol(name="simples", version="1.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))
-
-```
-
-
-
-
-
-
-Currently, for a service to be allowed you must import and use `UAgentResponse, UAgentResponseType` classes as this is the defined model that are reinforced.
-
-
- `UAgentResponseType` is used to represent different response types of the agent. When the agent sends the response to DeltaV, it also includes the type of the response. It contains the following types:
-
- - `FINAL`: this response type indicates that the message sent by the agent is a final response. It implies that the conversation or interaction has reached its conclusion, and no further responses are expected.
- - `ERROR`: this response type is used when the agent encounters an error or an exceptional situation.
- - `SELECT_FROM_OPTIONS`: this response type is used when DeltaV expects the user to select one option from a list of available options.
- - `FINAL_OPTIONS`: this response type is similar to `FINAL`, but it is used when the agent presents a final list of options to the user.
-
-
-The message you pack into this `UAgentResponse(message="0")` can be any string. If you were not wanting to be a service you could use `Request` as your `Replies`. Let's now define the **agent.py** script for our agent:
-
-
-
-
-
-
-
- ```py copy filename="agent.py"
-
- from simple_protocol import simples
-
- agent.include(simples)
-
-```
-
-
-
-
-
-
-
- You can follow the [Creating an Agentverse hosted agent ↗️](/guides/agentverse/creating-a-hosted-agent) guide if you don't know how to create an agent, or simply haven't created one already.
-
-
-In this example, we have created a simple agent doing nothing but responding to any agent that sends it a message with `0`.
-
-The Agentverse Functions functionality shows its potential when operating on the [DeltaV ↗️](/concepts/ai-engine/deltav) platform. This because Agents registered within the Agentverse, are those retrieved by the AI Engine when users interact with DeltaV chat interface to require a specific objective execution.
-
-Once you finalized the development of your agent, and it is being run (assuming no issues arise), then the agent and its [protocols ↗️](/references/uagents/uagents-protocols/agent-protocols) manifests are uploaded to the [Almanac ↗️](/references/contracts/uagents-almanac/almanac-overview) contact in the form of **protocol digests**.
-
-
- You can check and validate that the uploading process has been carried out correctly by searching for your agent's address on the Agentverse Explorer, and check if the protocols have been uploaded successfully. If not, you need to wait until the protocols will be uploaded successfully.
-
-
-## Register your agents and their functions!
-
-On the [Agentverse ↗️](https://agentverse.ai/) within the **My Agents** tab we previously defined our agent. In here, we can now define the Agent Function we want to provide to users. In this context, Agents Functions can be enrol directly within the Agent Editor window appearing when developing your Hosted Agent.
-
-Let's go ahead and click on your Agent to open the Agent Editor. Then click on the **Deploy** tab.
-
-
- You need to make sure your agent is up and running correctly as Agent Functions can be registered only if your agent is running!
-
-
-
-
-Then, you will be required to provide multiple information as shown below:
-
-
-
-There's a little to unpack here, but it's quite simple:
-
- - **Function title**: just the name of your Agent Function.
- - **Description**: super important to be as detailed as you can, as reasoning AI Engine looks at descriptions to understand what your Agent Function does.
- - **Application**: Objective Service or Sub-Service. For a detailed definition, check [here ↗️](/guides/services/services#primary-and-secondary-functions)
- - **Protocol**: it's defined in your `Agent`.
- - **Model**: again, we defined that in `simple_protocol.py`.
- - **Field descriptions**: just a simple text description of the fields of your `Model`.
-
-### Provide a detailed description
-
-The description is super important to the success of your Agent Function. You need to be very descriptive so that the AI Engine can retrieve your agent Functions correctly.
-
-An example for an agent that returns zero:
-
- `"This Agent Function returns the value zero. This agent returns a string representation of the integer 0. This Function is a representation of the value of zero."`
-
-#### A **bad** example for an agent that sells analytical data on .csv file you send to it:
-
- `"This Agent Function gives inferences on the data file you upload."`
-
-#### A **good** example for an agent that sells analytical data on .csv file you send to it:
-
- `"This Agent Function gives insight and inferences into the CSV file you upload. The function can give you insight into your CSV data. Upload a CSV file to learn more about the data."`
-
-You may need to test your description, if you're ever having trouble let us know over on our [Discord ↗️](https://discord.gg/fetchai).
-
-## Just in case, to test!
-
-If you want an agent to periodically send a message to your Agent Function, you can use the following code example:
-
-
-
-
-
-
-
- ```py copy filename="simple_interval.py"
-
- from ai_engine import UAgentResponse, UAgentResponseType
-
- class Request(Model):
- message: str
-
- @agent.on_message(model=UAgentResponse)
- async def handle_message(ctx: Context, sender: str, msg: UAgentResponse):
- ctx.logger.info(f"Received message from {sender}: {msg.message}")
-
- @agent.on_interval(period=3.0)
- async def send_message(ctx: Context):
- await ctx.send('YOUR AGENT ADDRESS', Request(message="hello there bob"))
- ctx.logger.info(f"Message has been sent to basically zero")
-
-```
-
-
-
-
-
-
-## Let's find our Function on DeltaV
-
-Now, head to [DeltaV ↗️](https://deltav.agentverse.ai/) and sign in.
-
-
- We encourage everyone operating on DeltaV to select the **Next Generation** AI Engine personality type. This AI Engine personality stands as a significant personality type offering _enhanced scalability_, _reliability_, and _flexibility_. The major key features include advanced context understanding, improved function recommendations, and the ability to handle multiple dialogue formats.
-
-
-
-
-We ask **"Please return me a zero"**:
-
-
-
-You will be asked to select an option. Choose **Basically zero** and confirm.
-
-
-
-Then, this is the full output:
-
-
-
-With that, **you have got an Agent Function which can be discovered and contacted with DeltaV! Awesome!**
diff --git a/pages/guides/agentverse/agentverse-mailbox/_meta.json b/pages/guides/agentverse/agentverse-mailbox/_meta.json
deleted file mode 100644
index 1bc0312c4..000000000
--- a/pages/guides/agentverse/agentverse-mailbox/_meta.json
+++ /dev/null
@@ -1,7 +0,0 @@
-{
- "utilising-the-mailbox": {
- "title": "Agentverse: Mailbox",
- "tags": ["Intermediate", "Python", "Communication", "Mailbox", "Local"],
- "timestamp": true
- }
-}
diff --git a/pages/guides/agentverse/agentverse-mailbox/utilising-the-mailbox.mdx b/pages/guides/agentverse/agentverse-mailbox/utilising-the-mailbox.mdx
deleted file mode 100644
index 2c73fbd6c..000000000
--- a/pages/guides/agentverse/agentverse-mailbox/utilising-the-mailbox.mdx
+++ /dev/null
@@ -1,207 +0,0 @@
-import { CodeGroup, CodeSegment, DocsCode, GithubCodeSegment } from "../../../../components/code";
-
-# Utilizing the Agentverse Mailroom feature
-
-## Introduction
-
-The **Agentverse** assists you in setting up mailboxes for [local ↗️](/guides/agents/intermediate/agent-types#local-agents) and [Hosted Agents ↗️](/guides/agents/intermediate/agent-types#hosted-agents), allowing them to have a two-way communication with each other without the need to be constantly online and without requiring your constant presence to operate.
-
-## Prerequisites
-
-Make sure you have read the following resources before going on with this guide:
-
- - [Quick Start Guide for uAgents Framework ↗️](/guides/agents/quickstart)
- - [Creating your first agent ↗️](/guides/agents/getting-started/create-a-uagent)
- - [Agents address ↗️](/guides/agents/getting-started/getting-uagent-address)
- - [Almanac contract ↗️](/concepts/fetch-network/almanac)
- - [Register in Almanac ↗️](/guides/agents/register-in-almanac)
- - [Communicating with other agents ↗️](/guides/agents/intermediate/communicating-with-other-agents)
- - [Agents protocols ↗️](/references/uagents/uagents-protocols/agent-protocols)
- - [Exchange protocol ↗️](/references/uagents/uagents-protocols/exchange-protocol)
- - [Agent Mailboxes ↗️](/guides/agents/intermediate/mailbox)
-
-### Local Agent setup
-
-Let's now start by creating a local agent named `alice` with a `handle_message()` function using an `@agent.on_message()` decorator to handle messages received by other agents and matching the `Message` class:
-
-
-
-
-
-
-
- ```py copy filename="local_agent_setup.py"
-
- 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()
-
- ```
-
-
-
-
-
-
-To create a Mailbox for your local Agent, you first need to run it and click on the [local Agent Inspector ↗️](/guides/agents/intermediate/local-agent-inspector) URL provided within the terminal output. You will be redirected towards the Inspector UI. Here, you will be able to see multiple details about your local Agent.
-
-To connect the local Agent with a Mailbox, click the **Connect** button.
-
-
-
-Then, select **Mailbox** and move on:
-
-
-
-At this point, you do not need to do anything. Just click on **Finish**:
-
-
-
-Great! You successfully connected the local Agent via a Mailbox to the Agentverse!
-
-You can then restart your local Agent. You will see a similar terminal output on your end:
-
- ```
- INFO: [Alice]: Starting agent with address: agent1qw8jn3nfl2fyyhe7v4x8pfmsge4hs9zqrqw9eq7h7hluzmd0da8z7j0uacx
- 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:8002 (Press CTRL+C to quit)
- INFO: [Alice]: Starting mailbox client for https://agentverse.ai
- INFO: [Alice]: Mailbox access token acquired
- INFO: [Alice]: Registration on Almanac API successful
- INFO: [Alice]: Registering on almanac contract...
- INFO: [Alice]: Registering on almanac contract...complete
- INFO: [mailbox]: Successfully registered as mailbox agent in Agentverse
- ```
-
-You can then restart your Agent; now your Agent doesn't need to run all the time as their messages will be waiting for them for when they come back online.
-
-### Agentverse Agent setup
-
-Now create an Agentverse Hosted Agent, `bob`, by selecting **+ New Agent** in the **My Agents** tab in the [Agentverse ↗️](https://agentverse.ai/). Then, select a blank script and add the following code into it:
-
-
-
-
-
-
-
- ```py copy filename="agentverse_agent_setup.py"
-
- 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()
-
-```
-
-
-
-
-
-
-Next, run **bob** on the Agentverse.
-
-### Expected output
-
-You will see something like the following depending on the agent considered:
-
-1. Agentverse Agent output:
-
- ```
- 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
-
- ```
-
-2. Local Agent output:
-
- ```
- 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
- ```
diff --git a/pages/guides/agentverse/avctl/_meta.json b/pages/guides/agentverse/avctl/_meta.json
deleted file mode 100644
index 1470e6a80..000000000
--- a/pages/guides/agentverse/avctl/_meta.json
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "avctl": {
- "title": "Agentverse Command Line Interface (AVCTL)",
- "tags": ["Intermediate", "Python", "AVCTL", "Agentverse"],
- "timestamp": true
- },
- "avctl-hosting": {
- "title": "AVCTL Hosting commands",
- "tags": ["Intermediate", "Python", "AVCTL", "Agentverse"],
- "timestamp": true
- },
- "avctl-ci-github": {
- "title": "CI with AVCTL and Github Actions",
- "tags": ["Intermediate", "Python", "AVCTL", "Agentverse", "Github"],
- "timestamp": true
- }
-}
diff --git a/pages/guides/agentverse/avctl/avctl-ci-github.mdx b/pages/guides/agentverse/avctl/avctl-ci-github.mdx
deleted file mode 100644
index 925ddf0c3..000000000
--- a/pages/guides/agentverse/avctl/avctl-ci-github.mdx
+++ /dev/null
@@ -1,210 +0,0 @@
-import { Callout } from 'nextra/components'
-import agentverse_secret from 'src/images/guides/agentverse/avctl/agentverse_secret.png';
-import github_secret from 'src/images/guides/agentverse/avctl/github_secret.png';
-import action from 'src/images/guides/agentverse/avctl/action.png';
-import { ImageByTheme } from "components/mdx"
-import {CodeGroup, CodeSegment, DocsCode, GithubCodeSegment} from "../../../../components/code";
-
-# CI with AVCTL and Github Actions
-
-This guide explains how we deploy an agent, or update a deployed agent on agentverse using AVCTL.
-
-## Structure
-
-We have a [GitHub repo](https://github.com/fetchai/avctl-ci-example) where you can template or clone this code.
-
-It is made up of three parts, but really two we have our deployment scripts in `.github/workflows` and in `scripts/` and our Agent is under `agent/`.
-
- ```
- ├── README.md
- ├── .github
- │ └── workflows
- │ └── deploy-agent.yaml
- ├── agent
- │ ├── README.md
- │ ├── agent.py
- │ ├── poetry.lock
- | └── pyproject.toml
- └── scripts
- └── deploy-agent.sh
- ```
-
-This logic is very simple, we have a Github workflow that triggers when the branch main is updated. It then calls the
-deployment script in `scripts/deploy-agent.sh`; this script first checks if the Agent already has an address defined in `.avctl/config.toml`; in case it does, is this agent registered? If it isn't, we proceed and register this agent.
-
-If it is registered, let's stop the remote Agent and update it.
-
-You can see the deploy script below, or on [Github](https://github.com/fetchai/avctl-ci-example/blob/main/scripts/deploy-agent.sh)
-
-
-
-
-
-
-
- ```py copy filename="deploy-agent.sh"
-
- # 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
-
-```
-
-
-
-
-
-
-## Getting started
-
-Head on over to the [Agentverse ↗️](https://agentverse.ai) and sign in. Under your profile link (top right) there is an
-option for `API Keys`:
-
-
-
-Clicking this, takes you to an API Key window; here click new **+ New API Key**, give the key a name and give this API key
-full permissions. Click generate API Key at the bottom of the page, and copy the output. Detailed instructions can
-also be found [here ↗️](/guides/apis/agent-function-creation-apis#how-to-get-agentverse-api-tokens)
-
-Once you've got your `API_KEY`, be sure to have forked the [Github repo ↗️](https://github.com/fetchai/avctl-ci-example),
-and visit that repo. Go to settings, on the left hand menu select **Secrets and variables**, and click actions from the
-drop down.
-
-You'll get a window like shown below:
-
-
-
-Click **New repository secret** and enter the `API_KEY`; we have named ours `AGENTVERSE_API_KEY`.
-
-Great! With that set, copy it in your Agent code below Agent definition part. It is assumed here that your Agent is tested, and you also have an account on [Agentverse ↗️](https://agentverse.ai).
-
-Now, let's push:
-
- ```
- git add .
- git commit -m "updating agent"
- git push
- ```
-Visit your forked repo Github page, and under actions you should see the runner in action:
-
-
-
-### Possible error
-
-You may need to locally run:
-
- ```
- sudo git update-index --chmod=+x scripts/deploy-agent.sh
- ```
-
-This tells git to update the permission on the executable script. Then push up the changes for them to take effect.
-
-## Running this locally:
-
-Please follow the installation guide [here ↗️](/guides/agentverse/avctl/avctl#installation)
-
-Update the permissions on `deploy-agent.sh` (You should only need to do this once):
-
- ```
- chmod +x scripts/deploy-agent.sh
- ```
-
-Login to Agentverse from terminal:
-
- ```
- avctl auth login
- ```
-
-Then, from terminal run:
-
- ```
- ./scripts/deploy-agent.sh
- ```
-
-You should see output similar too, dependent on your Agents deployed state:
-
- ```
- josh@vm avctl-ci-example % ./scripts/deploy-agent.sh
- Project already initialized
- Agent exists on agentverse under address: 'agent1qfx5mmewjs4x9ysyxemsaxv6empds4mmpx4sav84yagmhed5yczdwtqkcxu'
- Agent agent1qfx5mmewjs4x9ysyxemsaxv6empds4mmpx4sav84yagmhed5yczdwtqkcxu has been stopped.
- Pushing latest code...
- Everything is up to date. Nothing to push
- Agent agent1qfx5mmewjs4x9ysyxemsaxv6empds4mmpx4sav84yagmhed5yczdwtqkcxu is now running!
- josh@vm avctl-ci-example %
-
- ```
-
-## Quirks
-
-For security reasons, the Agentverse defines your Agent's address and stores your Private Key. An address you set locally will not be applied on Agentverse using the above method.
-
-## Further steps
-
-To get familiar with AVCTL, we recommend reading the other guides in this series: [AVCTL ↗️](/guides/agentverse/avctl/avctl) and [AVCTL hosting ↗️](/guides/agentverse/avctl/avctl-hosting).
diff --git a/pages/guides/agentverse/avctl/avctl-hosting.mdx b/pages/guides/agentverse/avctl/avctl-hosting.mdx
deleted file mode 100644
index c3f71c6f6..000000000
--- a/pages/guides/agentverse/avctl/avctl-hosting.mdx
+++ /dev/null
@@ -1,148 +0,0 @@
-import { Callout } from 'nextra/components'
-
-# AVCTL Hosting
-
-AVCTL `hosting` commands are used for perform agent related actions using Command Line Interface.
-
-## Hosting commands
-
-Before starting actions related to agents make a directory using `mkdir myagent`.
-
- - `avctl hosting init` - Initialize agent template.
-
-```
-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
-```
-
- - `avctl hosting get agents` - Get all agents for the user.
-
-```
-abc@xyz-MacBook-Pro myagents % avctl hosting get agents
-NAME ADDRESS COMPILED DOMAIN REVISION RUNNING WALLET ADDRESS
-name true/false 5 true/false
-```
-
- - `avctl hosting get agent` - Prints the selected deployed agent.
-
-```
-abc@xyz-MacBook-Pro myagents % avctl hosting get agent -a ''
-```
-
- - `avctl hosting pull` - Pull agent files from Agentverse.
-
-```
-abc@xyz-MacBook-Pro myagents % avctl hosting pull -a ''
-* File 'agent.py' successfully downloaded
-* File '.env' successfully downloaded
-```
-
- - `avctl hosting run -l` - Run Agent (optional `-l` flag for logs) if `a` not provided it returns latest pulled agent.
-
-```
-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:
-```
-
- - `avctl hosting stop` - Stop agent
-
-```
-abc@xyz-MacBook-Pro myagents % avctl hosting stop -a
-Agent has stopped!
-```
-
- - `avctl hosting push` - Upload files to Agentverse.
-
-```
-abc@xyz-MacBook-Pro myagents % avctl hosting push -a ''
-All local dependencies are supported on agentverse.
-
-* File '.env' successfully uploaded
-* File 'agent.py' successfully uploaded
-```
-
- - `avctl hosting sync` - Automatically synchronize your local files with those in Agentverse. This command decides whether to pull or push files based on which location has the most recent changes.
-
-```
-abc@xyz-MacBook-Pro myagents % avctl hosting sync -a
-Local and remote files are in sync. Everything is up to date.
-```
-
- - `avctl hosting logs -f` - Print agent logs (optional `-f` option to follow logs).
-
-```
-abc@xyz-MacBook-Pro myagents % avctl hosting logs -f -a
-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:
-```
-
- - `avctl hosting deploy -n ` - Deploy an agent to Agentverse. This command also updates and restarts the agent if it's already deployed.
-
-```
-abc@xyz-MacBook-Pro myagents % avctl hosting deploy -n Generate Keyword news
-Agent exists on agentverse under address: ''
-Pushing latest code and starting the agent...
-All local dependencies are supported on agentverse.
-
-* File '.env' successfully uploaded
-* File 'agent.py' successfully uploaded
-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:
-```
-
- - `avctl hosting add secrets ` - Add a secret
-
- - `avctl hosting delete secrets ` - Delete a secret
-
- - `avctl hosting get secrets` - Retrieve names of all secrets.
-
-```
-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 %
-```
-
- - `avctl hosting packages` - Lists all supported packages by Agentverse.
-
-```
-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 %
-```
-
- - `avctl hosting delete agents -a ` - Deletes an agent from agentverse.
-
-```
-abc@xyz-MacBook-Pro myagents % avctl hosting delete agents -a
-NAME ADDRESS COMPILED DOMAIN REVISION RUNNING WALLET ADDRESS
-name true 4 true
-
-Agent successfully deleted
-```
-
-
- Note: for hosting **push** and **sync** commands the agent should be always in stopped state.
-
diff --git a/pages/guides/agentverse/avctl/avctl.mdx b/pages/guides/agentverse/avctl/avctl.mdx
deleted file mode 100644
index 337bad21a..000000000
--- a/pages/guides/agentverse/avctl/avctl.mdx
+++ /dev/null
@@ -1,52 +0,0 @@
-import { Callout } from 'nextra/components'
-
-# AVCTL - Agentverse Command Line Interface
-
-## Introduction
-
-`AVCTL` is a powerful Command Line Interface (CLI) tool designed for interacting with the Agentverse ecosystem. It offers a range of functionalities from authorization to hosting management, making it an essential tool for developers working within the Agentverse environment.
-
-## Installation
-
-**Pre-requisites**: Ensure that you have `Go` installed on your system.
-
- - **For Mac/Linux users**
-
- ```
- brew tap fetchai/avctl
- brew install avctl
- ```
-
- - **For windows user**
-
- **Using Chocolatey**
- ```
- choco install avctl
- ```
-
-## Usage
-
-There are two types of avctl commands named **auth** and **hosting**. `avctl auth` is used for authorization and `avctl hosting` is used to perform all other actions.
-
-- [Avctl auth commands ↗️](/guides/avctl/avctl#avctl-auth-commands)
-- [Avctl hosting commands ↗️](/guides/avctl/avctl-hosting)
-
-## AVCTL auth commands
-
-AVCTL `auth` commands are used for authorization and logging in and logging off of user.
-
-### Authentication commands
-
-- `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.
-
-```
-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
-```
-
diff --git a/pages/guides/agentverse/creating-agentverse-agents/_meta.json b/pages/guides/agentverse/creating-agentverse-agents/_meta.json
deleted file mode 100644
index e2c1e88af..000000000
--- a/pages/guides/agentverse/creating-agentverse-agents/_meta.json
+++ /dev/null
@@ -1,27 +0,0 @@
-{
- "creating-a-hosted-agent": {
- "title": "Agentverse: Hosted Agents",
- "tags": ["Beginner", "Python", "Agentverse", "Hosted"],
- "timestamp": true
- },
- "simple-dice-roll-agent": {
- "title": "Agentverse: Dice Roll agent",
- "tags": ["Beginner", "Python", "Functions", "Agentverse", "Hosted"],
- "timestamp": true
- },
- "allowed-imports": {
- "title": "Agentverse: Allowed Imports",
- "tags": ["Beginner", "Python", "Agentverse"],
- "timestamp": true
- },
- "agentverse-teams": {
- "title": "Agentverse Teams",
- "tags": ["Beginner", "Agentverse", "Teams"],
- "timestamp": true
- },
- "agent-explorer": {
- "title": "Agentverse Marketplace",
- "tags": ["Beginner", "Agentverse", "Marketplace"],
- "timestamp": true
- }
-}
diff --git a/pages/guides/agentverse/creating-agentverse-agents/agent-explorer.mdx b/pages/guides/agentverse/creating-agentverse-agents/agent-explorer.mdx
deleted file mode 100644
index 9e18bac2b..000000000
--- a/pages/guides/agentverse/creating-agentverse-agents/agent-explorer.mdx
+++ /dev/null
@@ -1,130 +0,0 @@
-import { Callout } from 'nextra/components'
-
-# Agentverse: Marketplace
-
-The **Agentverse Marketplace** lets you look for and connect with other agents registered in the [Almanac ↗️](/references/contracts/uagents-almanac/almanac-overview). Agents being developed on the [Agentverse ↗️](https://agentverse.ai/) are automatically registered in the Almanac, making it simple for anybody to find them and explore their features. In light of this, it is possible to describe the Agentverse Marketplace's functionality as that of an **Almanac Explorer**, as it enables the retrieval of detailed information on any agent that is recorded inside the Almanac.
-
-
- It may be possible that users may not be willing to share agents information but rather wanting to keep them private for any reason. This is achievable thanks to the possibility of **differentiating between public and private agents**. Checkout the following resource for further understanding on this topic: [Public and private agents ↗️](/concepts/agents/public-private-agents).
-
-
-
-
-## Different types of agents
-
-Every Agent available and displayed on the Marketplace can be a: **Hosted**, **Local**, **Mailbox**, or **Proxy** Agent.
-
-### Hosted
-
-**Hosted** agents are agents being developed on the [Agentverse: My Agents ↗️](/concepts/agent-services/agent-hosting) and correctly registered within the Almanac contract and whose registration is up-to-date, meaning that all provided information is up-to-date. In this case the agent is denoted by a green **Active** tag.
-
-### Local
-
-**Local** Agents operate on local infrastructure, offering full control and persistent state, making them ideal for high-performance, real-time, or customized applications. Check out this [resource ↗️](/guides/agents/intermediate/agent-types) for a better understanding of local Agents.
-
-### Mailbox
-
-**Mailbox** Agents are those registered within the [Agentverse: Mailroom ↗️](/concepts/agent-services/agent-mail) and thus are being able to send and receive messages continuously. Mailbox Agents provide a hybrid solution, allowing messages to be stored and processed later when the Agent reconnects, ensuring seamless communication even during downtime.
-
-### Custom
-
-**Custom** Agents are fully configurable, requiring manual setup for connectivity, networking, and deployment. They offer maximum flexibility, allowing developers to control infrastructure, security, and integration, making them ideal for custom or private networks.
-
-### Proxy
-
-**Proxy** Agents connect directly to the Agentverse without requiring a mailbox, enabling continuous operations and enhanced visibility within the Agentverse Marketplace. Check out this [resource ↗️](/guides/agents/intermediate/agent-proxy) for a better understanding of Proxy Agents.
-
-
-Agents which are not online are visible as **Offline** Agents.
-
-Check out the [Agents guides ↗️](/guides) for additional information on the **uAgents Framework** and **Agents**.
-
-## Searching Agents
-
-Agents registered within the Almanac are identified by the following elements:
-
- 1. Agent's **address**.
- 2. Agent's **protocols**.
-
-
- You can explore an agent's [protocols ↗️](/references/uagents/uagents-protocols/agent-protocols) by clicking on the related **Manifest** icon within the protocol's button.
-
-
-It is possible to search and retrieve any Agent specifically by using one of these pieces of information within the search bar in the Marketplace. Additionally, thanks to **filtering** functionality, it is possible to filter Agents based on specific features. For instance, you can search for Agents sharing the same protocol; this can be very helpful when you wish to interact with a given subset of Agents sharing similar features in accordance with your development purposes. You can also use the 3 drop down menus available just below the search bar: **Agent**, **State** and **Trust**. The first lets you search for Agents or [Functions ↗️](/guides/agents/intermediate/agent-functions). The second lets you filter **Active** and **Inactive** Agents. The last one lets you filter **Verified** and **Unverified** Agents.
-
-You can also sort agents based on their geographical location using the 📍button:
-
-
-
-For further guidance on the multiple features of the Agentverse, visit the [Agentverse guides ↗️](/guides).
-
-## Advanced search and filtering
-
-The search bar in the Agentverse Marketplace enables you to refine your searches using filters in combination with plain text queries, similar to GitHub's search functionality.
-
-Below you can find the currently supported filters:
-
-### `is:` options
-
-#### Runtype
-
-This filter allows you to refine searches based on the type of Agent:
-
-- `is:hosted` - Returns hosted Agents.
-- `is:local` - Returns local Agents.
-- `is:mailbox` - Returns mailbox Agents.
-- `is:custom` - Returns custom Agents.
-- `is:proxy` - Returns proxy Agents.
-
-#### Developers
-
-This filter allows you to refine searches based on the Agent's developer:
-
-- `is:fetch-ai` - Returns Agents affiliated with Fetch.ai.
-- `is:community` - Returns community Agents.
-
-#### Others
-
-- `is:active` - Returns active Agents.
-- `is:verified` - Returns verified Agents.
-
-You can add multiple filters when searching for a particular agent. For instance, providing `is:hosted` and `is:active` in the search bar will retrieve all registered Agents that are both **Hosted** and **Active**:
-
-
-
-Additionally, it is possible to use `is:active`, `is:community`, `is:verified`, and `is:fetch-ai` in combination with `-` before them. This way, you will retrieve all agents having the opposite features. For instance, typing `-is:active` in the search bar would return all **inactive** Agents:
-
-
-
-### `has:` options
-
-#### Attributes
-
-This filter allows you to refine searches based on a specific attribute:
-
-- `has:location` - Filters Agents that have a location specified.
-- `has:readme` - Filters Agents that include a README file.
-- `has:guide` - Filters Agents having a guide available.
-- `has:interactions>` - Filters Agents based on the number of interactions. Supported values for `interactions` are the following: `1k`, `10k`, `100k`, `1m`, `10m`, `100m`.
-
-For example, `has:interactions>1k` would return Agents with more than 1,000 interactions.
-
-
-
-### `tag:` options
-
-This filter is used to categorize and refine searches based on the Agent's function, industry, or technology. The followings are the currently available tags:
-
-- `tag:Source_Code` – Filters Agents that provide open-source or accessible code for customization.
-- `tag:domain_tag` – Returns Agents classified under specific industries or specialized domains.
-- `tag:finance` – Filters Agents related to financial services, transactions, or market analytics.
-- `tag:geo` – Returns Agents handling geolocation, mapping, spatial data, or navigation.
-- `tag:integration` – Filters Agents designed to connect and interact with external systems or APIs.
-- `tag:llm` – Returns Agents powered by Large Language Models (LLMs) for AI-driven tasks.
-- `tag:mobility` – Filters Agents focused on transportation, logistics, and smart mobility solutions.
-- `tag:search` – Returns Agents specialized in search, indexing, and retrieval functions.
-- `tag:simple` – Filters lightweight Agents with minimal features, ideal for basic use cases.
-- `tag:source_code` – Similar to `Source_Code`, filters agents with publicly available code.
-- `tag:tech_tag` – Returns Agents classified under specific technology-related categories.
-- `tag:travel` – Filters Agents providing travel-related functions, itinerary planning, or bookings.
-- `tag:utility` – Returns Agents offering essential or general-purpose functionalities.
diff --git a/pages/guides/agentverse/creating-agentverse-agents/agentverse-teams.mdx b/pages/guides/agentverse/creating-agentverse-agents/agentverse-teams.mdx
deleted file mode 100644
index a29f17648..000000000
--- a/pages/guides/agentverse/creating-agentverse-agents/agentverse-teams.mdx
+++ /dev/null
@@ -1,45 +0,0 @@
-# Agentverse Teams
-
-## Introduction
-
-**Agentverse Teams** is a collaborative feature designed to support organizations and teams in developing Agent projects together on the Agentverse. Whether working on a hackathon or collaborating on a long-term project, the Teams feature allows multiple users to straightforwardly create and share Agents within members of the same group. Indeed, Team members can view, edit, and collaborate on any Agent created by any other members, thus facilitating the Agent application development process.
-
-The Agentverse simplifies project management by centralizing access to all Team Agents and resources, making it easier to track progress and coordinate tasks. This functionality provides greater flexibility as Team owners can control access while ensuring new members can quickly get onboarded. This functionality is valuable during hackathons and events, where rapid interactions and real-time collaboration are crucial for deploying solutions quickly and effectively.
-
-The Agentverse Teams feature fosters a collaborative approach while supporting shared learning and skill development among Team members.
-
-## How to create Teams
-
-Head over to the [Agentverse](https://agentverse.ai/) and sign in.
-
-You will then need to click on your **Profile** icon on the top right side of the screen. In the drop-down menu, click on **Create Team**. A window will open up, and you will need to provide the name for the team and accept the terms of service. Once you do so, click **Create Team** button.
-
-
-
-
-
-**Great! Your Agentverse Team is now set up! You can start adding members into it.**
-
-To add members just share the Team URL with other people you wish to add to your team on Agentverse.
-
-## Managing Your Agentverse Team Account
-
-Once you create a Team, you can switch between your personal and team accounts either by using the drop-down menu below your Profile icon:
-
-
-
-Or the dedicated button nearby Profile Settings:
-
-
-
-When clicking on the team account, you will be redirected towards the **Team Profile Settings Dashboard**.
-
-
-
-Here, you can view multiple information about your Team, its members and the Agents. First of all, you can check Team members, their role, status and when they joined. You can also remove users from your Team by clicking on the dedicated button within the more options menu on the right side of the Team member's box.
-
-Additionally, you can browse Agents created and modified by any Team member. You can view the full list of Agents by clicking on the _View all_ link close to the _Agents_ box.
-
-Finally, If you are the Team owner you can invite new members by using the dedicated _+ Add Member_ button.
-
-**Switching back to your personal account will restrict your view to only your personal Agents, which you can continue to develop independently.**
diff --git a/pages/guides/agentverse/creating-agentverse-agents/allowed-imports.mdx b/pages/guides/agentverse/creating-agentverse-agents/allowed-imports.mdx
deleted file mode 100644
index 32b81192d..000000000
--- a/pages/guides/agentverse/creating-agentverse-agents/allowed-imports.mdx
+++ /dev/null
@@ -1,669 +0,0 @@
-# Agentverse: allowed imports
-
-## Introduction
-
-In the [Agentverse ↗️](https://agentverse.ai/) 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:
-
- - [`uagents` ↗️](/guides/agentverse/allowed-imports#uagents).
-
- - [`requests` ↗️](/guides/agentverse/allowed-imports#requests).
-
- - [`cosmpy` ↗️](/guides/agentverse/allowed-imports#cosmpy).
-
- - [`pydantic` ↗️](/guides/agentverse/allowed-imports#datetime).
-
- - [`uagents-ai-engine` ↗️](/guides/agentverse/allowed-imports#ai_engine).
-
- - [`MySQLdb` ↗️](/guides/agentverse/allowed-imports#mysqldb).
-
- - [`pymongo` ↗️](/guides/agentverse/allowed-imports#pymongo).
-
- - [`bs64` ↗️](/guides/agentverse/allowed-imports#bs4-beautifulsoup).
-
- - [`faiss-cpu` ↗️](/guides/agentverse/allowed-imports#faiss-cpu).
-
- - [`fetchai-babble` ↗️](/guides/agentverse/allowed-imports#fetchai-babble).
-
- - [`google-generativeai` ↗️](/guides/agentverse/allowed-imports#google-generativeai).
-
- - [`langchain-anthropic` ↗️](/guides/agentverse/allowed-imports#langchain-anthropic).
-
- - [`langchain-community` ↗️](/guides/agentverse/allowed-imports#langchain-community).
-
- - [`langchain-core` ↗️](/guides/agentverse/allowed-imports#langchain-core).
-
- - [`langchain-google-genai` ↗️](/guides/agentverse/allowed-imports#langchain-google-genai).
-
- - [`langchain-google-vertexai` ↗️](/guides/agentverse/allowed-imports#langchain-google-vertexai).
-
- - [`langchain-openai` ↗️](/guides/agentverse/allowed-imports#langchain-openai).
-
- - [`langchain-text-splitters` ↗️](/guides/agentverse/allowed-imports#langchain-text-splitters).
-
- - [`langchain` ↗️](/guides/agentverse/allowed-imports#langchain).
-
- - [`nltk` ↗️](/guides/agentverse/allowed-imports#nltk).
-
- - [`openai` ↗️](/guides/agentverse/allowed-imports#openai).
-
- - [`tenacity` ↗️](/guides/agentverse/allowed-imports#tenacity).
-
- - [`unstructured` ↗️](/guides/agentverse/allowed-imports#unstructured).
-
- - [`validators` ↗️](/guides/agentverse/allowed-imports#validators).
-
- - [`web3` ↗️](/guides/agentverse/allowed-imports#web3).
-
-## Allowed imports
-
-#### uagents
-
-Build fast and lightweight for decentralized scenarios using the `uagents` Framework. Checkout the [ ↗️](/concepts/agents/agents) documentation and the [`uagents` package ↗️](https://pypi.org/project/uagents/) for more information.
-
- - **Available classes**: `Model`, `Context`, `Protocol`.
-
- **Example**:
-
- ```py copy
- 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**:
-
- ```py copy
- 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 ↗️](/guides/fetch-network/cosmpy/install) documentation and the [CosmPy package ↗️](https://pypi.org/project/cosmpy/)for more information.
-
- - **Full access to all functions and features**.
-
- **Example**:
-
- ```py copy
- 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**:
-
- ```py copy
- from pydantic import BaseModel
-
- data = {
- "name": "alice",
- "age": 21
- }
-
- class User(BaseModel):
- name: str
- age: int
-
- user = User(**data)
-
- print(user)
- ```
-
-#### 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 ↗️](/concepts/ai-engine/ai-engine-intro) documentation and the [AI Engine package ↗️](https://pypi.org/project/uagents-ai-engine/) for further information.
-
- - **Full access to all functions and features**.
-
- **Example**:
-
- ```py copy
- 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**:
-
- ```py copy
- 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**:
-
- ```py copy
- 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**:
-
- ```py copy
- 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**:
-
- ```py copy
- 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 ↗️](https://pypi.org/project/fetchai-babble/).
-
- **Example**:
-
- ```py copy
- 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 ↗️](https://pypi.org/project/google-generativeai/).
-
- **Example**:
-
- ```py copy
- 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 ↗️](https://pypi.org/project/langchain-anthropic/).
-
- **Example**:
-
- ```py copy
- 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 ↗️](https://pypi.org/project/langchain-community/).
-
- **Example**:
-
- ```py copy
- 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 ↗️](https://pypi.org/project/langchain-core/).
-
- **Example**:
-
- ```py copy
- 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 ↗️](https://pypi.org/project/langchain-google-genai/).
-
- **Example**:
-
- ```py copy
- 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 ↗️](https://pypi.org/project/langchain-google-vertexai/).
-
- **Example**:
-
- ```py copy
- 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 ↗️](https://pypi.org/project/langchain-openai/).
-
- **Example**:
-
- ```py copy
- 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 ↗️](https://pypi.org/project/langchain-text-splitters/).
-
- **Example**:
-
- ```py copy
- 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 ↗️](https://pypi.org/project/langchain/).
-
- **Example**:
-
- ```py copy
- 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**:
-
- ```py copy
- 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**:
-
- ```py copy
- 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**:
-
- ```py copy
- 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**:
-
- ```py copy
- 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 ↗️](https://pypi.org/project/validators/).
-
- **Example**:
-
- ```py copy
- import validators
- print(validators.email('someone@example.com')) # 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 ↗️](https://pypi.org/project/web3/).
-
- **Example**:
-
- ```py copy
- 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
-
- ```
-
-## Multi-file Support
-
-The Agentverse Code Editor enhances your agent development experience with multi-file support, enabling you to tackle complex projects with ease. Leverage this feature to:
-
- - **Interact between files**: simply import functions, classes, and variables from one file to another.
- - **Modular development**: divide your projects into manageable components for streamlined creation.
- - **Code reuse**: utilize modules across various sections of your project for efficient development.
- - **Enhanced organization**: maintain a structured and organized codebase for easier maintenance.
-
-If you want to create **new files** you just need to click on **+ New File** on [Agentverse ↗️](https://agentverse.ai/) inside your managed agent.
-
-You can create a Python message file with the following `Model` class:
-
- ```py copy
- from uagents import Model
-
- class Sentence(Model):
- text: str
- ```
-
-Then, you can just import the `Sentence` data model to your `agent.py` file and make use of it:
-
- ```py copy
- from uagents import Context
- from message import Sentence
-
- @agent.on_interval(period=2.0)
- async def print_message(ctx: Context):
- msg = Sentence(text=f"Hello there my wallet address is {ctx.wallet}.")
- print(msg.text)
- ```
-
-For additional information on Functions, head over to [Agent Functions ↗️](/guides/agents/intermediate/agent-functions) and [Register Agent Functions ↗️](/guides/agentverse/agentverse-functions/registering-agent-services) resources.
-
diff --git a/pages/guides/agentverse/creating-agentverse-agents/creating-a-hosted-agent.mdx b/pages/guides/agentverse/creating-agentverse-agents/creating-a-hosted-agent.mdx
deleted file mode 100644
index 57a17daba..000000000
--- a/pages/guides/agentverse/creating-agentverse-agents/creating-a-hosted-agent.mdx
+++ /dev/null
@@ -1,174 +0,0 @@
-import { Callout } from 'nextra/components'
-
-# Creating an Agentverse hosted agent
-
-## Introduction
-
-On the [Agentverse ↗️](https://agentverse.ai/) you can create and host any type of Agent you want to create using the [My Agents ↗️](/concepts/agent-services/agent-hosting) tab.
-
-
- Check out the [Agentverse: allowed imports ↗️](/guides/agentverse/allowed-imports) guide for a better understanding of the packages available for development of Agents on the Agentverse.
-
-
-Let's start by heading over to the **Agentverse: My Agents** tab, click on the **+ New Agent**. Here, there are 2 different ways you can start creating your agent. You can either choose to create an Agent:
-
- 1. From a **Blank Agent**.
- 2. From a **Skeleton Agent**.
-
-## Prerequisites
-
-Make sure you have read the following resources before going on with this guide:
-
- - [Quick Start Guide for uAgents Framework ↗️](/guides/agents/quickstart)
- - [Creating your first agent ↗️](/guides/agents/getting-started/create-a-uagent)
- - [Agents address ↗️](/guides/agents/getting-started/getting-uagent-address)
- - [Almanac contract ↗️](/concepts/fetch-network/almanac)
- - [Register in Almanac ↗️](/guides/agents/register-in-almanac)
- - [Agents running on Agentverse ↗️](/guides/agents/intermediate/hosted-agent)
-
-## Quota Mechanism in Agentverse
-
-To keep your hosted Agents running and maintain uninterrupted operation, **it is required that users log in to the Agentverse at least once every _30 days_**. Failure to do so will result in your Agent being deactivated. This mechanism ensures efficient resource management and prevents unmaintained Agents from consuming unnecessary resources.
-
-
- Ensure you log in at least once every 30 days to prevent your hosted Agent from being deactivated.
-
-
-## Creating an Agent from a blank script
-
-You can create your Agent from a blank script by navigating towards the [Agentverse ↗️](https://agentverse.ai/), signing in and choosing the **My Agents** tab. Here, click on the **+ Agents** button.
-
-
-
-Here, click on the **+ New Agent** button and choose **Blank Agent**.
-
-
-
-You will need to provide a **name** for the Agent you wish to create.
-
-
-
-Once you select it, your agent will be ready to be coded and a box will appear in the **My Agents** page with different data being displayed about the agent you have just created, including the **name** and the **address** of the agent.
-
-
-
-If you click on your agent box, the code editor will be displayed. This is the **Agent Editor**; it allows you to create, edit and refine the code for the Agent you have in mind all in one place. The Agent editor provides various basic information about your Agent, including the **Agent address** and **wallet address**. For additional information on Agent addresses, have a look at our dedicated documentation [here ↗️](/guides/agents/getting-uagent-address).
-
-
-
-The Agent Editor has an integrated **agent.py** and **.env** files that allow you to start programming immediately! The Agent Editor offers you the option of structuring your project into several file windows, which are located on the left-hand side of the editor window. All you have to do is enter a name for the new file to be added. An additional feature of the Agent Editor is the **Agent Logs**; a built-in terminal that displays the output of your script after it has been executed. The Agent Logs provides multiple filters for the different log levels.
-
-The Agent Logs feature is available by clicking the _third bottom_ icon on the left side of the Agent Editor. The first and second buttons enable you to explore **Agents Secrets** and **Agent Storage** features.
-
-
- This way, we aim at making Agents' development as quick and efficient as possible. This is a great tool to determine if your code runs smoothly and to check if any error arises and solve it immediately!
-
-
-
-
-### Documentation and customization for your Agents
-
-Whenever you create an Agent, it is always a good practice to provide a **README** file, **metadata** and an **Agent's icon** for better reference. The **README** helps in providing a clear and concise overview of the Agent's purpose, functionality, and setup instructions. You will be able to see this file within your Agent's Overview page in Agentverse. On the other hand, the **Metadata** should serve as a structured summary of your Agent's configuration, such as its _name_, _description_, _creator details_, and any other _specific settings_ or _dependencies_.
-
-Check out the following [guide ↗️](/guides/agents/intermediate/mailbox) if you have a [local Agent ↗️](/guides/agents/intermediate/agent-types#local-agents) which you want to register into the Agentverse via a Mailbox. The guide will help in understanding how to enroll the Agent using a Mailbox, and how to possibly set up a README file locally and then publish it on Agentverse for your local Agent.
-
-Additionally, every Agent should have a custom icon (i.e., an **Avatar**) to visually distinguish it from others. This icon improves the Agent's identity and usability within the Agentverse. It is possible to customize your agent's **avatar** by clicking on your current Agent's avatar icon and choose either an existing avatar or upload your own! You can do this straightforwardly from the full list of your Hosted Agents or from the Agent Editor when editing information for a particular Agent!
-
-
-
-## Create your first hosted Agent on the Agentverse!
-
-You are now ready to start using the Agentverse to create and edit your Agents in few minutes! Let's begin with creating a simple Agent printing **"Hello world!"** in the Agent Logs on an interval of 3 seconds by using the `.on_interval()` decorator.
-
-Here's an example:
-
-
-
-To run the agent, simply click on the **Run** button. You can stop the script by clicking on the **Stop** button.
-
-The output will be printed in the Agent Logs window:
-
-
-
-
- Within the Agent Editor, you can import and utilize a predefined set of modules to develop your ideas. These pre-approved modules offer a diverse range of functionalities, allowing you to build complex Agents. For further information on modules being available within the Agentverse Editor, have a look at the following resource: [Agentverse: allowed imports ↗️](/guides/agentverse/allowed-imports).
-
-
-## Create an Agent based on a template
-
-You can also create an Agent by choosing **Skeleton Agent** or one of the template options available within the **Getting Started**, **DeltaV Integration**, **Smart Services** or the **AI/ML** tabs. A description of each template Agent is provided when hovering above the option you want to choose.
-
-
-
-There are different categories you can choose from:
-
- 1. **Getting Started**: this category helps you in creating basic Agents using the Agents technology.
- You can:
-
- - _Create your first Agent_.
- - _Send messages between two Agents_.
- - _Storing data_.
- - _Organize your Agents with protocols_.
- - _Create an Agent requesting data from a website_.
- - _Create an Agent sending tokens to another agent_.
- - _Create an Agent interacting with an oracle smart contract_.
-
- 2. **AI/ML**: this category allows you to develop AI/ML Agents.
-
- You can choose to:
-
- - _Create an Agent requesting data from an AI model_.
-
- 3. **Smart Services**: this category is for building smart Agents for different services.
-
- You can choose among:
-
- - _Weather data agent_: this allows you to develop Agents retrieving weather data from weather services API.
- - _Weather data provider and consumer agents_: this use case allows you to create two different Agents, one providing weather data and another one consuming such data.
- - _Weather data seller and buyer agents_: this use case allows you to create two different Agents, one selling weather data and another one buying such data.
- - _Weather oracle provider and consumer agents_: this use case allows you to create two different Agents, one updating an oracle contract with weather data and another one requesting such data to the oracle by paying a small fee.
- - _MongoDB Atlas integration_: this use case shows how to use MongoDB Atlas as a backend for Agent storage with a restaurant booking example.
- - _PlanetScale integration_: this use case shows how to use PlanetScale as a backend for Agent storage with a restaurant booking example.
-
- 4. **DeltaV Integration**: this category allows you to develop Agents offering different Agent Functions which are then made available through the [DeltaV ↗️](/concepts/ai-engine/deltav) chat based on a given template. These Agents and related Functions need to register within the [Agentverse ↗️](/concepts/agent-services/services) first so for them to be available for queries from users operating and interacting with DeltaV Agent. Checkout our dedicated guide for Agent Functions available [here ↗️](/guides/agents/intermediate/agent-functions).
-
- You can choose to:
-
- - _Stock Price Agent_: create a DeltaV compatible Agent requesting the price of a stock.
- - _Coin Toss Agent_: create a DeltaV compatible Agent tossing a coin for you.
- - _Dice Roll Agent_: create a DeltaV compatible Agent rolling a dice for you.
- - _EV Charger Agent_: create a DeltaV compatible Agent to find nearby EV charging stations.
- - _Geocode Agent_: create a DeltaV compatible Agent to find the latitude and longitude of a given address.
- - _Restaurant Agent_: create a DeltaV compatible Agent to find the nearby restaurants based on a given location.
-
-Let's assume you want to create your Agent using the **Your first Agent template** from the **Getting Started** window.
-Each template available presents a small number in the bottom right corner indicating the number of Agents available for that particular template.
-
-
-
-Whenever you choose one of the templates available to start building your Agent, in the Agent Editor you will see some additional information appearing when clicking on the use case chosen, alongside with the baseline code needed to make it runnable. You can use this as a starting point for your ideas.
-
-
-
-The output in this case would be the following:
-
-
-
-## Support for Local Agent Code
-
-You can now import the `Agent` class and create your agent with `my_agent = Agent(...)`. Note that this is simply a wrapper for your pre-loaded `agent` instance, so any custom configuration you add to the Agent will be ignored. This is because the configuration, seed, name, and address for hosted Agents is already set, and is not allowed to be overwritten.
-
-Additionally, you can now use `agent.run()` method, but this is also not required. Clicking `Run` will cause your agent to run whether you include this command or not. The main reason for supporting this is to unify local and hosted Agent code, so that your Agent code can run as either local or hosted without any modifications.
-
-**Exceptions**:
-
-- Use of `Bureau` is not allowed as each Agent project can contain only a single agent.
-- For security reasons, imports are still restricted to those listed in [Agentverse: allowed imports ↗️](/guides/agentverse/allowed-imports). Soon we will be making available a new hosting environment which much fewer restrictions on the imports.
-
-
- Check out the [AVCTL - Agentverse Command Line Interface ↗️](/guides/avctl/avctl) to better understand how to possibly interact with the Agentverse. AVCTL provides multiple features (e.g., authorization and hosting management) allowing developers to log in, set up projects, and deploy Agents on the Agentverse.
-
-
-## Register Domain Name
-
-You can also provide a **Web3 Agent Name** to your Agent. To do so, just click on **+ Register Web3 Name** and fill in the dedicated field for this. This way, your Agent will be given a unique name, making it easier for other Agents to find and communicate with it. The only requirement is _the name being in lowercase with no web3 in between_.
diff --git a/pages/guides/agentverse/creating-agentverse-agents/simple-dice-roll-agent.mdx b/pages/guides/agentverse/creating-agentverse-agents/simple-dice-roll-agent.mdx
deleted file mode 100644
index f37e55f73..000000000
--- a/pages/guides/agentverse/creating-agentverse-agents/simple-dice-roll-agent.mdx
+++ /dev/null
@@ -1,99 +0,0 @@
-import { CodeGroup, CodeSegment, DocsCode, GithubCodeSegment } from "../../../../components/code";
-
-# Creating a simple dice roll Agent on Agentverse
-
-## Introduction
-
-The Agentverse provides multiple base templates you can use to start developing agents in a matter of seconds! You can do so by heading to the **My Agents** tab and click on **+ New Agent**. Here you can choose between a **Blank** agent and a **Skeleton** agent, which incorporates some predefined template you can use as a base point for code creation.
-
-In this example we are going to try out the **dice roll agent** use case.
-
-## Prerequisites
-
-Make sure you have read the following resources before going on with this guide:
-
- - [Quick Start Guide for uAgents Framework ↗️](/guides/agents/quickstart)
- - [Creating your first agent ↗️](/guides/agents/getting-started/create-a-uagent)
- - [Agents address ↗️](/guides/agents/getting-started/getting-uagent-address)
- - [Almanac contract ↗️](/concepts/fetch-network/almanac)
- - [Register in Almanac ↗️](/guides/agents/register-in-almanac)
- - [Agents running on Agentverse ↗️](/guides/agents/intermediate/hosted-agent)
-
-## Create your dice roll agent!
-
-For this navigate to the [Agentverse ↗️](https://agentverse.ai/), log in and select the **My Agents** tab. Here, click on the **Use case** button. When the dialog is open, select the **DeltaV compatible Dice Roll Agent** use case:
-
-
-
-Now, a new agent has been created for you:
-
-
-
-## Run your dice roll agent!
-
-After clicking on the row of your newly created agent, you should be able to see the source code of your dice roll agent in the editor view:
-
-
-
-
-
-
-
- ```py copy filename="agent.py"
-
- """
- This agent can create a simple dice roll, it is compatible with DeltaV.
- """
-
- import random
- from uagents import Agent, Context, Field, Model, Protocol
- from ai_engine import UAgentResponse, UAgentResponseType
-
- agent = Agent()
-
-
- class DiceRoll(Model):
- num_rolls: int = Field(description="Number of rolls.")
-
-
- dice_roll_protocol = Protocol("DiceRoll")
-
-
- @dice_roll_protocol.on_message(model=DiceRoll, replies={UAgentResponse})
- async def roll_dice(ctx: Context, sender: str, msg: DiceRoll):
- """Simulate a dice roll for the specified number of times and sends the results."""
- result = ", ".join([str(random.randint(1, 6)) for _ in range(msg.num_rolls)])
- message = f"Dice roll results: {result}"
- await ctx.send(
- sender, UAgentResponse(message=message, type=UAgentResponseType.FINAL)
- )
-
-
- agent.include(dice_roll_protocol, publish_manifest=True)
-
- if __name__ == "__main__":
- agent.run()
-
-```
-
-
-
-
-
-
-Now click on the **Run** button in the upper right corner of the editor so that you have your dice roll agent up and running!
-
-
-
-**Great! You have just created your agent starting from a predefined template in Agentverse!** You are now ready to understand how to enroll your agent on the Agentverse and make it retrievable by the [AI Engine ↗️](/concepts/ai-engine/ai-engine-intro) and subsequently [DeltaV ↗️](/concepts/ai-engine/deltav).
-
-Check out the following resources to better grasps all of these concepts:
-
- - [Agentverse Functions ↗️](/guides/agents/intermediate/agent-functions).
- - [Agentverse Functions: register your Agents Functions on the Agentverse! ↗️](/guides/agentverse/agentverse-functions/registering-agent-services).
- - [Agentverse Functions: register a coin toss agent as a Function ↗️](/guides/agentverse/agentverse-functions/registering-agent-coin-toss).
diff --git a/pages/guides/ai-engine-sdk/_meta.json b/pages/guides/ai-engine-sdk/_meta.json
deleted file mode 100644
index d5ce6b2f4..000000000
--- a/pages/guides/ai-engine-sdk/_meta.json
+++ /dev/null
@@ -1,12 +0,0 @@
-{
- "python": {
- "title": "AI Engine Python SDK",
- "tags": ["Intermediate", "Python", "Functions", "AI Engine"],
- "timestamp": true
- },
- "javascript": {
- "title": "AI Engine Javascript SDK",
- "tags": ["Intermediate", "Python", "Functions", "AI Engine"],
- "timestamp": true
- }
-}
diff --git a/pages/guides/ai-engine-sdk/javascript.mdx b/pages/guides/ai-engine-sdk/javascript.mdx
deleted file mode 100644
index 044ee2d83..000000000
--- a/pages/guides/ai-engine-sdk/javascript.mdx
+++ /dev/null
@@ -1,273 +0,0 @@
-import { Callout } from 'nextra/components'
-import { CodeGroup, CodeSegment, DocsCode, GithubCodeSegment } from "../../../components/code";
-
-# AI-Engine Javascript SDk
-
-## Introduction
-
-AI Engine SDK provides an easy-to-use interface for integrating advanced AI functionalities into your applications. With a simple API and comprehensive documentation, developers can effortlessly leverage powerful AI tools and enhance their projects.
-
-## Getting Started
-
-### Prerequisites
-Before you begin, ensure you have met the following requirements:
-- **Node.js v20 or higher** is installed on your system.
-- A valid **Agentverse API key**. You can obtain this from [Agentverse ↗️](https://agentverse.ai/).
-
-
-To find out how to generate an API KEY, check out the documentation regarding [Agentverse API keys ↗️](https://fetch.ai/docs/guides/apis/agent-function-creation-apis).
-
-
-### Installation
-You can install the AI Engine SDK using npm or yarn. Follow the commands below.
-
-```bash copy
-npm install @fetchai/ai-engine-sdk
-yarn add @fetchai/ai-engine-sdk
-```
-
-
- Explore the additional resources we have on AI Engine compatible Agents:
- - [Make your agents AI Engine compatible ↗️](/guides/agents/intermediate/ai-engine-compatible-agent)
- - [Agent Functions ↗️](/guides/agents/intermediate/agent-functions)
- - [Register Agent Functions ↗️](/guides/agentverse/agentverse-functions/registering-agent-services)
- - [DeltaV ↗️](/concepts/ai-engine/deltav)
-
-
-## SDK overview
-
-### Creating the AI Engine client object
-
-To set up and initialize the AI Engine client with your API key, use the following code snippet. This client will allow you to interact with the AI Engine API, enabling you to start sessions, get function groups, and manage messages.
-
-```javascript copy
-import { AiEngine } from "@fetchai/ai-engine-sdk";
-const aiEngine = new AiEngine(apiKey);
-```
-
-### Querying Function Groups in AI Engine SDK
-
-```javascript copy
-const functionGroups = await aiEngine.getFunctionGroups();
-const functionGroupId = functionGroups.find((g) => g.name === "Fetch Verified");
-```
-
-If you would like to use the functions in your own My Functions function group, you can use this filter instead:
-
-```javascript copy
-const functionGroupId = functionGroups.find((g) => g.name === "My Functions");
-```
-
-### Creating a session with the AI Engine
-
-This code starts a session with the AI Engine using the UUID of the selected function group.
-
-```javascript copy
-const session = await aiEngine.createSession(functionGroupId);
-```
-
-### Starting the conversation with an arbitrary objective
-
-```javascript copy
-await session.start("Find a holiday destination");
-```
-
-### Querying new messages
-
-This line asynchronously queries the AI engine to retrieve a list of messages related to the current session. Use `setTimeout` or `setInterval` to regularly check for new messages.
-
-```javascript copy
-const messages = await session.getMessages();
-```
-
-## Handling Different Types of Messages
-
-#### Task Selection Message (`isTaskSelectionMessage`)
-
-This message is generated when the AI engine suggests functions based on the initial objective or provides multiple options for a function.
-
-#### Agent Message (`isAgentMessage`)
-
-This is a regular question from the AI Engine that the user needs to reply to with a string.
-
-#### AI Engine Message (`isAiEngineMessage`)
-
-This message type doesn't require a user response; it simply notifies the user about something.
-
-#### Confirmation Message (`isConfirmationMessage`)
-
-This message is sent when the AI Engine has gathered all necessary inputs for the agent's function, indicating that the context is complete.
-
-#### Stop Message (`isStopMessage`)
-
-This message is sent when the session has ended, and the AI Engine no longer expects any replies from the user.
-
-
-All message types (except for the AI engine message and stop message) expect a response from the user.
-
-
-## SDK Methods for Replying
-
-### Task Selection Message
-
-Use `session.submitTaskSelection`.
-
-### Agent Message
-
-Use `session.submitResponse`.
-
-### Confirmation Message
-
-Use either `session.submitConfirmation` to confirm, or `session.rejectConfirmation` to reject the context generated by the AI engine.
-
-## Deleting session
-
-After finishing a conversation with the AI Engine, you can delete the session by using the following command.
-
-```javascript copy
- await session.delete()
-```
-
-## Example Usage of the SDK
-
-The following example demonstrates how to use the AI Engine SDK to interact with the AI Engine. The script sets up the client, queries function groups, creates a session, and handles different types of messages in a loop.
-
-
-
-
-
-
-
- ```py copy filename="example.ts"
-
- import * as readline from "node:readline";
-
- import {
- AiEngine,
- isAgentMessage,
- isAiEngineMessage,
- isConfirmationMessage,
- isStopMessage,
- isTaskSelectionMessage,
- } from "@fetchai/ai-engine-sdk";
-
- const apiKey = process.env["AV_API_KEY"] ?? "";
-
- const snooze = (ms: number) =>
- new Promise((resolve) => setTimeout(resolve, ms));
-
- const main = async () => {
- const rl = readline.promises.createInterface({
- input: process.stdin,
- output: process.stdout,
- });
-
- const aiEngine = new AiEngine(apiKey);
-
- const functionGroups = await aiEngine.getFunctionGroups();
- const publicGroup = functionGroups.find((g) => g.name === "Fetch Verified");
- if (publicGroup === undefined) {
- throw new Error('Could not find "Public" function group.');
- }
-
- const session = await aiEngine.createsession(publicGroup.uuid);
- await session.start(await rl.question("What is your objective: "));
-
- try {
- let emptyCount = 0;
- let sessionEnded = false;
- while (emptyCount < 12) {
- const messages = await session.getMessages();
- if (messages.length === 0) {
- emptyCount++;
- } else {
- emptyCount = 0;
- }
-
- for (const message of messages) {
- if (isTaskSelectionMessage(message)) {
- console.log("Please select a task from the list below:");
- console.log("");
- for (const option of message.options) {
- console.log(`${option.key}: ${option.title}`);
- }
-
- const optionIndex = parseInt(
- await rl.question("\nEnter task number: "),
- );
-
- // check the index
- if (optionIndex < 0 || optionIndex >= message.options.length) {
- throw new Error("Invalid task number");
- }
-
- await session.submitTaskSelection(message, [
- message.options[optionIndex]!,
- ]);
- } else if (isAgentMessage(message)) {
- console.log("Agent: ", message.text);
-
- const response = await rl.question("User (enter to skip): ");
- if (response === "exit") {
- break;
- }
-
- if (response !== "") {
- await session.submitResponse(message, response);
- }
- } else if (isAiEngineMessage(message)) {
- console.log("Engine:", message.text);
- } else if (isConfirmationMessage(message)) {
- console.log("Confirm:", message.payload);
-
- const response = await rl.question(
- "\nPress enter to confirm, otherwise explain issue:\n",
- );
-
- if (response === "") {
- console.log("Sending confirmation...");
- await session.submitConfirmation(message);
- } else {
- await session.rejectConfirmation(message, response);
- }
- } else if (isStopMessage(message)) {
- console.log("\nSession has ended");
- sessionEnded = true;
- break;
- } else {
- console.error("???", message);
- }
- }
-
- // if the session has concluded then break
- if (sessionEnded) {
- break;
- }
-
- await snooze(1200);
- }
- } catch (e) {
- console.error("Error", e);
- } finally {
- // clean up the session
- await session.delete();
-
- // stop the readline interface
- rl.close();
- }
- };
-
- main();
-
-```
-
-
-
-
-
-
diff --git a/pages/guides/ai-engine-sdk/python.mdx b/pages/guides/ai-engine-sdk/python.mdx
deleted file mode 100644
index f53d03ee3..000000000
--- a/pages/guides/ai-engine-sdk/python.mdx
+++ /dev/null
@@ -1,326 +0,0 @@
-import { Callout } from 'nextra/components'
-import { CodeGroup, CodeSegment, DocsCode, GithubCodeSegment } from "../../../components/code";
-
-# AI-Engine Python SDk
-
-## Introduction
-
-AI Engine SDK provides an easy-to-use interface for integrating advanced AI functionalities into your applications. With a simple API and comprehensive documentation, developers can effortlessly leverage powerful AI tools and enhance their projects.
-
-## Getting Started
-
-### Prerequisites
-Before you begin, ensure you have met the following requirements:
-- **Python 3.10 or higher** installed on your system.
-- A valid **Agentverse API key**. You can obtain this from [Agentverse ↗️](https://agentverse.ai/).
-
-
-To find out how to generate an API KEY check out the documentation regarding [Agentverse API keys ↗️](https://fetch.ai/docs/guides/apis/agent-function-creation-apis).
-
-
-### Installation
-You can install the AI Engine SDK using either Poetry or pip. Follow the commands below.
-
-```bash copy
-poetry add ai-engine-sdk
-pip install ai-engine-sdk
-```
-
-
- Explore the additional resources we have on AI Engine compatible Agents:
- - [Make your agents AI Engine compatible ↗️](/guides/agents/intermediate/ai-engine-compatible-agent)
- - [Agent Functions ↗️](/guides/agents/intermediate/agent-functions)
- - [Register Agent Functions ↗️](/guides/agentverse/agentverse-functions/registering-agent-services)
- - [DeltaV ↗️](/concepts/ai-engine/deltav)
-
-
-## SDK overview
-
-### Creating the AI Engine client object
-
-To set up and initialize the AI Engine client with your API key, use the following code snippet. This client will allow you to interact with the AI Engine API, enabling you to start sessions, get function groups, and manage messages.
-
-```py copy
-from ai_engine_sdk import AiEngine
-ai_engine: AiEngine = AiEngine(api_key)
-```
-
-## Querying Function Groups
-
-The AI Engine SDK allows you to query different groups of functions, such as `private functions`, `public functions`, or `Fetch.ai-verified functions`. You can filter function groups using the respective methods provided by the SDK based on your needs.
-
-### Querying Private Functions
-
-Private functions are those that you have created and are not accessible to the public or other users. To access your private functions, use the `get_private_function_groups()` method. This will return all functions under your account, giving you access to personal or proprietary models and algorithms.
-
-#### Example
-
-```python
-private = await ai_engine.get_private_function_groups()
-
-private_functions = next(
- (g for g in private if g.name == "My Functions"),
- None
-)
-```
-
-#### Querying Public Functions
-
-Public functions are accessible by anyone on the platform. These functions include your publicly available functions and functions verified by Fetch.ai. To access public function groups, use the `get_public_function_groups()` method. You can further filter by two important groups: `Public` and `Fetch Verified`.
-
-```py copy
-public = await ai_engine.get_public_function_groups()
-
-# Access your public functions
-public_functions = next(
- (g for g in public if g.name == "Public"),
- None
-)
-
-# Access Fetch.ai-verified functions
-fetch_verified_group = next(
- (g for g in public if g.name == "Fetch Verified"),
- None
-)
-```
-
-### Sharing function groups
-
-Allow other users to use functions, under a function-group, without replicating that function or allowing
-them alter those functions or function-group data.
-
-If you wish to give access to a certain function-group (use, not alter the data/state of it), you can use the following method in the following way:
-
-```python
-# assuming `ai_engine` is a valid instance of AiEngine
-
-what_function_group_identifier_i_want_share="normally-this-is-an-uuid4"
-user_email_i_want_to_share_the_function_group_with = "random@domain.com"
-await ai_engine.share_function_group(
- function_group_id=what_function_group_identifier_i_want_share,
- target_user_email=user_email_i_want_to_share_the_function_group_with
-)
-```
-Now, if you were requesting the available function-groups for the user with email assigned to the `target_user_email` argument, the function-group with the id assigned to `function_group_id`.
-
-You can check that by using the `AiEngine.get_function_groups` method.
-
-### Creating a session with the AI Engine.
-
-This code starts a session with the AI Engine using the UUID of the selected function group.
-
-```py copy
-session = await ai_engine.create_session(function_group=public_group.uuid)
-```
-
-### Starting the conversation with an arbitrary objective
-
-```py copy
-await session.start(objective)
-```
-
-### Querying new messages
-
-This line asynchronously queries the AI engine to retrieve a list of messages related to the current session. The messages are returned as a list of `ApiBaseMessage` objects, which can include various types of messages such as agent messages, AI engine messages, task selections, confirmations, and session stop messages. These messages are then processed to determine the next actions in the session workflow.
-
-```py copy
-while True:
- messages: list[ApiBaseMessage] = await session.get_messages()
- sleep(4)
-```
-
-## Handling Different Types of Messages
-
-#### Task Selection Message (`is_task_selection_message`)
-
-This message is generated when the AI engine suggests functions based on the initial objective or provides multiple options for a function.
-
-#### Agent Message (`is_agent_message`)
-
-This is a regular question from the AI Engine that the user needs to reply to with a string.
-
-#### AI Engine Message (`is_ai_engine_message`)
-
-This message type doesn't require a user response; it simply notifies the user about something.
-
-#### Confirmation Message (`is_confirmation_message`)
-
-This message is sent when the AI Engine has gathered all necessary inputs for the agent's function, indicating that the context is complete.
-
-#### Stop Message (`is_stop_message`)
-
-This message is sent when the session has ended, and the AI Engine no longer expects any replies from the user.
-
-
-All message types (expect for the AI engine message and stop message) expects a response from the user.
-
-
-## SDK Methods for Replying
-
-### Task Selection Message
-
-Use `session.submit_task_selection`.
-
-### Agent Message
-
-Use `session.submit_response`.
-
-### Confirmation Message
-
-Use either `session.submit_confirmation` to confirm, or `session.reject_confirmation` to reject the context generated by the AI engine.
-
-## Deleting session
-
-After finishing a conversation with the AI Engine, you can delete the session by using the following command.
-
-```py copy
- await session.delete()
-```
-
-## Example Usage of the SDK
-
-The following example demonstrates how to use the AI Engine SDK to interact with the AI Engine. The script sets up the client, queries function groups, creates a session, and handles different types of messages in a loop.
-
-
-
-
-
-
-
- ```py copy filename="run_example.py"
-
- import asyncio
- import logging
- import os
- import sys
- from time import sleep
- from ai_engine_sdk import (
- AiEngine,
- is_agent_message,
- is_ai_engine_message,
- is_confirmation_message,
- is_stop_message,
- is_task_selection_message, TaskSelectionMessage
- )
- from ai_engine_sdk import ApiBaseMessage, FunctionGroup
-
- logger = logging.getLogger(__name__)
-
- api_key = os.getenv("AV_API_KEY", "")
- interaction_user_prompt_header = f"\n\n🤖 Interaction time"
-
-
- async def main():
- logger.debug("🚀 Starting example execution")
- ai_engine = AiEngine(api_key)
-
- function_groups: list[FunctionGroup] = await ai_engine.get_function_groups()
-
- public_group = next((g for g in function_groups if g.name == "Fetch Verified"), None)
- if public_group is None:
- raise Exception('Could not find "Public" function group.')
-
- session = await ai_engine.create_session(function_group=public_group.uuid)
- default_objective: str = "Find a flight to warsaw."
-
- logger.info(interaction_user_prompt_header)
- objective = input(f"\n🎯 What is your objective [default: {default_objective}]: ") or default_objective
- await session.start(objective)
-
- try:
- empty_count = 0
- session_ended = False
-
- while empty_count < 100:
- messages: list[ApiBaseMessage] = await session.get_messages()
- if len(messages) == 0:
- empty_count += 1
- else:
- empty_count = 0
-
- message: ApiBaseMessage
- for message in messages:
- if is_task_selection_message(message_type=message.type):
- task_selection_message: TaskSelectionMessage = message
-
- logger.info(interaction_user_prompt_header)
- print("Please select a key from the list below:\n")
- for _, option in task_selection_message.options.items():
- print(f"➡ 🔑 {option.key} -> 🧰 {option.title}")
- option_key = str(input("\nEnter task key: "))
-
- # check the index
- if option_key not in task_selection_message.options.keys():
- raise Exception(f"🔴 Invalid task number.\n You selected: {option_key}")
- logger.debug(option_key)
- await session.submit_task_selection(
- message,
- [task_selection_message.options[option_key]]
- )
- del task_selection_message
- elif is_agent_message(message):
- logger.info(interaction_user_prompt_header)
- print(message.text.capitalize())
- response = input("✍ (enter to skip): ")
- if response == "exit":
- break
-
- if response != "":
- await session.submit_response(message, response)
- elif is_ai_engine_message(message):
- logger.info(f"\n 🤖 ℹ Informative message \n\n ---> ✨{message.text}")
- sleep(3.5)
- elif is_confirmation_message(message_type=message.type):
- logger.info(interaction_user_prompt_header)
- print("Confirm:", message.payload)
- response = input("\nPress enter to confirm, otherwise explain issue:\n")
-
- if response == "":
- await session.submit_confirmation(message)
- else:
- await session.reject_confirmation(message, response)
- elif is_stop_message(message):
-
- logger.info("\n 👋 Session has ended, thanks! ")
- session_ended = True
- break
-
- # if the session has concluded then break
- if session_ended:
- break
-
- logger.info(f"\n🤖 Processing\n")
- sleep(1.5)
- logger.debug(f"No messages: {empty_count} times in a row")
-
- except Exception as e:
- logger.debug(f"Unhandled exception: {e}")
- print("Error", e)
- raise e
- finally:
- # clean up the session
- await session.delete()
-
-
- if __name__ == "__main__":
- logging.basicConfig(
- stream=sys.stdout,
- level=logging.DEBUG,
- # level=logging.INFO,
- format='%(asctime)s %(levelname)s %(module)s: %(message)s',
- datefmt="%H:%M:%S"
- )
- asyncio.run(main())
-
-```
-
-
-
-
-
-
diff --git a/pages/guides/apis/_meta.json b/pages/guides/apis/_meta.json
deleted file mode 100644
index 90fa875dd..000000000
--- a/pages/guides/apis/_meta.json
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "agent-function-creation-apis": {
- "title": "Agents and Functions creation APIs",
- "timestamp": true
- },
- "secret-management-apis": {
- "title": "Secret Management APIs",
- "timestamp": true
- }
-}
diff --git a/pages/guides/apis/agent-function-creation-apis.mdx b/pages/guides/apis/agent-function-creation-apis.mdx
deleted file mode 100644
index a233c0b21..000000000
--- a/pages/guides/apis/agent-function-creation-apis.mdx
+++ /dev/null
@@ -1,420 +0,0 @@
-import { CodeGroup, CodeSegment, DocsCode, GithubCodeSegment } from "../../../components/code";
-
-# Agents and Functions Creation using APIs
-
-## Introduction
-
-This guide shows how to create **Agents** and **Agent Functions** in Agentverse using APIs. With this guide, we set up a Python script that interacts with the Agentverse and help us creating Agents and Agent Functions. Before you begin, it is necessary that you satisfy the following requirements:
-
- - Python version greater than 3.9 and less than 3.11.
- - The `requests` library is installed. You can install it using: `pip install requests`.
- - [Agentverse ↗️](https://agentverse.ai/) credentials.
-
-## How to get Agentverse API Tokens
-
- - Log in to your [Agentverse ↗️](https://agentverse.ai/) account and go to the Profile section.
- - Click on button `+ New API Key`.
- - Give name to your API key.
- - Click on `write` for `Access to all resources in Agentverse` and click on `Generate API Key`
-
-
-
-## How to create Agents and respective Functions
-
- 1. Open terminal and create a directory `agents` using: `mkdir agents`.
- 2. Create two Python files, `agent.py` and `agent_create.py`, in this directory and include the following sample scripts within them. You can do this using:
-
-
-
- ```py copy filename="mac"
- touch agent.py
- ```
-
-
-
- ```py copy filename="windows"
- echo. > agent.py
- ```
-
-
-
- ```py copy filename="ubuntu"
- touch agent.py
- ```
-
-
-
-
-
- ```py copy filename="mac"
- touch agent_create.py
- ```
-
-
-
- ```py copy filename="windows"
- echo. > agent_create.py
- ```
-
-
-
- ```py copy filename="ubuntu"
- touch agent_create.py
- ```
-
-
-
- 3. Fill in the scripts with the code presented here below for each one of them:
-
-### Script 1: `agent.py`
-
-
-
-
-
-
-
- ```py copy filename="agent.py"
-
- import requests
- import json
- from ai_engine import UAgentResponse, UAgentResponseType
-
-
- class Coordinates(Model):
- location: str
-
-
- location_protocol = Protocol("Location Coordinates")
-
-
- async def location_coordinates(latitude, longitude):
- url = "https://geocoding-by-api-ninjas.p.rapidapi.com/v1/reversegeocoding"
- querystring = {"lat": latitude, "lon": longitude}
-
- headers = {
- "X-RapidAPI-Key": "YOUR_API_KEY",
- "X-RapidAPI-Host": "geocoding-by-api-ninjas.p.rapidapi.com"
- }
-
- response = requests.get(url, headers=headers, params=querystring)
-
- data = response.json()[0]['name']
-
- return data
-
-
- @location_protocol.on_message(model=Coordinates, replies=UAgentResponse)
- async def location_coordinates_calculator(ctx: Context, sender: str, msg: Coordinates):
- ctx.logger.info(msg.location)
- latitude, longitude = map(str.strip, msg.location.split(','))
- message = location_coordinates(latitude, longitude)
- ctx.logger.info(f"Location found: {message}")
- await ctx.send(sender, UAgentResponse(message=message, type=UAgentResponseType.FINAL))
-
-
- agent.include(location_protocol)
-
-```
-
-
-
-
-
-
-### Script 2: `agent_create.py`
-
-This script interacts with the Agentverse API to achieve the Agent and Function creation tasks.
-
-**Let's get started!**
-
-1. Import the required libraries and set up the authorization token:
-
- ```python
- # Importing Required libraries
- import time
- import requests
-
- # Define access token
- token = 'Bearer '
- ```
-
-2. Take the agent name from user and store the agent's address:
-
- ```python
- # Take name of agent from user
- name = input('Please give name of your agent? ')
-
- # Create payload for agent creation request
- agent_creation_data = {
- "name": name
- }
-
- # Post request to create an agent and store address
- response_agent = requests.post("https://agentverse.ai/v1/hosting/agents", json=agent_creation_data, headers={
- "Authorization": token
- }).json()
- address = response_agent['address']
- print(f'Agent Address : {address}')
- ```
-
-3. Take code from `agent.py` file. Then, store it in a dedicated script for the created agent:
-
- ```python
- # Reading code to be placed in agent
- with open('agent.py', 'r') as file:
- code = file.read()
- agent_code_data = {
- "code": code
- }
-
- # Creating agent.py script for created agent
- response_code_update = requests.put(f"https://agentverse.ai/v1/hosting/agents/{address}/code", json=agent_code_data, headers={
- "Authorization": token
- })
-
- # Starting the agent
- requests.post(f"https://agentverse.ai/v1/hosting/agents/{address}/start", headers={
- "Authorization": token
- })
-
- time.sleep(10) # waiting before getting agent's protocol
- ```
-
-4. Requesting protocol digest for the created Agent:
-
- ```python
- # Request to get agent protocol digest
- response_protcol = requests.get(f"https://agentverse.ai/v1/almanac/agents/{address}", headers={
- "Authorization": token
- })
- protocol_digest = response_protcol.json()['protocols'][1]
- print(f'Protocol Digest : {protocol_digest}')
-
- time.sleep(10) # Waiting before getting model_digest
- ```
-
-5. Request `Model` digest and name using Almanac APIs:
-
- ```python
- # Request to get agent's model details
- response_model = requests.get(f"https://agentverse.ai/v1/almanac/manifests/protocols/{protocol_digest}", headers={
- "Authorization": token
- })
- model = response_model.json()['models']
-
- time.sleep(10) # Waiting before storing details to create functions
- ```
-
-6. Now, save all the required details to create the Agent Function. Then, create the Agent Function on the basis of the details received:
-
- ```python
- # Taking inputs from user for details required to create a function
- name_function = input("Please give function name: ")
- description = input("Please enter function description: ")
- field_name = input("Please enter field name: ")
- field_description = input("Please enter field description: ")
- tasktype = input("Please tell primary or secondary function: ").upper()
-
- # Logging details provided by user
- print(
- f"Function name: {name_function} \nFunction Description: {description} \nField Name: {field_name}\nField Description: {field_description}\nTask Type: {tasktype}"
- )
-
- # Storing model digest and name to be used for function creation
- model_digest = response_model.json()["interactions"][0]["request"].replace("model:", "")
- print(f"Model Digest : {model_digest}")
- model_name = model[0]["schema"]["title"]
- print(f"Model Name : {model_name}")
-
- # Creating payload for function creation
- data = {
- "agent": address,
- "name": name_function,
- "description": description,
- "protocolDigest": protocol_digest,
- "modelDigest": model_digest,
- "modelName": model_name,
- "arguments": [
- {
- "name": field_name,
- "required": True,
- "type": "string",
- "description": field_description,
- }
- ],
- "type": tasktype,
- }
-
- # Requesting AI Engine function API to create a function with created payload and storing the response.
- response_function = requests.post(
- "https://agentverse.ai/v1beta1/functions/",
- json=data,
- headers={"Authorization": token},
- )
- # Storing name of function and printing it to check if function was created successfully
- name = response_function.json()["name"]
- print(f"Function Created with name: {name}")
- ```
-
-#### Complete Script
-
-
-
-
-
-
-
- ```py copy filename="agent_create.py"
-
- # Importing Required libraries
- import time
- import requests
-
- # Decode the refresh token
- token = f'Bearer '
-
- # Take name of agent from user
- name = input('Please give name of your agent? ')
- # Create payload for agent creation request
- agent_creation_data = {
- "name": name
- }
- # Post request to create an agent and store address
- response_agent = requests.post("https://agentverse.ai/v1/hosting/agents", json=agent_creation_data,
- headers={"Authorization": token}).json()
-
- address = response_agent['address']
- print(f'Agent Address : {address}')
-
- # Reading code to be placed in agent
- with open('agent.py', 'r') as file:
- code = file.read()
- agent_code_data = {
- "code": code
- }
-
- # Creating simple_function.py script for created agent
- response_code_update = requests.put(f"https://agentverse.ai/v1/hosting/agents/{address}/code", json=agent_code_data,
- headers={"Authorization": token})
-
- # Starting the agent
- requests.post(f"https://agentverse.ai/v1/hosting/agents/{address}/start", headers={"Authorization": token})
- time.sleep(10) # waiting before getting agent's protocol
-
- # Request to get agent protocol digest
- response_protcol = requests.get(f"https://agentverse.ai/v1/almanac/agents/{address}", headers={"Authorization": token})
- protocol_digest = response_protcol.json()['protocols'][1]
- print(f'Protocol Digest : {protocol_digest}')
- time.sleep(10) # Waiting before getting model_digest
-
- # Request to get agent's model details
- response_model = requests.get(f"https://agentverse.ai/v1/almanac/manifests/protocols/{protocol_digest}",
- headers={"Authorization": token})
- model = response_model.json()['models']
- time.sleep(10) # Waiting before storing details to create functions
-
- # Taking inputs from user for details required to create a function
- name_function = input("Please give function name: ")
- description = input("Please enter function description: ")
- field_name = input("Please enter field name: ")
- field_description = input("Please enter field description: ")
- tasktype = input("Please tell primary or secondary function: ").upper()
-
- # Logging details provided by user
- print(
- f"Function name: {name_function} \nFunction Description: {description} \nField Name: {field_name}\nField Description: {field_description}\nTask Type: {tasktype}"
- )
-
- # Storing model digest and name to be used for function creation
- model_digest = response_model.json()["interactions"][0]["request"].replace("model:", "")
- print(f"Model Digest : {model_digest}")
- model_name = model[0]["schema"]["title"]
- print(f"Model Name : {model_name}")
-
- # Creating payload for function creation
- data = {
- "agent": address,
- "name": name_function,
- "description": description,
- "protocolDigest": protocol_digest,
- "modelDigest": model_digest,
- "modelName": model_name,
- "arguments": [
- {
- "name": field_name,
- "required": True,
- "type": "string",
- "description": field_description,
- }
- ],
- "type": tasktype,
- }
-
- # Requesting AI Engine function API to create a function with created payload and storing the response.
- response_function = requests.post(
- "https://agentverse.ai/v1beta1/functions/",
- json=data,
- headers={"Authorization": token},
- )
- # Storing name of function and printing it to check if function was created successfully
- name = response_function.json()["name"]
- print(f"Function Created with name: {name}")
-
-```
-
-
-
-
-
-
-## Steps to run the script
-
-1. Open terminal and go to directory `agents` created above.
-2. Make sure `agent.py` and `agent_create.py` are in this directory.
-3. Head over to the [Agentverse ↗️](https://agentverse.ai/) and [generate API keys ↗️](#how-to-get-agentverse-api-tokens).
-4. Open script in editor and replace `token` field.
-5. Run command `python agent_create.py` and enter the required details.
-6. Provide Agent and Function details as asked, then, check agent and function on Agentverse.
-
-## Expected Output
-
-- Provide all details asked in the script:
-
- ```
- abc@xyz-MacBook-Pro agents % python3 agents_create.py
- Please give name of your agent? my first API agent
- Agent Address : agent1q06l8hekn859e5rtwufewmyhwghe6j9y00g0wc8u7gcx05cjfk98jyf6lte
- Protocol Digest : c7a6f160fd8d8b7cb357dad9b5be420510ce466dbb67051c07caf2b860216b01
- Please give function name: location finder
- Please enter function description: this function helps to find nearest city using coordinates
- Please enter field name: location
- Please enter field description: this describes the coordinates of the location in string format longitude latitude
- Please tell primary or secondary function: primary
- Function name: location finder
- Function Description: this function helps to find nearest city using coordinates
- Field Name: location
- Field Description: this describes the coordinates of the location in string format longitude latitude
- Task Type: PRIMARY
- Model Digest : 10a2f843c4c92955688d5e7f22fabe79623869eabfcd97d97da83527b436d3e2
- Model Name : Coordinates
- Function Created with name: location finder
- ```
-
-- Agent created on Agentverse:
-
-
-
-- Function created on Agentverse:
-
-
diff --git a/pages/guides/apis/secret-management-apis.mdx b/pages/guides/apis/secret-management-apis.mdx
deleted file mode 100644
index ec0f2db67..000000000
--- a/pages/guides/apis/secret-management-apis.mdx
+++ /dev/null
@@ -1,173 +0,0 @@
-import { Callout } from 'nextra/components'
-import { CodeGroup, CodeSegment, DocsCode, GithubCodeSegment } from "../../../components/code";
-
-# Adding Secret to Agents using Agentverse APIs
-
-## Introduction
-
-This guide provides details on how to use the [Agentverse hosting APIs ↗️](/apis/agentverse/hosting) to add a secret to an agent. **Secrets** are added to an agent to ensure they remain hidden from end users and to enhance security. Before you begin, ensure you satisfy the following pre-requisites:
-
- - Python version greater than 3.9 and less than 3.11.
- - The `requests` library installed. You can install it using `pip install requests`.
- - [Agentverse ↗️](https://agentverse.ai/) credentials.
-
-### Steps to get API Tokens
-
- - Go to **Profile** section in [Agentverse ↗️](https://agentverse.ai/).
- - Click on button `+ New API Key`.
- - Give name to your API key.
- - Click on `write` for `Access to all resources in Agentverse` and click on `Generate API Key`
-
-
-
-**Let's explore the script for this example!**
-
-## Script to add secret to agent
-
-1. Create a Python script and name it `agent_secret.py` using:
-
-
-
- ```py copy filename="mac"
- touch agent_secret.py
- ```
-
-
-
- ```py copy filename="windows"
- echo. > agent_secret.py
- ```
-
-
-
- ```py copy filename="ubuntu"
- touch agent_secret.py
- ```
-
-
-
-2. Within the script have just created, import the `requests` library:
-
- ```py
- # Importing libraries
- import requests
- ```
-
-3. Define the token variable with your Fauna access token:
-
- ```py
- # Decode the refresh token
- token = 'Bearer fauna_access_token'
- ```
-
-4. Now, input the agent's address, the name for the secret, and the value of the secret:
-
- ```py
- # Take name of agent and secret details from user
- address = input('Please enter address of agent to which you want to add the secret: ')
- name = input("Please enter name for your secret: ")
- secret = input("Please enter value for your secret: ")
- ```
-
-5. Create the payload for the POST request to add the secret:
-
- ```py
- # Create Payload for post request
- data = {
- 'address': address,
- 'name': name,
- 'secret': secret
- }
- ```
-
-6. Send the POST request to the Agentverse API to add the secret:
-
- ```py
- # Post request to add secret to agent
- response_agent = requests.post("https://agentverse.ai/v1/hosting/secrets", json=data, headers={"Authorization": token})
- ```
-
-7. Check if the response status code is 200 (success) and print an appropriate message:
-
- ```py
- # Check if the response code is 200
- if response_agent.status_code == 200:
- print("Secret added successfully.")
- else:
- print(f"Failed to add secret. Status code: {response_agent.status_code}")
- ```
-
-The full script should look as follows:
-
-
-
-
-
-
-
- ```py copy filename="agent_secret.py"
-
- # Importing libraries
- import requests
-
- # Decode the refresh token
- token = 'Bearer fauna_access_token'
-
- # Take name of agent and secret details from user
- address = input('Please enter address of agent to which you want to add the secret: ')
- name = input("Please enter name for your secret: ")
- secret = input("Please enter value for your secret: ")
-
- # Create Payload for post request
- data = {
- 'address': address,
- 'name': name,
- 'secret': secret
- }
-
- # Post request to add secret to agent
- response_agent = requests.post("https://agentverse.ai/v1/hosting/secrets", json=data, headers={"Authorization": token})
-
- # Check if the response code is 200
- if response_agent.status_code == 200:
- print("Secret added successfully.")
- else:
- print(f"Failed to add secret. Status code: {response_agent.status_code}")
-
-```
-
-
-
-
-
-
-## Steps to add secret to Agent using API
-
- - Navigate to th directory where `agent-secret.py` script is located using your terminal.
- - Open [Agentverse ↗️](https://agentverse.ai/) and [generate API keys ↗️](#how-to-get-agentverse-api-tokens).
- - Open script in editor and replace `fauna_access_token`.
- - Run `agent-secret.py` file using:
-
- `python agent-secret.py`
-
- - Provide agent's address, secret name and secret value.
- - Try using secret name in script instead of value, for example `APIKey` in our case.
-
-### Expected Output
-
-Provide details and response on basis of secret added or not to the Agent in Agentverse.
-
-
-
-
-
-
-
-
- We encourage everyone operating on DeltaV to select the **Next Generation** AI Engine personality type. This AI Engine personality stands as a significant personality type offering _enhanced scalability_, _reliability_, and _flexibility_. The major key features include advanced context understanding, improved function recommendations, and the ability to handle multiple dialogue formats.
-
diff --git a/pages/guides/fetch-network/_meta.json b/pages/guides/fetch-network/_meta.json
deleted file mode 100644
index 573060426..000000000
--- a/pages/guides/fetch-network/_meta.json
+++ /dev/null
@@ -1,51 +0,0 @@
-{
- "intro-fet-token": {
- "title": "Getting Started with FET token",
- "tags": ["Beginner", "Python", "FET"],
- "timestamp": true
- },
- "how-to-convert-fet-to-and-from-erc20": {
- "title": "How to convert native FET to and from ERC-20 FET",
- "tags": ["Intermediate", "Python", "FET"],
- "timestamp": true
- },
- "how-to-stake": {
- "title": "How to stake FET tokens",
- "tags": ["Intermediate", "Python", "FET"],
- "timestamp": true
- },
- "different-ways-to-stake-the-fet-token": {
- "title": "Different ways of staking FET",
- "tags": ["Intermediate", "Python", "Web3"],
- "timestamp": true
- },
- "re-delegating-staked-fet-token": {
- "title": "Re-delegating staked FET token",
- "tags": ["Intermediate", "Python", "FET"],
- "timestamp": true
- },
- "reconciliation-service": {
- "title": "Reconciliation service",
- "tags": ["Intermediate", "Python", "FET"],
- "timestamp": true
- },
- "ibc-transfers": {
- "title": "IBC CUDOS Tokens Transfer",
- "tags": ["Intermediate", "IBC", "CUDOS"],
- "timestamp": true
- },
- "aname-service": {
- "title": "ANAME Service",
- "tags": ["Intermediate", "Agents", "Domains", "ANAME"],
- "timestamp": true
- },
- "setting-up-a-multisig": {
- "title": "How to setup a Multisig Wallet",
- "tags": ["Intermediate", "Python", "Wallet"],
- "timestamp": true
- },
- "asi-wallet": "ASI Alliance Wallet",
- "cosmpy": "CosmPy",
- "jenesis": "Jenesis",
- "ledger": "Ledger"
-}
diff --git a/pages/guides/fetch-network/aname-service.mdx b/pages/guides/fetch-network/aname-service.mdx
deleted file mode 100644
index 818f7af62..000000000
--- a/pages/guides/fetch-network/aname-service.mdx
+++ /dev/null
@@ -1,89 +0,0 @@
-import { Callout } from 'nextra/components'
-
-ANAME Service
-
-# Agents Name Service
-
-## Overview
-
-A **domain** is a structured identifier that helps organize and address [Agents ↗️](/guides/agents/getting-started/whats-an-agent) within a network. It acts as a namespace, grouping Agents under a common label to make interactions more intuitive. In any Agent-based system, particularly in decentralized environments including the ASI network, Agents need a clear way to identify and communicate with each other. Instead of relying on long, complex addresses, domains provide a structured way to reference them.
-
-In a system where different applications or organizations manage multiple Agents, domains help distinguish their roles effortlessly. For instance, a transport-related Agent could belong to the `transport.agent` domain, while a financial Agent might operate under `finance.agent`. Within these domains, Agents have unique names, ensuring that they can be addressed correctly. An Agent named `bob-0.transport.agent` could be responsible for a smart mobility service, whereas `alice.weather.agent` might provide weather updates.
-
-Domains make Agents interactions more scalable and efficient by keeping their identities organized. As networks grow, having structured namespaces allows Agents to be categorized in a way that reduces confusion and improves communication. This structure also supports interoperability, enabling Agents from different domains to interact while maintaining distinct roles. By making it easier to discover and reference Agents, domains enhance both usability and system-wide coordination.
-
-## Agent Domains on the ASI Alliance Network
-
-It is possible to explore Agents domains on the ASI Alliance Network using the [Companion App ↗️](https://companion.fetch.ai/fetchhub-4/blocks). Open the App and connect your [ASI Alliance web ↗️](/guides/fetch-network/asi-wallet/web-wallet/get-started).
-
-
-
-Once you connect it successfully, you will need to click the **Connect Wallet** button in the top right corner and select **Domain** from the drop-down menu.
-
-
-
-You will be redirected to the **Domains** page.
-
-
-
-Here, you can either **_get a new domain_** for your Agents or **_explore already existing domains_** attached to your Agents.
-
-### Get a new domain
-
-In the **Domains** page, select the **Get a new domain** tab.
-
-Look for any domain you wish to buy and associate with an Agent by typing it in within the dedicated search bar (e.g., `billy.ai`). Once you click the **Check** button; a list of results will appear below showing all the results related to your search.
-
-A particular domain could have already been bought by another user and in that case it won't be available for purchase and marked as _Unavailable_. For any other available domain, check for the one you want to purchase and click the **Buy** button. A price in FET tokens per year will be displayed for each particular domain. The newly purchased domain is then associated and managed using the ASI Wallet Account you connected to the UI. This account becomes the **Administrator** of the domain, meaning that this account has full control over the domain's settings.
-
-
-
- An **Admin** has full control over domain settings, such as managing user roles and domain configurations, as well as performing tasks such as renewal and deletion of the domain itself. Admin permission is automatically granted to the account which purchased the domain in the first place. Once an administrator purchases a domain, it is possible to add all subdomains desired freely. Permissions within these subdomains are inherited from the top level domain permission configurations.
-
- On the other hand, a **Writer** account has limited access, primarily focused on registration of Agents into domains, without the ability to modify domain configurations or manage user roles. This permission level is assigned to users by the Admin account. Depending on the user's role, the UI will slightly change when it comes to domains' details exploration. If a user has no role being granted, then the user will just be able to check the domain's details, without the ability to perform any action.
-
-
-
-
-You will then be able to see all details related to the domain you have chosen.
-
-
-
-To complete the purchase, you must click **Confirm**, which will process the transaction on-chain. If you decide not to proceed, selecting **Cancel** will close the window without making any changes. If you go on with the purchase, you will need to **Approve** the transaction within your ASI Web Wallet pop-up window.
-
-
-
-After successful confirmation, the domain will be linked to your account, allowing you to use it as a recognizable identifier for your Agent. Remember that **you will need to renew the domain annually to maintain ownership!**
-
-### Explore your domains
-
-In the **Domains** page, select the **My domains** tab.
-
-
-
-You will be able to see a full list of all domains you previously purchased and that are associated with the address of the ASI Wallet you connected to the Companion App UI. Each Domain has multiple information, including:
-
-- **Subdomains**: The number of subdomains associated with the domain.
-- **Domain/Agent mappings**: How many mappings are set up between agents and the domain.
-- **Expiration**: Helps to monitor this to renew domains before they expire.
-- **Role**: It is the user's role associated with the domain based on permissions levels. We can distinguish 2 permission levels: _Admin_ and _Writer_.
-
-If you click on one of your domains, you will be able to explore the particular domain's details:
-
-#### Administrator permissions
-
-**_If you have Admin permissions_** then you will be in full control of that particular domain configuration.
-
- 
-
-You will be able to explore the details of that specific domain (e.g., `billy.helper`), including the Agents mapped towards it, the subdomains and weights in case Agents share the same domain. You can also explore **Permissions** within the dedicated section and add an Admin or a Writer account to the domain itself. You can edit or remove permissions by clicking the dedicated buttons for each permission granted.
-
-You are also able to add a particular Agent, using its address, to the domain by using the **Connect an Agent** section. You will need to provide the Agent Address and assign a weight to determine selection priority if multiple Agents share the same exact domain, with higher values indicating priority. You can optionally specify a subdomain (e.g., `foo.billy.helper`). Once you are satisfied, click **Add** to register the Agents and map it to that domain. Once an Agent is mapped to the domain, you can click the pencil icon to edit an existing Agent mapping, or, you can click the crossed-out link icon to remove an Agent's association with the domain:
-
- 
-
-#### Writer permissions
-
-**_If you have Writer permissions_**, then you will be just able to add/edit Agents mapped to that specific domain. It is at this point that the benefit of having Writer permission comes into play as this permission allows all manipulation with Agents and mapping to the domain. This is particularly helpful whenever you need someone to handle day-to-day registration of Agents into a particular domain configuration.
-
-
diff --git a/pages/guides/fetch-network/asi-wallet/_meta.json b/pages/guides/fetch-network/asi-wallet/_meta.json
deleted file mode 100644
index f64ad455f..000000000
--- a/pages/guides/fetch-network/asi-wallet/_meta.json
+++ /dev/null
@@ -1,21 +0,0 @@
-{
- "web-wallet": {
- "title": "Web Wallet",
- "tags": ["ASIAllianceWallet", "Web", "Wallet"]
- },
- "mobile-wallet": {
- "title": "Mobile Wallet",
- "tags": ["ASIAllianceWallet", "Mobile", "Wallet"],
- "timestamp": true
- },
- "asi-wallet-hardware-connection-guide": {
- "title": "Install ASI Alliance browser extension wallet with Ledger hardware wallet",
- "tags": ["Beginner", "Python", "Wallet"],
- "timestamp": true
- },
- "companion-app": {
- "title": "ASI Wallet Companion App",
- "tags": ["Intermediate", "Companion App"],
- "timestamp": true
- }
-}
diff --git a/pages/guides/fetch-network/asi-wallet/asi-wallet-hardware-connection-guide.mdx b/pages/guides/fetch-network/asi-wallet/asi-wallet-hardware-connection-guide.mdx
deleted file mode 100644
index 131a6dd74..000000000
--- a/pages/guides/fetch-network/asi-wallet/asi-wallet-hardware-connection-guide.mdx
+++ /dev/null
@@ -1,38 +0,0 @@
-# Setting up the ASI Alliance extension wallet with a Ledger hardware wallet
-
-If you own a Ledger hardware wallet and wish to enhance the security and functionality of your crypto assets, follow these steps to set up and perform your first transaction using the Fetch.ai browser extension wallet in combination with a ledger device.
-
-1. **Download and install the ASI Alliance browser extension wallet.**
-
- Visit the official website: [ASI Alliance Wallet ↗️](https://fetch.ai/get-fetch-wallet). Follow the installation prompts to seamlessly integrate the extension into your browser.
- The wallet is supported on Chrome, Brave and Firefox.
-
-2. **Plug in your ledger and open the Ledger Live software.**
-
- Connect your ledger hardware wallet to your computer using the supplied USB cable. Launch the Ledger Live software if it's not already running. Ensure that your Ledger device is properly connected and recognized by Ledger Live.
-
-3. **Download and install the Cosmos app.**
-
- Inside the Ledger Live software, navigate to the "Manager" section.
- Search for "Cosmos" or "ATOM" within the app catalog. Click on the Cosmos app, and then follow the on-screen instructions to install it onto your Ledger device.
-
-4. **Create a Cosmos address.**
-
- If you don't already possess a Cosmos (ATOM) address, you can easily create one through Ledger Live. This is a mandatory step as Fetch is a cosmos-sdk based chain. In Ledger Live, access the "Accounts" section and choose "Add Account." Select "Cosmos" as the cryptocurrency and follow the prompts to generate a new Cosmos address.
-
-5. **Open ASI Alliance browser Extension Wallet and Connect Ledger.**
-
- Launch the ASI Alliance browser extension wallet by clicking on its icon located in your browser's toolbar.
- Locate and click the "Connect Ledger" option.
- - For first-time setup, choose "Connect Ledger" at the beginning of the wallet setup.
- - If you already possess a ASI Alliance wallet, navigate to the "Accounts" tab in the upper right corner and create a new account by selecting the "Connect Ledger" option.
-
- Once you've connected, ensure the cosmos app is open on your ledger.
-
-6. **Create a test transaction and sign it with the Ledger.**
-
-To confirm that your Ledger hardware wallet is correctly linked to the ASI Alliance extension wallet, initiate a test transaction with a minimal amount of FET. Within the ASI Alliance extension wallet, access the **Send** section.
-
-Enter the recipient's address and specify the amount for the test transaction. Carefully follow the on-screen instructions to verify and sign the transaction using your Ledger device.
-
-Review the transaction details on your Ledger device, and once satisfied, approve it. Wait for the transaction to process and gain confirmation. You can monitor its status within the ASI Alliance extension wallet or explore it further on a blockchain explorer such as [Mintscan ↗️](https://www.mintscan.io/fetchai).
diff --git a/pages/guides/fetch-network/asi-wallet/companion-app.mdx b/pages/guides/fetch-network/asi-wallet/companion-app.mdx
deleted file mode 100644
index 81df93d22..000000000
--- a/pages/guides/fetch-network/asi-wallet/companion-app.mdx
+++ /dev/null
@@ -1,287 +0,0 @@
-# ASI Wallet Companion App
-
-## Introduction
-
-Within the ASI Network, an essential tool is the **Companion App** which works similarly to any block explorer, thus offering the opportunity for users to navigate and analyze the Fetch.ai blockchain network data and related information.
-
-You can access the Companion App [here ↗️](https://companion.fetch.ai/fetchhub-4/blocks).
-
-Overall, an explorer provides a user-friendly interface for viewing and tracking on-chain activities, including transactions, blocks, smart contracts, wallet addresses and so on. By allowing users to search for and verify blockchain data, a block explorer serves as an essential resource for developers, researchers, and anyone looking to understand the workings of a blockchain ecosystem.
-
-## Companion App Functionalities
-
-### Blocks Page
-
-The **Blocks** page of the Companion App UI provides a detailed breakdown of each specific block, making it easy for users to analyze individual transactions and understand the context of on-chain activities. It is useful for developers, network validators, and anyone looking to verify or trace transactions on the blockchain.
-
-
-
-The Block Summary provides a high-level overview of recent network activity, including:
-
-- **Block Height**: it indicates the latest block number on the blockchain.
-- **Block Count (last 24h)**: it shows the number of blocks created in the past 24 hours.
-- **Transaction Count (last 24h)**: it displays the total number of transactions processed in the last 24 hours.
-- **Block Time**: it is the average time it takes to create a new block, measured in seconds.
-
-On the other hand, the _Recent Blocks_ section provides a table that lists the most recent blocks added to the blockchain, thus making it easy for users to track historical block data. The page offers multiple data details, including:
-
-- **Block Number (Hash)**: it displays the unique block number and its associated hash. Clicking on the block number or hash may lead to a detailed block view.
-- **Created At**: it is the timestamp when the block was created, along with how long ago it occurred.
-- **Proposer**: it is the validator that proposed the block. Validators' names (e.g., Kiln, Altruistic Automaton, Blockscope.net) are shown alongside their icons or logos.
-- **Transaction Count (Tx count)**: it is the number of transactions included within each block.
-
-You can click on a specific Block, you can enter the _Block Details_ page. This page provides in-depth information about the specific block on the blockchain:
-
-
-
-Here, you can explore multiple information about the specific Block you choose, including:
-
-- **Block Height**: it indicates the block's position in the blockchain.
-- **Block Time**: it displays the time the block was created, with the timestamp and time elapsed. It also indicates if the block time is Expected or otherwise.
-- **Proposer**: it is the validator who proposed the block which is shown with a corresponding logo or icon.
-- **Transaction Count (Tx counts)**: it is the number of transactions included in the block.
-- **Gas Used / Wanted**: it is the amount of gas used by the block's transactions compared to the total gas available.
-- **Hash**: it is the unique hash representing the block, which you can copy if needed.
-
-In the _Transactions Section_, you have an overview of all details related to all transactions included in that specific block, including:
-
-- **Transaction Hash (Tx hash)**: it is the unique identifier for each transaction. Clicking on the hash leads to a detailed transaction view.
-- **Time**: it is the timestamp when the transaction was included in the block.
-- **Result**: it is the status of the transaction.
-- **Messages**: it describes the action taken.
-- **Height**: it is the block height where the transaction is recorded.
-
-### Transactions Page
-
-The **Transactions** page provides a comprehensive view of the transactions activity on the Network. It allows users to monitor recent transactions, assess network activity over different time periods, and verify individual transaction details.
-
-
-
-Then _Transactions Summary Section_ provides an overview of the transaction statistics:
-
-- **Total Transactions**: it is the cumulative number of transactions processed on the network.
-- **Transactions (last 30 days)**: Number of transactions processed over the past 30 days.
-- **Transactions (yesterday)**: Transactions that occurred on the previous day.
-- **TPS (Last 20 blocks)**: it is the average Transactions Per Second (TPS) calculated based on the most recent 20 blocks.
-
-Within the Transactions table, you have a view of each individual transactions with the following details:
-
-- **Transaction Hash (Tx hash)**: It is the unique identifier for each transaction.
-- **Time**: it is the time at which the transaction was processed.
-- **Result**: it shows the status of the transaction.
-- **Messages**: it indicates the type of action performed.
-- **Height**: it indicates the block height in which the transaction was included.
-
-By clicking on the _Transaction Hash_, you will be redirected to the _Transaction Details_ page where you will be able to find all needed information about that specific transaction, as shown below:
-
-
-
-### Accounts Page
-
-The **Accounts** Summary page provides an overview of account data, including:
-
-- **Daily Active Accounts**: the number of accounts that were active in the last 24 hours.
-- **Monthly Active Accounts**: the amount of accounts active in the past month.
-- **90d Active Accounts**: the total number of accounts active in the last 90 days.
-
-
-
-You can choose among multiple options to explore **Accounts**: _Rich List_, _Most Activators_ and _Trends_. Within the _**Rich List**_ option, you can view the top accounts ranked by their FET holdings with the multiple details, including the Accounts Address and amounts of FET being held by each account.
-
-The _**Most Activators**_ tab displays the top accounts ranked by their transaction activity, and provides information about the total number of transactions initiated by each account.
-
-On the other hand, the _**Trends**_ tab provides an interactive visualization of Accounts activity over time, thus offering insights into the dynamics of user engagement within the network. This helps to identify patterns (e.g., growth or decline in activity levels), and assist stakeholders in enhancing their understanding of user engagement on the network over time.
-
-### Agents Page
-
-The **Agents** page provides a comprehensive overview of the [Agents ↗️](/guides/agents/getting-started/whats-an-agent) currently active on the ASI Network. Agents are autonomous entities that can interact with each other and the broader digital economy. They play a crucial role in enabling decentralized applications and services.
-
-
-
-On this page, you can find valuable information about the Agents available on the Network, including:
-
-- **Total Agents**: this is the total amount of Agents being registered on the Network.
-- **Active Registrations**: this is the number of Agents being currently active.
-- **Protocols**: the overall amount of [Protocols ↗️](/guides/agents/intermediate/protocols) being in use within the Network.
-- **Domains**: it is the number of Agents Domains being registered on the Network.
-
-The pie chart offers a visual representation of the distribution of Agents based on their domain ownership and registration status.
-
-By selecting a specific Agent, and by clicking on a specific Agent Address, you will be redirected to the Agents Details page:
-
-
-
-Here, you are able to explore multiple details about any Agent, including the following:
-
-- **Agent Address**: the unique address of the Agent.
-- **Almanac Registration**: the current status of the Agent's registration in the [Almanac Contract ↗️](/references/contracts/uagents-almanac/almanac-overview).
-- **Registration time** and **expiry date**.
-
-In this page, you are also able to check for **Protocols** and **Domains** related to that particular Agent.
-
-To learn more about how to create and manage Agents, check out our [documentation ↗️](https://fetch.ai/docs/) and Agent guides. By understanding Agents, you can unlock the full potential of the ASI Network and build innovative decentralized applications.
-
-### Validators Page
-
-The **Validators** page of the Companion App UI provides an overview of the blockchain's validators, helping users analyze their performance, participation, and overall contribution to network security. It is particularly useful for delegators, network participants, and developers who want to track validators' statistics.
-
-#### Validators Summary
-
-
-
-The **Validators Summary** section offers a high-level breakdown of validator activity, including:
-
-- **Active / Allocated Validators**: Displays the number of currently active validators compared to the total in the network.
-- **Onchain APR**: Shows the current annual percentage rate (APR) for staking rewards.
-- **Bonded Rate**: Shows the percentage of total staked tokens relative to the total supply.
-- **Avg. / weighted Commission**: Highlights the average commission rates taken by validators.
-
-Once you connect your [ASI Wallet ↗️](/guides/fetch-network/asi-wallet/web-wallet/get-started) to the Companion App UI, you will be able to see the refreshed table for Validators based on your Stakes amount:
-
-
-
-The **Validators Table** provides a detailed list of active validators with key metrics, including:
-
-- **Rank**: Indicates the validator’s ranking based on voting power.
-- **Validator**: Displays the validator's name, logo, and identity.
-- **Voting Power**: Shows the total stake delegated to the validator, representing their influence in consensus.
-- **Commission**: Displays the fee percentage charged by the validator on delegated rewards.
-- **Uptime & Missed Blocks**: Highlights validator reliability, showing uptime percentage and recent missed blocks.
-- **Participation**: Measures how actively the validator participates in the network.
-- **Delegators**: The number of users delegating stakes to each specific validator.
-- **Stake**: Amount payable to stake with a specific validator.
-
-Each validator has a menu (... button) allowing users to manage their stakes:
-
-- **Stake**: Delegate FET tokens to the selected validator.
-- **Unstake**: Withdraw staked tokens from the validator.
-- **Claim Rewards**: Collect earned staking rewards.
-
-#### Validators Details
-
-Users can click on a specific validator to access the **Validator Details** Page, which provides an in-depth view of their performance and activity.
-
-
-
-This page offers comprehensive information about a selected validator, including:
-
-- **Validator details**: Shows the validator's name, logo, address, description and related website.
-- **Voting Power**: Displays the validator's total stake and percentage of total network stake.
-- **Commission Rate**: Shows the fee structure for delegators.
-- **Expected APR**: Estimated annual percentage rate.
-- **Delegators**: the number of delegators supporting the validator and their respective stakes.
-- **Uptime History**: Provides a % indicating the validator's reliability and availability performance.
-- **Bonded Tokens**: Indicated the total delegated stake.
-- **Self Bonded Tokens**: It is the amount staked by the validator itself.
-- **Start Height**: Indicates the block number at which the validator first became active on the network.
-- **Uptime / Block Miss**: Uptime refers to the validator's availability and reliability in signing and proposing blocks. Block Miss stands as the number of blocks the validator failed to sign or propose within a given tracking period. The relationship between these two values indicates the amount of blocks being missed overall and stands as a measure of reliability into the specific validator.
-- **Window Block Miss**: It is the number of missed blocks in the current tracking window.
-
-Within the Validator's _Details_ page, users can interact with the specific validator through the dedicated buttons available in the UI:
-
-- **Claim rewards**: Collect earned staking rewards.
-- **Redelegate**: Transfer staked tokens to another validator without unstaking first.
-- **Unstake**: Withdraw FET tokens from the validator.
-- **Stake**: Delegate FET tokens to this validator.
-
-##### Proposed Blocks tab
-
-
-
-Within the **Proposed Blocks** tab available at the bottom of the validator's Details page, users are able to see a list of blocks that this validator has proposed as part of its role in the network. Here, you can explore the following information:
-
-- **Height**: The block number in the blockchain. Higher number means a more recent block.
-- **Block Hash**: It is the unique cryptographic identifier for the block.
-- **Tx Count (Transaction Count)**: The number of transactions included in the block. Higher transaction counts indicate active participation in processing transactions.
-- **Created At**: The timestamp when the block was proposed.
-
-These details and information helps users track if the validator is actively participating in block proposals, ensuring its reliability and trustworthiness.
-
-##### Power Events tab
-
-
-
-The **Power Events** tab provides a historical record of events that have impacted the validator's voting power. Users can check the following information within this tab:
-
-- **Height**: This refers to the block height at which the power event occurred. It essentially pinpoints the event's location within the blockchain's timeline.
-- **Tx Hash**: This is the unique transaction hash associated with the power event. You can click on it to view the transaction details on the explorer.
-- **Amount**: This indicates the change in the validator's voting power. A positive value signifies an increase in power, while a negative value represents a decrease.
-- **Time**: This is the timestamp of when the power event occurred.
-
-##### Delegators tab
-
-
-
-Lastly, within the **Delegators** tab, users can check out the information about those users who have delegated their tokens to the selected validator, including:
-
-- **Delegator**: This column lists the addresses of the users who have delegated their tokens to the validator.
-- **Amount**: This column indicates the amount of tokens each delegator has staked with the validator.
-- **Updated At**: This column shows the timestamp of when the delegation was last updated.
-
-
-##### Claim rewards, Redelegate, Unstake and Stake
-
-Within each specific validator's details page, users have the options to manage rewards as well as staked/delegated tokens to that particular validator. They can do this by clicking on the dedicated buttons: **Claim rewards**, **Redelegate**, **Unstake** and **Stake**.
-
-
-
-For instance, by clicking the **Stake** button, a side panel will appear showing you different data about the Stake operation:
-
-
-
-This way, you can directly stake FET tokens with the validator of your choice. You will need to provide the Amount of tokens you wish to stake as well as the name of the Validator you want to stake your tokens with. You can also add a _memo_ field for information you wish to add to the transaction. Once you are satisfied, click on the **Stake** button. You will see a summary showing up for the operation. Then, click on **Confirm** and **Approve** the transaction within your ASI Wallet.
-
-### Proposals Page
-
-The **Proposals** page of the Companion App UI provides an overview of the Governance Proposals taking place within the ASI network.
-
-
-
-This page allows users to check out the total number of proposals, their status, and voting outcomes. Users can track past proposals along with their approval or rejection status. The page helps ensure transparency in network governance and allows users to stay informed about decisions affecting the ASI ecosystem.
-
-#### Proposals summary and details
-
-
-
-The **Proposals Summary** page provides an overview of all Proposals. It displays the Total amount of Proposals and current available ones under Voting Period Proposals. This page provides multiple details for each governance proposal:
-
-- Proposal ID
-- Title
-- Type
-- Your Vote
-- Status
-- Voting End On
-
-By switching **My Votes** toogle on, you will be able to filter proposals and see just those for which you voted previously.
-By clicking on a particular proposal, you will be able to explore additional details through the **Proposal Details** page:
-
-
-
-Through the details page, users are able to explore in a more detailed manner all the aspects of a specific proposal, starting with actual votes, voting details and description. You can check out the proposal's description at the bottom within the **Description** section:
-
-
-
-Instead, by clicking on the **Json** tab, you will be able to explore the Proposal's details in json format:
-
-
-
-#### How to vote for Proposals
-
-Whenever you wish to participate in a Governance Proposals voting, you will need to open the related Proposal's details page by clicking on the Proposal itself within the Proposals page in the Companion App. Once you open the proposal's details page, if the proposal voting period hasn't still ended, then you should be able to see a **Vote** button at the top of the page:
-
-
-
-By clicking on this one, a drop-down menu will appear with multiple options:
-
-
-
-By selecting one of the voting options displayed, you will have your vote being registered and the UI will refresh. You should be able to see something similar to the following:
-
-
-
-
-### Reconciliation Page
-
-The **Reconciliation Service** enables users with Hardware Wallets to recover funds migrated from the Fetch Staking platform on Ethereum to the Fetch Mainnet. By linking their ASI [Alliance Wallet ↗️](/guides/fetch-network/asi-wallet/web-wallet/get-started) and Metamask, users can securely associate their Ethereum staking address with a Fetch recovery address to restore access to their tokens. Within this tab you can also access the **CUDOS Tokens Transfer** UI if you have either Locked or Convertible CUDOS Tokens in your wallet.
-
-You can access these services via the [Companion App ↗️](https://companion.fetch.ai/fetchhub-4/reconciliation) and follow the steps provided. For a detailed overview, see the [Reconciliation ↗️](/guides/fetch-network/reconciliation-service) or the [IBC CUDOS Tokens Transfers ↗️](/guides/fetch-network/ibc-transfers) guides for a better understanding.
diff --git a/pages/guides/fetch-network/asi-wallet/mobile-wallet/_meta.json b/pages/guides/fetch-network/asi-wallet/mobile-wallet/_meta.json
deleted file mode 100644
index 8e0ff8d62..000000000
--- a/pages/guides/fetch-network/asi-wallet/mobile-wallet/_meta.json
+++ /dev/null
@@ -1,42 +0,0 @@
-{
- "get-started": {
- "title": "Getting started",
- "tags": ["ASIAllianceWallet", "Mobile", "Wallet"],
- "timestamp": true
- },
- "home-screen": {
- "title": "Feature 1: Home Screen",
- "tags": ["ASIAllianceWallet", "Mobile", "Home", "Wallet"],
- "timestamp": true
- },
- "stake": {
- "title": "Feature 2: Stake",
- "tags": ["ASIAllianceWallet", "Mobile", "Staking", "Wallet"],
- "timestamp": true
- },
- "send-receive": {
- "title": "Feature 3: Send and Receive functions",
- "tags": ["ASIAllianceWallet", "Mobile", "Send", "Receive", "Wallet"],
- "timestamp": true
- },
- "activity": {
- "title": "Feature 4: Activity",
- "tags": ["ASIAllianceWallet", "Mobile", "Activity", "Wallet"],
- "timestamp": true
- },
- "more": {
- "title": "Feature 5: More options",
- "tags": ["ASIAllianceWallet", "Mobile", "Wallet"],
- "timestamp": true
- },
- "gov-proposal": {
- "title": "Feature 6: Gov Proposal",
- "tags": ["ASIAllianceWallet", "Mobile", "Gov Proposal", "Wallet"],
- "timestamp": true
- },
- "ledger-guide": {
- "title": "Feature 7: Ledger Guide",
- "tags": ["ASIAllianceWallet", "Web", "Ledger Guide", "Wallet"],
- "timestamp": true
- }
-}
diff --git a/pages/guides/fetch-network/asi-wallet/mobile-wallet/activity.mdx b/pages/guides/fetch-network/asi-wallet/mobile-wallet/activity.mdx
deleted file mode 100644
index 837a2f7da..000000000
--- a/pages/guides/fetch-network/asi-wallet/mobile-wallet/activity.mdx
+++ /dev/null
@@ -1,15 +0,0 @@
-# How to use ASI Alliance Wallet
-
-## Feature 4 - Activity
-
-This page allows users to delve into activity undertaken with the wallet, encompassing transfers, staking, re-delegation and overall interactions. You can check your activity following these steps:
-
- - Open ASI Alliance Wallet Dashboard.
- - Navigate to **Activity Tab**.
-
-|  |  |
-|--------------------------------------------------------|--------------------------------------------------------|
-
- - Clicking on any of the activity navigate to the detail page.
-
-
diff --git a/pages/guides/fetch-network/asi-wallet/mobile-wallet/get-started.mdx b/pages/guides/fetch-network/asi-wallet/mobile-wallet/get-started.mdx
deleted file mode 100644
index ea0301d89..000000000
--- a/pages/guides/fetch-network/asi-wallet/mobile-wallet/get-started.mdx
+++ /dev/null
@@ -1,121 +0,0 @@
-# ASI Alliance Wallet
-
-## Installation
-
- 1. Install the **ASI Alliance Wallet** app on your device. This wallet is compatible with all Android and iOS versions. You can find it by searching for **ASI Alliance Wallet** on the **Google Play Store** or the **App Store**, or by using the following link:
- - [Play Store](https://play.google.com/store/apps/details?id=com.fetchai.wallet)
- - [App Store](https://apps.apple.com/in/app/fetch-ai-wallet/id1641087356)
-
-
-
-
-## On Boarding
-
-Launch the ASI Alliance Wallet app, and you will see 2 options:
- - Create a new wallet
- - Import a wallet
-
-
-
-### Create a new Wallet
-
-By choosing this option, you will have to choose across multiple options as shown below:
-
-
-
-**Note**: Continue with Apple only available in iOS devices.
-
-#### Continue with Google
-
- 1. Choose **Continue with Google**.
- 2. Pick the Google account you wish to use for continuing with this Fetch account.
-
-#### Create New seed phrase
-
-By choosing this option, you will be provided with a mnemonic seed phrase. Make sure to securely backup your mnemonic seed in a safe place.
-
-
-
-You will be then asked to confirm the seed phrase. To confirm your mnemonic seed, reorder the mnemonic phrases by clicking on them in the proper sequence.
-
-
-
-Last, you will need to provide a **Name** and **Password** for your account. The next time you wish to use the wallet or make significant changes to your account, this password will be required.
-
-
-
-All ready! You now have everything set to begin your ASI Alliance Wallet journey.
-
-
-
-### Import a wallet
-
-By choosing this option will be asked to choose across the following options:
-
-
-
-#### Import From ASI Alliance extension
-
- 1. Whenever a user accesses the mobile app and already has an account created on the web extension, they can utilise the **Import from ASI Alliance extension** function to access all their extension accounts on their phone.
-
-
-
- 2. To do this, the user needs to navigate to:
-
- 1. The **hamburger menu** on the web extension, select **Settings**.
- 2. Then, choose **Link ASI Alliance Wallet**.
- 3. After entering the password, they can scan the barcode to link all their accounts from the web extension to the mobile app.
-
-
-
-#### Use a seed phrase or a private key
-
- 1. When a user opens the mobile app and already has an account created on the web extension, they can import their existing account into the mobile app.
- 2. Using **Mnemonic Seed** or **Private Key**. The user can choose to import their account by pasting the mnemonic seed (12 or 24 words) or the private key.
-
-
-
- 3. And additionally, they can input the name of the account and set a password for it.
-
-
-
- 4. After completing the import process and providing necessary details, the user's existing account is successfully set up and ready to use in the mobile app.
-
-
-
-#### Connect Ledger
-
-If you use the ASI Alliance Wallet together with a Ledger hardware wallet and want to retain your key and mnemonics there.
-
- 1. Select **Connect ledger**.
- 2. Set a password for your account and give it a name. The next time you wish to use the wallet or make significant changes to your account, this password will be required.
-[Click here for More Details](/guides/fetch-network/asi-wallet/mobile-wallet/ledger-guide)
-
-
-
-#### Migrate from ETH
-
- 1. Select **Migrate from ETH**.
- 2. On the next page, click **Migrate a Meta mask Private Key**.
-
-
-
- 3. After that, You will then be taken to the main import screen, where you can name the key, specify the **ETH address** you are migrating from, which in this case is your Meta mask ETH address (this is used to ensure that the private key matches), and finally copy the private key from your Meta mask account.
-
-
-
- 4. If this is your first key in the wallet, you will be prompted to create a global password for your wallet. The password will be required the next time you use the wallet or make changes to your account.
-
- 5. After completing the import process and providing necessary details, the user's existing account is successfully set up and ready to use in the mobile app.
-
-
-
diff --git a/pages/guides/fetch-network/asi-wallet/mobile-wallet/gov-proposal.mdx b/pages/guides/fetch-network/asi-wallet/mobile-wallet/gov-proposal.mdx
deleted file mode 100644
index 837d55d01..000000000
--- a/pages/guides/fetch-network/asi-wallet/mobile-wallet/gov-proposal.mdx
+++ /dev/null
@@ -1,18 +0,0 @@
-# How to use ASI Alliance Wallet
-
-## Feature - Gov Proposal
-
-Governance proposal is a system for managing and implementing changes to cryptocurrency blockchains. In this type of governance, voting systems for instituting changes are programmed into the blockchain. Developers propose changes, and each stakeholder votes on whether to accept or reject the proposed change. Blockchain stakeholders might be developers, validators, token holders, or anyone else the blockchain is designed to include.
-
- - Open ASI Alliance Wallet Dashboard.
- - Navigate to **More Tab**.
- - Look for and select the **Proposals** option.
-
-|  |  |
-|--------------------------------------------------------|--------------------------------------------------------|
-
- - Clicking on any proposal navigates the user to the detail page.
- - The detail page provides all the necessary information about the proposal.
- - Users can vote or change their vote if the proposal is in an active status.
-
-
diff --git a/pages/guides/fetch-network/asi-wallet/mobile-wallet/home-screen.mdx b/pages/guides/fetch-network/asi-wallet/mobile-wallet/home-screen.mdx
deleted file mode 100644
index 23ba511e3..000000000
--- a/pages/guides/fetch-network/asi-wallet/mobile-wallet/home-screen.mdx
+++ /dev/null
@@ -1,102 +0,0 @@
-# How to use ASI Alliance Wallet
-
-## Feature 1 - Dashboard
-
-When a user opens the mobile app for the first time, they are presented with the **Account Dashboard**.
-
-
-
-Let's explore the Dashboard features below.
-
-### Dashboard Features
-
-#### Network Selector Option
-
-By clicking on **Network Selector** button, the user can change the network.
-
-|  |  |
-|--------------------------------------------------------|--------------------------------------------------------|
-
-#### Scanner Button
-
-Clicking on the scanner button allows the user to scan **QR codes** of other accounts for transactions.
-
-|  |  |
-|--------------------------------------------------------|--------------------------------------------------------|
-
-#### Chat Button
-
-**This feature is upcoming and not available yet**. Through this feature, users will be able to communicate with other users and Agents registered register on the network. Users can chat with autonomous agent to ask questions and perform wallet functions.
-
-
-
-#### Copy Address
-
-By clicking on **Copy**, the user can copy their account's address.
-
-
-
-#### Three Dots (More Options)
-
-You can access more functions and options by clicking on the 3 dots symbol as shown below:
-
-
-
-##### Add New Account
-
-Allows the user to create a new account, as described earlier.
-
-
-
-##### Change Account
-
-If the user has multiple accounts, they can switch between them here.
-
-
-
-##### Rename Account
-
-Enables the user to change the name of their account.
-
-
-
-##### Delete Wallet
-
-This provides the option to delete a wallet/account.
-
-|  |  |
-|--------------------------------------------------------|--------------------------------------------------------|
-
-User can also backup their mnemonic seed of account before deleting it by using this functionality.
-
-|  |  |
-|--------------------------------------------------------|--------------------------------------------------------|
-
-### Viewing Account Information
-
-#### Current Balance
-
-The user can see their current balance in FET (Fetch tokens) and in USD.
-
-
-
-#### Portfolio
-
-By clicking on the **View Portfolio** button, users can view their portfolio's performance over time as well as its composition.
-
-|  |  |
-|--------------------------------------------------------|--------------------------------------------------------|
-
-Clicking on any **Token tab** would redirect users to the related token detail page.
-
-
-
-**Stats** tab displays the staking information.
-
-
-
-#### Portfolio Performance
-
-In the Home screen, the user can track their portfolio performance over various timeframes (from 24 hours to 1 year).
-
-
diff --git a/pages/guides/fetch-network/asi-wallet/mobile-wallet/ledger-guide.mdx b/pages/guides/fetch-network/asi-wallet/mobile-wallet/ledger-guide.mdx
deleted file mode 100644
index 7f4aa5010..000000000
--- a/pages/guides/fetch-network/asi-wallet/mobile-wallet/ledger-guide.mdx
+++ /dev/null
@@ -1,51 +0,0 @@
-# Steps to Connect Ledger Hardware Wallet via Bluetooth
-
-## Feature 7 - Ledger Guide
-
-### Step 1 : Navigate to the Register Screen
-
- - Open the app and go to the **Home** screen.
- - Tap the three-dot icon and select **Add New Wallet**.
-
- # 
-
-> **Note** : New users will be automatically redirected to the **Register** screen.
-
-
-### Step 2 : Select Import a Wallet
- - On the Register screen, tap **Import a Wallet**.
- - Choose **Connect Hardware Wallet** and fill in the required information.
-
-|  |  |
-|--------------------------------------------------------|--------------------------------------------------------|
-
-### Step 3 : Enable Bluetooth & Location (If Required)
-Depending on your device type, follow these instructions :
-##### ***For iOS Users*** :
- - Navigate to **Settings > Bluetooth**.
- - Enable Bluetooth and **allow new connections**.
-
-##### **For Android Users** :
- - Navigate to **Settings > Bluetooth** or **Location**.
- - Enable Bluetooth and Location, then **allow new connections**.
-
- |  |  |
- |--------------------------------------------------------|--------------------------------------------------------|
-
-### Step 4 : Connect Ledger Device
- - Tap **Continue** on the app. A pop-up will appear.
- - The app will prompt you to:
- - **Unlock your Ledger device**.
- - **Open the Cosmos app** on the Ledger device.
- - Once detected, the app will display Ledger device details.
- - Tap **Device Info** to start the pairing process.
- - Follow on-screen instructions to complete the setup of your hardware account.
-
- |  |  |  |  |
- |--------------------------------------------------------|--------------------------------------------------------|--------------------------------------------------------|--------------------------------------------------------|
-
-#### Additional Notes :
- - Ensure your Ledger device is sufficiently charged before pairing.
- - If you face connection issues, try restarting Bluetooth and reconnecting.
- - Refer to the [attached video](/guides/fetch-network/asi-wallet/mobile-wallet/get-started#connect-ledger) for a visual walkthrough of these steps.
----
\ No newline at end of file
diff --git a/pages/guides/fetch-network/asi-wallet/mobile-wallet/more.mdx b/pages/guides/fetch-network/asi-wallet/mobile-wallet/more.mdx
deleted file mode 100644
index 19bb2a339..000000000
--- a/pages/guides/fetch-network/asi-wallet/mobile-wallet/more.mdx
+++ /dev/null
@@ -1,104 +0,0 @@
-# How to use ASI Alliance Wallet
-
-## Feature 5 - More Options
-
-- Open ASI Alliance Wallet Dashboard.
-- Navigate to **More Tab**.
-
-
-
-### More Option - Currency
-
-Within this section, you can set the currency configuration for your wallet. You can do so following these steps:
-
- - Access **Currency** option.
- - Within **More**, locate and select the **Currency** option.
-
-
-
- - Here, you can change the currency from USD to any other available currency.
-
-
-
-### Manage Token
-
-In the **Manage Tokens** section, you can view the tokens you've added and their details.
-
-
-
-You can add new tokens by clicking on the **+** sign next to the tokens list.
-
-
-
-### Address Book
-
-- Access the **Address Book** section.
-
-
-
-- View **Existing** addresses.
-
-
-
-### Add an Address
-
-You can **Add a new address** by clicking on the **+** sign button.
-
-
-
-### Edit an Address
-
-- If you need to edit an address:
- - Click on the **three dots** (...) next to the address.
-
-
-
- - Select **Rename** option.
-
-
-
- - From there, you can edit the address **Name**, **Memo**, and **Address** itself.
-
-
-
-### Delete Address
-
-- To **Delete an address**:
- - Click on the **three dots** (...) next to the address.
-
-
-
- - Select the **Delete Address** option to remove it.
-
-
-
- - Click on **Remove** option.
-
-
-
-### Security and Privacy Options
-
-- Explore the **Security and Privacy** section. Here, you can:
-
- - View your mnemonic seed after entering your password.
-
-
-
- - Click on **View Mnemonic seed** option.
-
-
-
- - View your mnemonic seed after entering your password.
-
-
-
- - Users can copy the mnemonic seed by clicking **Copy to Clipboard**.
-
-
-
-### ASI Alliance Wallet Version
-
-You can check the version of the app under the **ASI Alliance Wallet** option.
-
-|  |  |
-|--------------------------------------------------------|--------------------------------------------------------|
\ No newline at end of file
diff --git a/pages/guides/fetch-network/asi-wallet/mobile-wallet/send-receive.mdx b/pages/guides/fetch-network/asi-wallet/mobile-wallet/send-receive.mdx
deleted file mode 100644
index a830feaf2..000000000
--- a/pages/guides/fetch-network/asi-wallet/mobile-wallet/send-receive.mdx
+++ /dev/null
@@ -1,91 +0,0 @@
-import { Callout } from 'nextra/components'
-
-# How to use ASI Alliance Wallet
-
-## Feature 3 - Send/Receive Functionalities
-
-### Send/Receive Button
-
-This button allows the user to perform transaction send and receive functions. By utilizing this feature, users can send and receive transactions seamlessly within the app.
-
-
-
-## Send Option
-
-### Initiate Transfer
-
-If a user wants to send money to another user, they should start by locating the transaction button.
-
-### Select Send Option
-
-Once the transaction button is found, the user selects the option to send money.
-
-
-
-### Enter Amount and Account
-
-After selecting the send option, the user needs to enter the amount they wish to send and choose the account from which the money will be transferred.
-
-
-
-### Add Recipient's Address
-
-Next, the user is prompted to add the recipient's address. This can be done in two ways: either by **scanning the address** or by using the **Add to contact** option.
-
-
-
-### Review Transaction
-
-After adding the recipient's address, the user should review the transaction details to ensure accuracy.
-
-
-
-### Optional: Add Memo
-
-If the user wishes to add a memo to the transaction, they can do so at this stage.
-
-
- **Fetch transaction memo limits and storage details**
-
- 1. **Character/size limitations**: the memo field is limited to _256 bytes_ by default. This is configurable and can be changed via a governance proposal if needed. To check the current value programmatically, you can query the `auth` module parameters [here ↗️](https://rpc-fetchhub.fetch.ai/abci_query?path=%22custom/auth/params%22) and decode the response by copy-pasting there inner content of `value` (without quotes). You'll receive a base64-encoded response containing the parameters, which you can decode to view the structure, including the `max_memo_characters`, `tx_sig_limit`, and `tx_size_cost_per_byte` parameters.
-
- 2. **Limitations**: while you can add any data within the 256-byte limit, the memo field is intended for _short text_. Adding structured or binary data (e.g., blob attachments) is technically possible within the size constraint, but it isn't recommended due to potential gas costs and inefficiency. If you wish to store larger or more complex data, consider using other data storage methods, as encoding this data in the memo could potentially exhaust gas and processing limits. The current **gas constraints** are set up:
-
- - Each byte stored in a transaction costs 10 gas (as set by `tx_size_cost_per_byte`).
- - The maximum gas per block is 3,000,000 gas, which limits the total data that can be stored in a block.
- - While the block size limit is 300,000 bytes, the gas cost to store data near this size would max out the block's gas limit. Therefore, block gas constraints often restrict the size of a transaction more than the byte limit alone.
-
- 3. **On-chain storage and migrations**: once a transaction with a memo is added to a block, the memo data is stored permanently on-chain. During migrations, all transaction data, including the memo, should remain intact, as existing chain data should be preserved once migration is finalized.
-
-
-**Approve Transaction**: once the user has reviewed the transaction and made any necessary additions, they can proceed by clicking on the **Approve transaction** button.
-
-
-
-### Transaction Confirmation
-
-Upon approval, a transaction ID is generated, confirming that the transaction has been successfully processed.
-
-
-
-## Receive Option
-
-### Initiate Transaction
-
-If a user wants to **Receive money** from another user, they should start by locating the transaction button.
-
-### Select Receive Option
-
-Once the transaction button is found, the user selects the option to Receive money.
-
-
-
-### Choose Payment Method
-
-Determine the preferred method of payment, whether it's scanning a QR code or fetching the recipient's account address.
-
-### Complete Transaction
-
-Once the payment method is selected and the necessary details are provided, proceed to complete the transaction.
-
-
diff --git a/pages/guides/fetch-network/asi-wallet/mobile-wallet/stake.mdx b/pages/guides/fetch-network/asi-wallet/mobile-wallet/stake.mdx
deleted file mode 100644
index 0600525a7..000000000
--- a/pages/guides/fetch-network/asi-wallet/mobile-wallet/stake.mdx
+++ /dev/null
@@ -1,61 +0,0 @@
-# How to use ASI Alliance Wallet
-
-## Feature 2 - Stake
-
-### Stake Dashboard
-
- 1. By clicking on the **Stake** icon, users are redirected to the **Stake Dashboard** where they can see their available, staked, and claimable amounts. The dashboard also contains a list of validators in which users have staked.
- 2. The **Stake more** button allows users to stake with a variety of other validators. For a detailed walk - through, refer to **Stake Functions** .
- 3. **Staking rewards** provide information on the claimable amounts for all staked validators. Users can claim the entire amount or choose to claim from specific validators by clicking **View rewards**.
- 4. **Staked balances** provide an overview of staked tokens amounts.
-
-
-
-### Stake Functions
-
-1. The dashboard view is dynamic, appearing differently when the user hasn't staked yet. In this case, the user will see **Start Staking** or **Stake More**, both of which perform the same function. Clicking the button redirects to the **Validators List**, where users can filter validators by **APR**, **Voting Power**, and **Name**.
-
-2. Clicking on any validator box will redirect you to its details page; this allows the user to proceed with staking by providing the necessary transaction information. Once the transaction is completed, it will be displayed on the staking dashboard.
-
-|  |  |  |
-|--------------------------------------------------------|--------------------------------------------------------|--------------------------------------------------------|
-
-### Unstake Functions
-
-Unstaking involves withdrawing the staked amount from a validator. Follow these steps to unstake your tokens:
-
- 1. Open the **Stake Dashboard** view.
- 2. Scroll to the staked balances section and select the validator.
- 3. Click the **Unstake** button.
-
-If you withdraw the entire staked amount, you will see a _21-day unstaking process_ view for that token.
-
-|  |  |  |  |
-|--------------------------------------------------------|--------------------------------------------------------|--------------------------------------------------------|--------------------------------------------------------|
-
-### Redelegate Functions
-
-Redelegating involves moving funds from one validator to another. Follow these steps to successfully redelegate your tokens:
-
- 1. Open the **Stake Dashboard** view.
- 2. Scroll to the staked balances section and select the validator.
- 3. Click the **Redelegate** button.
- 4. Select the new validator where you want to stake the balance.
- 5. Fill in the necessary information and proceed with the transaction.
-
-|  |  |
-|--------------------------------------------------------|--------------------------------------------------------|
-
-### Claim Rewards
-
-**Staked rewards** can be claimed from multiple locations:
-
- 1. Home Tab
- 2. Portfolio
- 3. Stake Tab
- 4. Stake Token Detail
-
-After successfully withdrawing rewards, they will be displayed on the staking dashboard.
-
-|  |  |  |
-|--------------------------------------------------------|--------------------------------------------------------|--------------------------------------------------------|
diff --git a/pages/guides/fetch-network/asi-wallet/web-wallet/_meta.json b/pages/guides/fetch-network/asi-wallet/web-wallet/_meta.json
deleted file mode 100644
index 441ddff39..000000000
--- a/pages/guides/fetch-network/asi-wallet/web-wallet/_meta.json
+++ /dev/null
@@ -1,34 +0,0 @@
-{
- "get-started": {
- "title": "Getting started",
- "tags": ["ASIAllianceWallet", "Web", "Wallet"]
- },
- "home-screen": {
- "title": "Feature 1: Home Screen",
- "tags": ["ASIAllianceWallet", "Web", "Home", "Wallet"]
- },
- "stake": {
- "title": "Feature 2: Stake",
- "tags": ["ASIAllianceWallet", "Web", "Staking", "Wallet"]
- },
- "send-receive": {
- "title": "Feature 3: Send and Receive functions",
- "tags": ["ASIAllianceWallet", "Web", "Send", "Receive", "Wallet"]
- },
- "activity": {
- "title": "Feature 4: Activity page",
- "tags": ["ASIAllianceWallet", "Web", "Activity", "Wallet"]
- },
- "more": {
- "title": "Feature 5: More options",
- "tags": ["ASIAllianceWallet", "Web", "Wallet"]
- },
- "gov-proposal": {
- "title": "Feature 6: Gov Proposal",
- "tags": ["ASIAllianceWallet", "Web", "Gov Proposal", "Wallet"]
- },
- "ledger-guide": {
- "title": "Feature 7: Ledger Guide",
- "tags": ["ASIAllianceWallet", "Web", "Ledger Guide", "Wallet"]
- }
-}
diff --git a/pages/guides/fetch-network/asi-wallet/web-wallet/activity.mdx b/pages/guides/fetch-network/asi-wallet/web-wallet/activity.mdx
deleted file mode 100644
index 30f1e4958..000000000
--- a/pages/guides/fetch-network/asi-wallet/web-wallet/activity.mdx
+++ /dev/null
@@ -1,54 +0,0 @@
-# How to use ASI Alliance Wallet
-
-## Feature 4 - Activity
-
-This page allows users to delve into activity undertaken with the wallet, encompassing transfers, staking, re-delegation and overall interactions. You can check your activity following these steps:
-
- - Open ASI Alliance Wallet Home Page.
- - Navigate to the **Activity** tab.
-
-
-
- - Here you will be able to check all of the activity you undertook within the wallet
- - Here you will have 2 tabs **Transactions** and **Governance Proposals**.
-
-### Transactions
-
-Transaction tab consists of details of all the transactions done within this wallet.
- - It consists of all the details of every transaction.
-
-
-
-#### View your transaction details
-
- - You can view your transaction's details including Gas Used, Transaction Status, Recipient Address, Transaction Hash, Chain-ID, etc.
- - Click on the transaction card whose details you want to see.
-
-|  |  |  |
-|--------------------------------------------------------|--------------------------------------------------------|--------------------------------------------------------|
-
-
- - You can even **Send Again** (in case of Sent) the same amount to the same recipient with just one click.
- - Click on **Send Again**, you will be redirected to **Send** page with amount and recipient address already entered.
-
-
-
- - You can view your transactions on **Mintscan**.
-
-
-
-#### Filter Transactions
-
-You will also be able to filter your **Transactions** based on a variety of filters. Just click on the **Filter** button in the top right corner.
-
-
-
-### Governance Proposals
-
-You can also check **Governance Proposals** and their statuses.
-
-
-
-You can **Filter** them out based on **Vote**.
-
-
diff --git a/pages/guides/fetch-network/asi-wallet/web-wallet/get-started.mdx b/pages/guides/fetch-network/asi-wallet/web-wallet/get-started.mdx
deleted file mode 100644
index aa2ea1f30..000000000
--- a/pages/guides/fetch-network/asi-wallet/web-wallet/get-started.mdx
+++ /dev/null
@@ -1,100 +0,0 @@
-# ASI Alliance Wallet
-
-## Installation
-
-### How to install ASI Alliance Wallet
-
-Install **ASI Alliance Wallet** (*version 0.19.2*). The ASI Alliance Wallet is supported by all Chromium-based web browsers, including **Chrome**, **Brave**, **Edge**, **Decentr** as well as **Firefox**. You can install it for your [Chrome or Chromium-based browser here ↗️](https://chromewebstore.google.com/detail/asi-alliance-wallet/ellkdbaphhldpeajbepobaecooaoafpg?pli=1) or [Firefox ↗️](https://addons.mozilla.org/en-US/firefox/addon/asi-alliance-wallet/).
-
-To install the ASI Alliance Wallet, follow these steps:
-
- 1. Open your web browser and go to Google.
- 2. Type "ASI Alliance Wallet" in the search bar.
- 3. From the search results, select the first option that appears (it should match the image provided).
-
-
-
- 4. Click on **Add to Extension** to install ASI Alliance Wallet.
-
-
-
- 5. To use ASI Alliance Wallet, click on the ASI Alliance Wallet button in your browser. This will redirect you to the ASI Alliance Wallet landing page.
-
-
-
- 6. After opening the Wallet, you will see options like **Create new wallet** and **Import existing wallet**.
-
-
-
-## On Boarding
-
-### How to set up ASI Alliance Wallet
-
-You can choose between **Create new wallet** and **Import existing wallet**.
-
-
-
-### Create a new Wallet
-
-You will need to **Create a new seed phrase**. Make sure you do not lose it!
-
-
-
-### Create New seed phrase
-
- 1. Securely backup your mnemonic seed phrase. Also make sure to accept the Terms and Conditions as shown below.
-
-
-
- 2. **Set a password** and a **name** for your account. The next time you wish to use the wallet or make significant changes to your account, this password will be required so make sure to save it properly!
-
-
-
- 3. You will then need to confirm the mnemonic seed, by reordering the mnemonic phrases by clicking on them in the correct sequence.
- 4. User is now all set to begin your ASI Alliance Wallet journey.
-
-## Import a wallet
-
-By choosing this option, you will need to choose among 3 different option to import an existing wallet.
-
-
-
-Let's dive into them here below.
-
-### Use a seed phrase or a private key
-
- 1. **Mobile app**: When a user opens the mobile app and already has an account created on the web, they can import their existing account into the mobile app.
- 2. **Mnemonic Seed** or **Private Key**: The user can choose to import their account by pasting the mnemonic seed (12 or 24 words) or the private key.
- 3. Additionally, you can input the name of the account and set a password for it.
-
-
-
- 4. After completing the import process and providing the necessary details, the user's existing account will be successfully set up and ready to use in the mobile app.
-
-
-
-#### Connect Ledger
-
-If you use the ASI Alliance Wallet together with a **Ledger Hardware Wallet** and want to retain your key and mnemonics there, then:
-
- 1. Select **Connect ledger**.
- 2. Set a **password** for your account and give it a **name**. The next time you wish to use the wallet or make significant changes to your account, this password will be required.
- [Click here for More Details](/guides/fetch-network/asi-wallet/web-wallet/ledger-guide)
-
-#### Migrate from ETH
-
-If you already have a Metamask account, you can import an existing wallet following these steps:
-
- 1. Select **Migrate from ETH**.
- 2. On the next page, click **Migrate a Metamask Private Key**.
-
-
-
- 3. You will be taken to the main import screen, where you can provide the **Account Name**, the **Ethereum Address** you are migrating from (i.e., in this case, your Metamask ETH address). This is used to ensure that the private key matches. Finally, copy the **Private Key** from your Metamask account.
-
-
-
- 4. If this is your first key in the wallet, you will be prompted to create a **global password** for your wallet. The password will be required the next time you use the wallet or make changes to your account.
- 5. After completing the import process and providing the necessary details, the user's existing account is successfully set up and ready to use in the mobile app.
-
-
diff --git a/pages/guides/fetch-network/asi-wallet/web-wallet/gov-proposal.mdx b/pages/guides/fetch-network/asi-wallet/web-wallet/gov-proposal.mdx
deleted file mode 100644
index 4e9455058..000000000
--- a/pages/guides/fetch-network/asi-wallet/web-wallet/gov-proposal.mdx
+++ /dev/null
@@ -1,18 +0,0 @@
-# How to use ASI Alliance Wallet
-
-## Feature 6 - Gov Proposal
-
-Governance proposal is a system for managing and implementing changes to cryptocurrency blockchains. In this type of governance, voting systems for instituting changes are programmed into the blockchain. Developers propose changes, and each stakeholder votes on whether to accept or reject the proposed change. Blockchain stakeholders might be developers, validators, token holders, or anyone else the blockchain is designed to include.
-
- - Open ASI Alliance Wallet Dashboard.
- - Navigate to **More Tab**.
- - Look for and select the **Proposals** option.
-
-|  |  |
-|--------------------------------------------------------|--------------------------------------------------------|
-
- - Clicking on any proposal navigates the user to the detail page.
- - The detail page provides all the necessary information about the proposal.
- - Users can vote or change their vote if the proposal is in an active status.
-
-# 
\ No newline at end of file
diff --git a/pages/guides/fetch-network/asi-wallet/web-wallet/home-screen.mdx b/pages/guides/fetch-network/asi-wallet/web-wallet/home-screen.mdx
deleted file mode 100644
index 05528027d..000000000
--- a/pages/guides/fetch-network/asi-wallet/web-wallet/home-screen.mdx
+++ /dev/null
@@ -1,119 +0,0 @@
-# How to use ASI Alliance Wallet
-
-## Feature 1 - Home Screen
-
-When a user opens the web extension for the first time, they are presented with the **Account Dashboard**.
-
-
-
-Let's explore the Dashboard features below.
-
-### Account Dashboard Features
-
-#### Network Selector Option
-
-By clicking on **Network Selector** button located in the top left corner, the user can change the network.
-
-
-
- - On opening **Network Selector**, user gets a list of networks from which they can choose.
-
- - They also have 2 tabs **Cosmos** and **EVM** to select from.
-
-|  |  |
-|--------------------------------------------------------|--------------------------------------------------------|
-
- - User can use the **Show testnet** switch to show or hide testnets.
-
-
-
- - User can even enable/disable the networks they want to have in the list.
- - For that user can navigate to **Manage Networks** page.
-
-
-
- - User can toggle to enable or disable the network.
-
-
-
-#### Copy Address
-
-By clicking on **the area marked below** the user can copy their account's address.
-
-
-
-{/* #### Chat Option
-
-**This feature is upcoming and not available yet**. By clicking on this button, the users are able to open the **Chat** window where they can initiate a chat with other users. They can also chat with autonomous agent to ask questions and perform wallet functions.
-
- */}
-
-### Three Dots (More Options)
-
-By clicking on these 3 dots button, user will see the following options to manage their wallet:
-
-
-
-##### Add New Account
-
-This option allows the user to **Add a new wallet**, as described earlier.
-
-
-
-##### Change Account
-
-If the user has multiple accounts, they can switch across them using this functionality.
-
-
-
-##### Rename Account
-
-This function enables users to change the name of their account.
-
-
-
-##### Delete Wallet
-
-This functionality provides the option to delete a wallet.
-
-|  |  |
-|--------------------------------------------------------|--------------------------------------------------------|
-
-**User can also backup their mnemonic seed of account before deleting it by clicking on Back up mnemonic seed.**
-
-|  |  |  |
-|--------------------------------------------------------|--------------------------------------------------------|--------------------------------------------------------|
-
-### Viewing Account Information
-
-#### Current Balance
-
-The user can see their **Current Balance** in **Selected Network's** token and in USD.
-
-
-
-## Portfolio
-
-By clicking on the **View Portfolio** button, users can view their portfolio's stats, performance and composition.
-
-
-
-Here user will have 2 tabs: **Tokens** and **Stats**.
-
-
-
-By clicking on **Token** tab, users have the ability to explore the tokens page.
- - Users will be able to see price graph at different timelines but also perform **Receive** or **Send** operations by clicking on token boxes.
-
-|  |  |
-|--------------------------------------------------------|--------------------------------------------------------|
-
-On the other hand, the **Stats** tab displays the staking information, including **Available** tokens for staking, **Staked** tokens and **Staking rewards** accrued.
-
-
-
-### Portfolio Performance
-
-In the home screen of the Wallet, users can track their portfolio performance over various timeframes (from 24 hours to 1 year).
-
-
diff --git a/pages/guides/fetch-network/asi-wallet/web-wallet/ledger-guide.mdx b/pages/guides/fetch-network/asi-wallet/web-wallet/ledger-guide.mdx
deleted file mode 100644
index da6d60d4e..000000000
--- a/pages/guides/fetch-network/asi-wallet/web-wallet/ledger-guide.mdx
+++ /dev/null
@@ -1,98 +0,0 @@
-# Steps to Connect Ledger Hardware Wallet
-
-## Feature 7 - Ledger Guide
-
-### Step 1 : Open the Extensions and Navigate to the Register Screen
-
- - Launch the extensions and go to the **Home** screen.
-
- - Tap the **three-dot menu** and select **Add New Wallet**.
-
-# 
-
-> **Note** : If you are a new user, you will be automatically redirected to the **Register** screen.
-
-### Step 2 : Select Import Existing Wallet
-
- - On the **Register** screen, tap **Import Existing Wallet**.
-
- - Choose **Connect Hardware Wallet** and enter the required details.
-
-|  |  |
-|--------------------------------------------------------|--------------------------------------------------------|
-
-
-### Step 3 : Connect and Pair Your Ledger Device
-
- - Tap **Next** button. A pop-up will appear.
-
- - The extensions will detect your **Ledger device** connected through USB and display its details.
-
- - Tap **Device Info** to begin the pairing process.
-
- - Follow the on-screen instructions to complete the setup of your hardware wallet.
-
-# 
-
-# 
-
-### Additional Tips for a Smooth Connection
-
-✔ **Ensure Your Ledger Device is Charged** – Make sure it has sufficient battery before pairing.
-
-✔ **Troubleshooting Connection Issues** :
- - Try **reconnecting** your device.
- - If the issue persists, **restart** your Ledger device and try again.
----
-
-
-# Ledger Transactions Errors - Troubleshooting Guide
-
-## Error 1 : Connect and unlock your Ledger device
-
-#### **Description** : This error indicates that your Ledger device is not properly connected via **USB**.
-
-**Troubleshooting Steps** :
- 1. Ensure the device is properly connected via USB.
-
- 2. Try using a different USB cable or port.
-
- 3. If the connection is secure, attempt to click the **Approve Transaction** button twice.
-
- 4. Doing so may reveal the actual error related to USB permissions.
-
- 5. If the issue persists, regain USB permission by following the provided troubleshooting **hyperlink**.
-
-|  |  |
-|--------------------------------------------------------|--------------------------------------------------------|
-|  |  |
-
-## Error 2 : Unlock your Ledger device
-
-#### **Description** : This error means that your Ledger device is in a **locked state** and must be **unlocked before proceeding**.
-
- **Troubleshooting Steps** :
- 1. Press the device buttons to unlock it.
-
- 2. Ensure your Ledger device is powered on.
-
- 3. If the device does not respond, restart it and try again.
-
-
-
-## Error 3 : Unlock the Cosmos/Ethereum app on Ledger and try again.
-
-#### **Description** : This error suggests that you need to open the respective **Cosmos** or **Ethereum** app on your Ledger device before proceeding with the transaction.
-
-**Troubleshooting Steps** :
- 1. Navigate to the **Cosmos/Ethereum app** on your Ledger device.
-
- 2. Open the respective app and ensure it is running.
-
- 3. If the app is not installed, download and install it via Ledger Live : [Ledger Live Download](https://www.ledger.com/ledger-live)
-
- 4. Retry the transaction after ensuring the app is open and active.
-
-
-
----
\ No newline at end of file
diff --git a/pages/guides/fetch-network/asi-wallet/web-wallet/more.mdx b/pages/guides/fetch-network/asi-wallet/web-wallet/more.mdx
deleted file mode 100644
index 3d2594718..000000000
--- a/pages/guides/fetch-network/asi-wallet/web-wallet/more.mdx
+++ /dev/null
@@ -1,161 +0,0 @@
-# How to use ASI Alliance Wallet
-
-## Feature 5 - More Options
-
-- Open ASI Alliance Wallet Home Page.
-- Click **More** option on the home page.
-
-
-
-## More Page
-
-
-
-### Currency
-
-Within this section, you can set the currency configuration for your wallet. You can do so following these steps:
-
- - Select **Currency** box.
-
-
-
- - Here, you can change the wallet currency from USD to any other available currency.
-
-
-
-### Manage Token
-
-
-
-In the **Manage Tokens** tab, you can:
- - View the tokens you've added.
-
-
-
- - Add new tokens by clicking on the **+** button on the upper right side or by clicking on **Add Token** button.
- - You will need to provide the needed details for the token you wish to add.
-
-
-
-### Address Book
-
-Click the **Address Book** box.
- - You will be able to perform operation on addresses saved within the wallet.
-
-
-
- - You will be able to see all existing addresses.
-
-
-
-### Add an Address
-
-Add a **New address** by clicking on the **+** button on the upper right side or by clicking on **Add an Address** button.
-
-
-
-### Edit an Address
-
-If you need to **Edit an address**:
-
- - Click on the **Edit** button next to the address.
-
-
-
- - From there, you can edit the address **Name**, **Memo**, and **Address** itself.
-
-
-
-### Delete Address
-
-- To **Delete** an address:
-
-- Click on the **Delete** button next to the address.
-
-
-
- - Confirm.
-
-
-
-### Language
-
-User can change the wallet language using this option.
-
-|  |  |
-|--------------------------------------------------------|--------------------------------------------------------|
-
-### Security and Privacy Options
-
- - Click on the **Security and Privacy** box.
- - Here you will be able to perform multiple operations related to your account's security and privacy settings.
-
-
-
-Here, you can:
-
- - View **mnemonic seed / Private key** after entering your password.
-
- - Click on View **Mnemonic seed / Private key** option.
-
-|  |  |
-|--------------------------------------------------------|--------------------------------------------------------|
-
-- View your **mnemonic seed / Private key** after entering your password.
-
-- Users can copy the **mnemonic seed / Private key** by clicking **Copy to Clipboard**.
-
-
-|  |  |  |
-|--------------------------------------------------------|--------------------------------------------------------| --------------------------------------------------------|
-
-### Wallet Access Permission
-
-Here you can choose which websites can access addresses or signing.
-
-
-
-### Chain List Access
-
-Here you can set which websites can access your active chain list.
-
-
-
-### Auto-lock Timer
-
-User can set the **Auto-Lock Timer** by clicking on this box. This way, the wallet will lock when the device is in sleep mode after provided time.
-
-|  |  |
-|--------------------------------------------------------|--------------------------------------------------------|
-
-## Others
-
-### IBC Transfer
-
-Here you can perform IBC Transfer operations.
-
-
-
-To do so:
-
-1. Provide the transaction details:
-
- - **Destination chain**: the destination blockchain is called **Destination Chain**.
- - **Recipient**: the address you want to receive the tokens is the **Recipient**.
- - **Memo**: a memo that is optional.
-
-2. Click Next.
-
-
-
-### Guide
-
-This option redirects user to guide page to seek help.
-
-
-
-### Sign Out
-
-User will able to sign out from their account using this option.
-
-
diff --git a/pages/guides/fetch-network/asi-wallet/web-wallet/send-receive.mdx b/pages/guides/fetch-network/asi-wallet/web-wallet/send-receive.mdx
deleted file mode 100644
index 08ed9f128..000000000
--- a/pages/guides/fetch-network/asi-wallet/web-wallet/send-receive.mdx
+++ /dev/null
@@ -1,103 +0,0 @@
-import { Callout } from 'nextra/components'
-
-# How to use ASI Alliance Wallet
-
-## Feature 3 - Send/Receive Function
-
-### Send/Receive Button
-
-This button allows the user to perform **Send** and **Receive** token operations. By using this feature, users can send and receive transactions seamlessly within the wallet.
-
-
-
-## Send Option
-
-### Initiate Transfer
-
-If a user wants to send money to another user, they should start by locating the **Transaction** button.
-
-
-
-### Select Send Option
-
-Once the **Transaction** button is found, the user selects the option to **Send** money.
-
-
-
-### Enter Amount and Account
-
-After selecting the **Send** option, the user needs to enter the amount they wish to send and choose the account from which the money will be transferred. Be sure to select the correct account on your wallet.
-
-
-
-### Add Recipient's Address
-
-Next, the user is prompted to add the recipient's address. This can be done in three ways: either by **manually entering it**, **scanning the address** or by using the **Add to contact** option.
-
-
-
-### Optional: Add Memo
-
-If the user wishes to add a **Memo** to the transaction, they can do so at this stage.
-
-
-
-
- **Fetch transaction memo limits and storage details**
-
- 1. **Character/size limitations**: the memo field is limited to _256 bytes_ by default. This is configurable and can be changed via a governance proposal if needed. To check the current value programmatically, you can query the `auth` module parameters [here ↗️](https://rpc-fetchhub.fetch.ai/abci_query?path=%22custom/auth/params%22) and decode the response by copy-pasting there inner content of `value` (without quotes). You'll receive a base64-encoded response containing the parameters, which you can decode to view the structure, including the `max_memo_characters`, `tx_sig_limit`, and `tx_size_cost_per_byte` parameters.
-
- 2. **Limitations**: while you can add any data within the 256-byte limit, the memo field is intended for _short text_. Adding structured or binary data (e.g., blob attachments) is technically possible within the size constraint, but it isn't recommended due to potential gas costs and inefficiency. If you wish to store larger or more complex data, consider using other data storage methods, as encoding this data in the memo could potentially exhaust gas and processing limits. The current **gas constraints** are set up:
-
- - Each byte stored in a transaction costs 10 gas (as set by `tx_size_cost_per_byte`).
- - The maximum gas per block is 3,000,000 gas, which limits the total data that can be stored in a block.
- - While the block size limit is 300,000 bytes, the gas cost to store data near this size would max out the block's gas limit. Therefore, block gas constraints often restrict the size of a transaction more than the byte limit alone.
-
- 3. **On-chain storage and migrations**: once a transaction with a memo is added to a block, the memo data is stored permanently on-chain. During migrations, all transaction data, including the memo, should remain intact, as existing chain data should be preserved once migration is finalized.
-
-
-### Review Transaction
-
-After adding the recipient's address, the user should Review the transaction details to ensure accuracy.
-
-Then, the user will need to **Approve the Transaction**. Once the user has reviewed the transaction and made any necessary additions, they can proceed by clicking on the **Approve Transaction** button.
-
-
-
-### Transaction Confirmation
-
-Upon approval, a **Transaction ID** is generated, confirming that the transaction has been successfully processed.
-
-
-
-## Receive Option
-
-### Initiate Transaction
-
-If a user wants to **Receive** money from another user, they should start by locating the **Transaction** button.
-
-
-
-### Select Receive Option
-
-Once the **Transaction** button is found, the user selects the option to **Receive** money.
-
-
-
-{/* ### Choose Payment Method
-
-Determine the preferred method of payment, whether it's scanning a QR code or fetching the recipient's account address.
-*/}
-### QR Code and wallet address
-
-User is redirected to the Receive page, where their QR Code and wallet address can be accessed.
- - QR Code can be scanned to send the tokens.
- - Wallet address can be copied.
-
-
-
-## Native Bridge
-
-If users want to **Native Bridge** tokens from another blockchain, then they will need to choose this option as shown below and follow the needed steps.
-
-
diff --git a/pages/guides/fetch-network/asi-wallet/web-wallet/stake.mdx b/pages/guides/fetch-network/asi-wallet/web-wallet/stake.mdx
deleted file mode 100644
index 65d3b94fb..000000000
--- a/pages/guides/fetch-network/asi-wallet/web-wallet/stake.mdx
+++ /dev/null
@@ -1,83 +0,0 @@
-# How to use ASI Alliance Wallet
-
-## Feature 2 - Stake
-
-By choosing this option, you will be redirected to the **Staking Dashboard** where you can review all of the related information.
-
-
-
-### Stake Dashboard
-
- 1. By clicking on the **Stake** icon, users are redirected to the **Stake Dashboard** where they can see their available, staked, and claimable amounts. The dashboard also contains a list of validators in which users have staked.
- 2. The **Stake more** button allows users to stake with a variety of other validators. For a detailed walk - through, refer to **Stake Functions** .
-
-
-
- 3. **Staking rewards** provide information on the claimable amounts for all staked validators. Users can claim the entire amount or choose to claim from specific validators by clicking **View rewards**.
- 4. **Staked balances** provide an overview of staked tokens amounts.
-
-
-
-### Stake Functions
-
-1. The dashboard view is dynamic, appearing differently when the user hasn't staked yet. In this case, the user will see **Start Staking** or **Stake More**, both of which perform the same function. Clicking the button redirects to the **Validators List**, where users can filter validators by **APR**, **Voting Power**, and **Name**.
-
-2. Clicking on any validator box will redirect you to its details page; this allows the user to proceed with staking by providing the necessary transaction information. Once the transaction is completed, it will be displayed on the staking dashboard.
-
-|  |  |  |
-|--------------------------------------------------------|--------------------------------------------------------|--------------------------------------------------------|
-
-### Unstake Functions
-
-Unstaking involves withdrawing the staked amount from a validator. Follow these steps to unstake your tokens:
-
- 1. Open the **Stake Dashboard** view.
- 2. Scroll to the staked balances section and select the validator.
-
-
-
- 3. Click the **Unstake** button.
-
-If you withdraw the entire staked amount, you will see a _21-day unstaking process_ view for that token.
-
-|  |  |
-|--------------------------------------------------------|--------------------------------------------------------|
-
-### Redelegate Functions
-
-Redelegating involves moving funds from one validator to another. Follow these steps to successfully redelegate your tokens:
-
- 1. Open the **Stake Dashboard** view.
- 2. Scroll to the staked balances section and select the validator.
- 3. Click the **Redelegate** button.
-
-
-
- 4. Select the new validator where you want to stake the balance.
-
- 5. Fill in the necessary information and proceed with the transaction.
-
-
-
-### Claim Rewards
-
-**Staked rewards** can be claimed from multiple locations:
-
- 1. Home Tab
-
-
-
- 2. Portfolio
-
-
-
- 3. Stake Tab
-
-
-
- 4. Stake Token Detail
-
-
-
-After successfully withdrawing rewards, they will be displayed on the staking dashboard.
-
diff --git a/pages/guides/fetch-network/cosmpy/_meta.json b/pages/guides/fetch-network/cosmpy/_meta.json
deleted file mode 100644
index a3a659c96..000000000
--- a/pages/guides/fetch-network/cosmpy/_meta.json
+++ /dev/null
@@ -1,35 +0,0 @@
-{
- "install": {
- "title": "Installation",
- "tags": ["Beginner", "Python", "CosmPy"]
- },
- "establishing-node-connection": {
- "title": "Connecting to a blockchain",
- "tags": ["Beginner", "Python", "CosmPy"]
- },
- "querying-address-balances": {
- "title": "Querying balances",
- "tags": ["Beginner", "Python", "CosmPy"]
- },
- "creating-wallet": {
- "title": "Wallets and private keys",
- "tags": ["Beginner", "Python", "CosmPy"],
- "timestamp": true
- },
- "transaction-broadcast": {
- "title": "Sending funds",
- "tags": ["Beginner", "Python", "CosmPy"],
- "timestamp": true
- },
- "staking": {
- "title": "Staking",
- "tags": ["Beginner", "Python", "CosmPy"],
- "timestamp": true
- },
- "smart-contracts": {
- "title": "Smart contracts",
- "tags": ["Beginner", "Python", "CosmPy"],
- "timestamp": true
- },
- "use-cases": "Use cases"
-}
diff --git a/pages/guides/fetch-network/cosmpy/creating-wallet.mdx b/pages/guides/fetch-network/cosmpy/creating-wallet.mdx
deleted file mode 100644
index 4442a7b37..000000000
--- a/pages/guides/fetch-network/cosmpy/creating-wallet.mdx
+++ /dev/null
@@ -1,65 +0,0 @@
-# Wallets and private keys
-
-## Introduction
-
-**Wallets** allow individuals to manage, store and transact across blockchain networks. Wallets are composed of a public and private key pair. The private key is a unique and secret cryptographic code that provides ownership and control over the wallet and allows individuals to authorize transactions signing. The public address is a cryptographic identifier that allows individuals to receive and view transactions.
-
-Changes to the state of a network are achieved by broadcasting transactions. To accomplish this, we can use CosmPy in a straightforward way to create and manage private keys and addresses. In this guide, you will learn how to both generate a **new private key** as well as **recover a previously generated one**.
-
-The examples below outlines how to achieve both of these operations.
-
-## Generate a new private key
-
-First of all, import the needed modules and then use the `PrivateKey` class to create your `private_key`:
-
- ```py copy
- # Import necessary classes
- from cosmpy.aerial.wallet import LocalWallet
- from cosmpy.crypto.keypairs import PrivateKey
-
- # Creating a random private key
- private_key = PrivateKey()
- ```
-
-## Recover an existing private key
-
-Let's start by extracting the private key and convert it into a base64 encoded string. You can do this on macOS or Linux for the Fetch.ai network using the FetchD CL.
-
-An example is provided in the code snippet below:
-
- ```py copy
- # Extract the private key and convert it into a base64 encoded string
- fetchd keys export mykeyname --unsafe --unarmored-hex | xxd -r -p | base64
- ```
-
-Once you have extracted and converted the key into a base64 encoded string you can recover to an existing private key by following along the provided example below:
-
- ```py copy
- # Import necessary classes
- from cosmpy.aerial.wallet import LocalWallet
- from cosmpy.crypto.keypairs import PrivateKey
-
- # Recovering an existing private key
- private_key = PrivateKey('') # Here is where you provide the base64 encoded private key string
- ```
-
-The `PrivateKey` object is one of CosmPy's low level primitives. This is why it is generally paired with a `Wallet` object. You can now create a local wallet using the `LocalWallet` class from the CosmPy library and initialize it with the `private_key` you generated or recovered earlier. The `LocalWallet` class is used to manage a local wallet associated with a private key for interacting with the Cosmos blockchain.
-
-With this wallet object, you can perform various operations, such as generating the corresponding public address associated with the private key and signing transactions. You can also query useful information such as the address from the wallet directly. The example below showcases how to achieve both of these outlined operations:
-
- ```py copy
- wallet = LocalWallet(private_key)
- print(wallet.address()) # will print the address for the wallet
- ```
-
-## From mnemonic
-
-You can also use an account's mnemonic phrase to get the associated private key. The example provided below showcases how to achieve that:
-
- ```py copy
- from cosmpy.aerial.wallet import LocalWallet
-
- mnemonic = "person knife december tail tortoise jewel warm when worry limit reward memory piece cool sphere kitchen knee embody soft own victory sauce silly page"
-
- wallet = LocalWallet.from_mnemonic(mnemonic)
- ```
diff --git a/pages/guides/fetch-network/cosmpy/establishing-node-connection.mdx b/pages/guides/fetch-network/cosmpy/establishing-node-connection.mdx
deleted file mode 100644
index 3b38a3f80..000000000
--- a/pages/guides/fetch-network/cosmpy/establishing-node-connection.mdx
+++ /dev/null
@@ -1,33 +0,0 @@
-import { Callout } from 'nextra/components'
-
-# Connecting to a blockchain
-
-Once you have installed CosmPy, you can **connect and begin interacting with Cosmos-based blockchains**. You can do so by running the following command:
-
- ```py copy
- import cosmpy
- from cosmpy.aerial.client import LedgerClient, NetworkConfig
-
- # Connecting to the Fetch.ai mainnet
- ledger_client = LedgerClient(NetworkConfig.fetch_mainnet())
- ```
-
-In the code snippet above, we are using the `LedgerClient` as a client object which takes a `NetworkConfig` as an argument. For ease of use, network configurations are provided automatically. For instance, `NetworkConfig.fetch_mainnet()` is the configuration for the [Fetch ledger ↗️](/concepts/fetch-network/ledger/intro). However, CosmPy allows you to customize the network configuration and interact with other chains.
-
-
- You can explore a full list of chain identifiers, denominations and endpoints at [chain registry ↗️](https://github.com/cosmos/chain-registry/).
-
-
-Below, you can find an example of a custom network configuration:
-
- ```py copy
- cfg = NetworkConfig(
- chain_id="cosmoshub-4",
- url="grpc+https://grpc-cosmoshub.blockapsis.com:429",
- fee_minimum_gas_price=1,
- fee_denomination="uatom",
- staking_denomination="uatom",
- )
-
- ledger_client = LedgerClient(cfg)
- ```
diff --git a/pages/guides/fetch-network/cosmpy/install.mdx b/pages/guides/fetch-network/cosmpy/install.mdx
deleted file mode 100644
index 43577b4e2..000000000
--- a/pages/guides/fetch-network/cosmpy/install.mdx
+++ /dev/null
@@ -1,67 +0,0 @@
-import { Callout } from 'nextra/components'
-
-# Installation 🛠
-
-Welcome to **CosmPy**, the Python-based library that streamlines your interactions with Cosmos SDK based blockchain networks.
-
-## System Requirements
-
-The [CosmPy ↗️](https://pypi.org/project/cosmpy/) package is a Python library running on Ubuntu/Debian, and MacOS systems.
-
-On your computer, you may need to install:
-
- - [Python ↗️](https://www.python.org/downloads/) 3.8, 3.9 or 3.10.
- - [PIP ↗️](https://pypi.org/project/pip/) (Python Installs Packages).
- - [Poetry ↗️](https://python-poetry.org/) for virtual environments (optional).
- - [CosmPy ↗️](https://pypi.org/project/cosmpy/).
-
-## Walk-through
-## Install with Pip
-
- 1. First of all, create a directory for cosmpy related projects: `mkdir directory_name`
-
- 2. Within the directory, let's create and open a virtual environment using Poetry: `poetry init -n && poetry shell` (Optional)
-
- 3. Then, install CosmPy with the following command: `pip install cosmpy`
-
- 4. Finally, check if installation was successful: `pip show cosmpy`
-
-Once installed, you should see the following output on your terminal:
-
- ```
- Name: cosmpy
- Version: 0.9.0
- Summary: A library for interacting with the cosmos networks
- Home-page: https://github.com/fetchai/cosmpy
- Author: Fetch.AI Limited
- Author-email:
- License: Apache-2.0
- Requires: bech32, ecdsa, grpcio, jsonschema, protobuf, pycryptodome, python-dateutil, requests
- ```
-
-## Install from source code
-
- 1. First of all, download the latest released version from Github and navigate to the cosmpy directory:
-
- ```
- git clone https://github.com/fetchai/cosmpy.git
- cd cosmpy
- ```
-
- 2. Then install the required dependencies:
-
- ```
- poetry install
- ```
-
- 3. Lastly, open the virtual environment:
-
- ```
- poetry shell
- ```
-
-For more information on CosmPy, visit our dedicated [GitHub ↗️](https://github.com/fetchai/cosmpy) repository.
-
-
- If you wish to expand your knowledge on these topics, please visit our [GitHub repository ↗️](https://github.com/fetchai/cosmpy) for CosmPy and also checkout our dedicated [CosmPy guides ↗️](/guides#cosmpy) and [CosmPy references ↗️](/references#cosmpy-api) for information on CosmPy APIs.
-
diff --git a/pages/guides/fetch-network/cosmpy/querying-address-balances.mdx b/pages/guides/fetch-network/cosmpy/querying-address-balances.mdx
deleted file mode 100644
index 769337af2..000000000
--- a/pages/guides/fetch-network/cosmpy/querying-address-balances.mdx
+++ /dev/null
@@ -1,45 +0,0 @@
-import { Callout } from 'nextra/components'
-
-# Querying balances
-
-Once you have established a [connection to a network node ↗️](/guides/fetch-network/cosmpy/establishing-node-connection), you can use the `LegderClient` object to perform many useful operations, such as **querying balances**. In particular the `LedgerClient` object allows you to:
-
- 1. Query all balances associated with a **particular address**.
- 2. Query all balances associated with a **particular denomination**.
-
-Let's explore how to achieve both.
-
- 1. We start by importing CosmPy as well as the relevant modules.
- 2. Then, we connect to the chain we want to perform the query on.
- 3. Once connected, we specify the address we want to query. In our example we will connect to the Fetch.ai mainnet and we query all balances associated with a particular address:
-
- ```py copy
- import cosmpy
- from cosmpy.aerial.client import LedgerClient, NetworkConfig
-
- ledger_client = LedgerClient(NetworkConfig.fetch_mainnet())
-
- address: str = 'fetch12q5gw9l9d0yyq2th77x6pjsesczpsly8h5089x'
- balances = ledger_client.query_bank_all_balances(address)
- print(balances)
- ```
-
-Whenever **querying all balances associated with a _particular address_** returns a `List` of `Coin` objects that contain `amount` and `denom` variables that correspond to all the funds held at the address and their denominations.
-
-
- This list includes all natively defined coins along with any tokens transferred using the inter-blockchain communication [IBC ↗️](https://ibcprotocol.org/) protocol.
-
-
-Once completed, you will see the following output in your terminal:
-
- ```py copy
- [Coin(amount='1616060698998992698400', denom='afet'), Coin(amount='10', denom='ibc/605C5B80A8253543F8038F96F56BA13BDD8D300E12F1B32A3FA2E1EB2A933FA1'), Coin(amount='5000000', denom='ibc/B58E6786772640EC4B538AFC4393F742C326734B74CCAFAFBF7EFDC7D435B428')]
- ```
-
-In order to **query all balances associated with a _particular denomination_*+, we can run the same script but substitute the final balance command we used in the snippet above, with:
-
- ```py
- balance = ledger_client.query_bank_balance(address, denom='afet')
- ```
-
-This will return the value of the (integer) funds held by the address with the specified denomination. If the `denom` argument is omitted the function will return the fee denomination specified in the `NetworkConfig` object used to initialize the `LedgerClient`.
diff --git a/pages/guides/fetch-network/cosmpy/smart-contracts.mdx b/pages/guides/fetch-network/cosmpy/smart-contracts.mdx
deleted file mode 100644
index 11c27a4ee..000000000
--- a/pages/guides/fetch-network/cosmpy/smart-contracts.mdx
+++ /dev/null
@@ -1,69 +0,0 @@
-# Smart contracts
-
-## Deploy a smart contract
-
-CosmPy offers the possibility to easily deploy **smart contracts** using the `LedgerContract` object. For this, you will need the **path** to where the contract is stored (in this case `simple.wasm`), a [`LedgerClient` ↗️](/guides/fetch-network/cosmpy/establishing-node-connection) and a [Wallet ↗️](/guides/fetch-network/cosmpy/creating-wallet).
-
-The example below shows how to achieve this:
-
- ```py copy
- from cosmpy.aerial.contract import LedgerContract
-
- PATH = "contracts/simple/simple.wasm"
-
- contract = LedgerContract(PATH, ledger_client)
- contract.deploy({}, wallet)
- ```
-
-## Interact with smart contracts
-
-We can now start interacting with any smart contract in different ways by executing one of the following operations.
-
-### Retrieve contract address
-
-After deployment, you can obtain the address of the deployed contract on the network using the `address` method in the following way:
-
- ```py copy
- print(f"Contract deployed at: {contract.address}")
- ```
-
-### Query contract's state variables
-
-We can also query the values of the contract's state variables using the `query` method and provide a dictionary specifying the query information:
-
- ```py copy
- result = contract.query({"get": {"owner": wallet}})
- print("Initial state:", result)
- ```
-
-### Set contract's state variables
-
-We can update the contract's state variables by using the `execute` method and by providing a dictionary specifying the update wanted. Use the `wait_to_complete()` method to wait for the execution to finish.
-
-The following code sets the state variable `value` to `foobar`:
-
- ```py copy
- contract.execute({"set": {"value": "foobar"}}, wallet).wait_to_complete()
- ```
-
-Once you set a state variable to its updated value, you can query it again to confirm such changes took place effectively. Considering the example above, we can check if changes were set correctly in the following way:
-
- ```py copy
- result = contract.query({"get": {"owner": wallet)}})
- print("State after set:", result)
- ```
-
-### Clear state variables
-
-We can clear the contract's state variables using the `execute` method in the following way:
-
- ```py copy
- contract.execute({"clear": {}}, wallet).wait_to_complete()
- ```
-
-Then, we can check if the operation was correctly executed by running what follows:
-
- ```py copy
- result = contract.query({"get": {"owner": wallet}})
- print("State after clear:", result)
- ```
diff --git a/pages/guides/fetch-network/cosmpy/staking.mdx b/pages/guides/fetch-network/cosmpy/staking.mdx
deleted file mode 100644
index 9cdbd61a5..000000000
--- a/pages/guides/fetch-network/cosmpy/staking.mdx
+++ /dev/null
@@ -1,75 +0,0 @@
-import { Callout } from 'nextra/components'
-
-# Staking
-
-## Introduction
-
-**Staking** is a crucial mechanism for Proof-of-Stake (PoS) based blockchains, empowering users to actively participate in securing the network while earning rewards. Staked (delegated) funds are bonded to validator nodes. These validator nodes validate transactions and maintaining the network's integrity. By bonding funds to validators, individuals earn governance rights and actively contribute to the network's security and decentralization.
-
-
- Bonding is the process of telling the network of your choice that you want to stake tokens on it. The bonding period is the lapse of time the blockchain delegator waits before his asset are bonded. Conversely, unbonding is the action of telling the network you want to unlock those assets. The unbonding period is the designated amount of time that a blockchain delegator waits before having access to move or sell their tokens.
-
-
-## Delegating
-
-Considering CosmPy, the `Ledgerclient` object provides utilities for interacting with the staking component of the network. As you continue to explore this guide, you will notice that the `LedgerClient` object plays a part in all stake related processes. To begin with, we will start with one example to showcase how to use CosmPy to delegate 20 FET to a validator, using a `wallet` object:
-
- ```py copy
- validator_address = 'fetchvaloper1e4ykjwcwhwtasqxq50d4m7xz9hh7a86e9y8h87'
-
- tx = ledger_client.delegate_tokens(validator_address, 20, wallet)
-
- # block until the transaction has been successful or failed
- tx.wait_to_complete()
- ```
-
-## Re-delegating
-
-Similarly to the delegate option, re-delegating is the process of unbonding staked funds from one validator node and bonding them to another. This is highly useful in cases where a better validator option has arisen or in crisis management situations where a rapid re-delegation is needed. In the example below, you will learn how to re-delegate 10 tokens from an existing `validator_address` to another `alternative_validator_address`:
-
- ```py copy
- validator_address = 'fetchvaloper1e4ykjwcwhwtasqxq50d4m7xz9hh7a86e9y8h87'
- alternate_validator_address = 'fetchvaloper1e4ykjwcwhwtasqxq50d4m7xz9hh7a86e9y8h87'
-
- tx = ledger_client.redelegate_tokens(validator_address, alternate_validator_address, 10, wallet)
-
- # block until the transaction has been successful or failed
- tx.wait_to_complete()
- ```
-
-## Undelegating
-
-Undelegated funds go through an **unbonding period** (i.e., typically 14 to 21 days for Cosmos sdk based projects) and once their unbonding period is complete funds become transferable. The code snippet we have shared, showcases how to use the `LedgerClient` object to invoke the undelegation (in this case 5 tokens) and start the cool down process.
-
-Importantly, the cool down is tracked for each undelegation invocation. For instance, if you trigger 3 undelegate actions on 3 consecutive days the first batch of tokens will become available 3 days before the final batch. In the snippet below, we provide the command needed to undelegate your tokens:
-
- ```py copy
- tx = ledger_client.undelegate_tokens(validator_address, 5, wallet)
-
- # block until the transaction has been successful or failed
- tx.wait_to_complete()
- ```
-
-## Claiming Rewards
-
-**Delegated funds accrue rewards**. Rewards can be collected at any time and unlike delegations become immediately available.
-
-You can claim rewards from a specific validator using the following commands:
-
- ```py copy
- tx = ledger_client.claim_rewards(validator_address, wallet)
-
- # block until the transaction has been successful or failed
- tx.wait_to_complete()
- ```
-
-## Stake queries
-
-Additionally, CosmPY allows you to perform useful **stake queries** and **summaries**. You can query the stake information on any particular address at any point using the `LedgerClient` as shown in the example below:
-
- ```py copy
- address = 'fetch1h2l3cnu7e23whmd5yrfeunacez9tv0plv5rxqy'
-
- s = ledger_client.query_staking_summary(address)
- print(f"Summary: Staked: {s.total_staked} Unbonding: {s.total_unbonding} Rewards: {s.total_rewards}")
- ```
diff --git a/pages/guides/fetch-network/cosmpy/transaction-broadcast.mdx b/pages/guides/fetch-network/cosmpy/transaction-broadcast.mdx
deleted file mode 100644
index 4b9d0f160..000000000
--- a/pages/guides/fetch-network/cosmpy/transaction-broadcast.mdx
+++ /dev/null
@@ -1,114 +0,0 @@
-import { CodeGroup, CodeSegment, DocsCode, GithubCodeSegment } from "../../../../components/code";
-
-# Sending funds
-
-CosmPy allows for simplification of transactions broadcasting. After [creating a wallet ↗️](/guides/fetch-network/cosmpy/creating-wallet) you can send transactions by following the below provided example. In it, we first connect to the desired network then provide the desired destination address. The transaction is then broadcast using the `Ledger_client.send_tokens()` function:
-
- ```py copy
- from cosmpy.aerial.client import LedgerClient, NetworkConfig
-
- # Establishing connection to the network
- ledger_client = LedgerClient(NetworkConfig.fetch_mainnet())
-
- # Providing destination address
- destination_address = 'fetch1h2l3cnu7e23whmd5yrfeunacez9tv0plv5rxqy'
-
- # Broadcasting the transaction
- tx = ledger_client.send_tokens(destination_address, 10, "atestfet", wallet)
-
- # block until the transaction has been successful or failed
- tx.wait_to_complete()
- ```
-
- In this example, we want to send 10 atestfet tokens to the `destination_address`. The `send_tokens()` method is called on the `ledger_client` object, which is an instance of the `LedgerClient` class used to interact with the Fetch.ai blockchain network. The parameter wallet is the local wallet used to sign the transaction and provide the necessary credentials. The code then waits for the transaction to complete (either successfully or failed) before proceeding further.
-
-## Sending and verifying a transaction
-
-For a more comprehensive example, we will use the **testnet** and submit a transaction then verify its completion by exploring the output on the terminal. For transactions made on the mainnet it is advisable to use our [block explorer ↗️](https://explore.fetch.ai/) or any other block explorer, such as [Mintscan ↗️](https://www.mintscan.io/fetchai). The following code snippet shows you how to create two wallets, namely for `alice` and `bob`.
-
-Once created, the next step is to establish a connection to Fetch.ai's testnet. We then query `alice`'s balance and include a while function to make sure `alice` has a positive balance and can perform the transaction. In this case `alice` will send `bob` 10 atestfet. As a final step, we will print the transaction hash, as well as `bob`'s and `alice`'s related balances:
-
-
-
-
-
-
-
- ```py copy filename="sending_funds.py"
-
- # Import the required libraries and modules
- from cosmpy.aerial.client import LedgerClient, NetworkConfig # Required to establish a connection to the network
- from cosmpy.aerial.faucet import FaucetApi # Required to fund Alice's wallet if she has a 0 balance
- from cosmpy.aerial.wallet import LocalWallet # Required to create Alice and Bob's local wallets
-
-
- def main():
- """Run main."""
- # Create Alice and Bob's wallets
- alice = LocalWallet.generate()
- bob = LocalWallet.generate()
-
- # Establish a connection to the testnet
- ledger = LedgerClient(NetworkConfig.fetchai_stable_testnet())
- faucet_api = FaucetApi(NetworkConfig.fetchai_stable_testnet())
-
- # Query Alice's Balance
- alice_balance = ledger.query_bank_balance(bob.address())
-
- # Should alice have no funds in her wallet, add funds
- while alice_balance < (10 ** 18):
- print("Providing wealth to alice...")
- faucet_api.get_wealth(alice.address())
- alice_balance = ledger.query_bank_balance(alice.address())
-
- # Print Alice and Bob's getting-uagent-address and balances
- print(
- f"Alice Address: {alice.address()} Balance: {ledger.query_bank_balance(alice.address())}"
- )
-
- print(
- f"Bob Address: {bob.address()} Balance: {ledger.query_bank_balance(bob.address())}"
- )
-
- # Broadcast the transaction and print the outputs on the terminal
- tx = ledger.send_tokens(bob.address(), 10, "atestfet", alice)
- print(f"TX {tx.tx_hash} waiting to complete...")
-
- tx.wait_to_complete()
-
- print(f"TX {tx.tx_hash} waiting to complete...done")
-
- print(
- f"Alice Address: {alice.address()} Balance: {ledger.query_bank_balance(alice.address())}"
- )
-
- print(
- f"Bob Address: {bob.address()} Balance: {ledger.query_bank_balance(bob.address())}"
- )
-
-
- if __name__ == "__main__":
- main()
-
-```
-
-
-
-
-
-
-Once you have executed the script, you will notice the console output is consistent with the code. At first, we see a print of the starting balance of both addresses. Then, we see the transaction hash along with the new balances for both `alice` and `bob`:
-
- ```
- Alice Address: fetch1kfsarzv8s0kl7pcznjgyc6mnaz96akl79kzttv Balance: 10000000000000000000
- Bob Address: fetch1ww8gsxk4usmq0tdjyele4nqyxcmc3zquu3fc52 Balance: 0
- TX 25E8F5D9F101DB5AC57DC5FF2566BA4F290609B6AADBFF1D566B398BA5FFAF48 waiting to complete...
- TX 25E8F5D9F101DB5AC57DC5FF2566BA4F290609B6AADBFF1D566B398BA5FFAF48 waiting to complete...done
- Alice Address: fetch1kfsarzv8s0kl7pcznjgyc6mnaz96akl79kzttv Balance: 9999416775000000512
- Bob Address: fetch1ww8gsxk4usmq0tdjyele4nqyxcmc3zquu3fc52 Balance: 10
- ```
diff --git a/pages/guides/fetch-network/cosmpy/use-cases/_meta.json b/pages/guides/fetch-network/cosmpy/use-cases/_meta.json
deleted file mode 100644
index 97d9791c5..000000000
--- a/pages/guides/fetch-network/cosmpy/use-cases/_meta.json
+++ /dev/null
@@ -1,32 +0,0 @@
-{
- "stake-auto-compounder": {
- "title": "Stake auto-compounder",
- "tags": ["Intermediate", "Python", "CosmPy"],
- "timestamp": true
- },
- "stake-optimizer": {
- "title": "Stake optimizer",
- "tags": ["Intermediate", "Python", "CosmPy"],
- "timestamp": true
- },
- "oracles": {
- "title": "Oracles",
- "tags": ["Intermediate", "Python", "CosmPy"],
- "timestamp": true
- },
- "wallet-top-up": {
- "title": "Wallet top-up",
- "tags": ["Intermediate", "Python", "CosmPy"],
- "timestamp": true
- },
- "liquidity-pool": {
- "title": "Liquidity pool",
- "tags": ["Intermediate", "Python", "CosmPy"],
- "timestamp": true
- },
- "swap_automation": {
- "title": "Swap automation",
- "tags": ["Intermediate", "Python", "CosmPy"],
- "timestamp": true
- }
-}
diff --git a/pages/guides/fetch-network/cosmpy/use-cases/liquidity-pool.mdx b/pages/guides/fetch-network/cosmpy/use-cases/liquidity-pool.mdx
deleted file mode 100644
index 771aa4f59..000000000
--- a/pages/guides/fetch-network/cosmpy/use-cases/liquidity-pool.mdx
+++ /dev/null
@@ -1,528 +0,0 @@
-import { CodeGroup, CodeSegment, DocsCode, GithubCodeSegment } from "../../../../../components/code";
-
-# Liquidity pool
-
-## Introduction
-
-This Liquidity pool interaction guide provides a practical demonstration of interacting with a liquidity pool on the Fetch.ai network. This script showcases various operations, including swapping assets, providing liquidity, and withdrawing liquidity, utilizing smart contracts and local wallets.
-
-## Walk-through
-
-1. Let's start by creating a Python script for this and name it:
-
-
-
- ```py copy filename="mac"
- touch aerial_liquidity_pool.py
- ```
-
-
-
- ```py copy filename="windows"
- echo. > aerial_liquidity_pool.py
- ```
-
-
-
- ```py copy filename="ubuntu"
- touch aerial_liquidity_pool.py
- ```
-
-
-
-2. Let's then import the needed modules:
-
-
-
-
-
-
-
- ```py copy filename="aerial_liquidity_pool.py"
-
- import argparse
- import base64
- from cosmpy.aerial.client import LedgerClient, NetworkConfig
- from cosmpy.aerial.contract import LedgerContract
- from cosmpy.aerial.faucet import FaucetApi
- from cosmpy.aerial.wallet import LocalWallet
-
-```
-
-
-
-
-
-
-3. We need to define a `_parse_commandline()` function:
-
-
-
-
-
-
-
- ```py copy filename="aerial_liquidity_pool.py"
-
- def _parse_commandline():
- parser = argparse.ArgumentParser()
- parser.add_argument(
- "swap_amount",
- type=int,
- nargs="?",
- default=10000,
- help="atestfet swap amount to get some cw20 tokens on wallet's address",
- )
- parser.add_argument(
- "cw20_liquidity_amount",
- type=int,
- nargs="?",
- default=100,
- help="amount of cw20 tokens that will be provided to LP",
- )
- parser.add_argument(
- "native_liquidity_amount",
- type=int,
- nargs="?",
- default=2470,
- help="amount of atestfet tokens that will be provided to LP",
- )
- return parser.parse_args()
-
-```
-
-
-
-
-
-
- The function expects and processes three command-line arguments:
-
- - `swap_amount`: this argument specifies the amount of atestfet tokens to swap in order to receive some cw20 tokens on the wallet's address. It is an optional argument, and if not provided, it defaults to `10000`.
- - `cw20_liquidity_amount`: this argument sets the amount of cw20 tokens that will be provided to the liquidity pool. It is also optional and defaults to `100` if not provided.
- - `native_liquidity_amount`: this argument represents the amount of atestfet tokens that will be provided to the liquidity pool. Like the others, it is optional and defaults to `2470` if not specified.
-
- The `help` parameter for each argument provides a description of what it is used for. The function then uses `parser.parse_args()` to process the command-line arguments provided by the user and return them as an object containing the values for `swap_amount`, `cw20_liquidity_amount`, and `native_liquidity_amount`.
-
-4. We are now ready to define our `main()` function, which orchestrates the interaction with a liquidity pool using the provided command-line arguments. We define it in multiple parts, as follows:
-
-
-
-
-
-
-
- ```py copy filename="aerial_liquidity_pool.py"
-
- def main():
- """Run main."""
- args = _parse_commandline()
-
- # Define any wallet
- wallet = LocalWallet.generate()
-
- # Network configuration
- ledger = LedgerClient(NetworkConfig.latest_stable_testnet())
-
- # Add tokens to wallet
- faucet_api = FaucetApi(NetworkConfig.latest_stable_testnet())
- faucet_api.get_wealth(wallet.address())
-
- # Define cw20, pair and liquidity token contracts
- token_contract_address = (
- "fetch1qr8ysysnfxmqzu7cu7cq7dsq5g2r0kvkg5e2wl2fnlkqss60hcjsxtljxl"
- )
- pair_contract_address = (
- "fetch1vgnx2d46uvyxrg9pc5mktkcvkp4uflyp3j86v68pq4jxdc8j4y0s6ulf2a"
- )
- liq_token_contract_address = (
- "fetch1alzhf9yhghud3qhucdjs895f3aek2egfq44qm0mfvahkv4jukx4qd0ltxx"
- )
-
- token_contract = LedgerContract(
- path=None, client=ledger, address=token_contract_address
- )
- pair_contract = LedgerContract(
- path=None, client=ledger, address=pair_contract_address
- )
- liq_token_contract = LedgerContract(
- path=None, client=ledger, address=liq_token_contract_address
- )
-
- print("Pool (initial state): ")
- print(pair_contract.query({"pool": {}}), "\n")
-
-```
-
-
-
-
-
-
- It starts by calling `_parse_commandline()` to retrieve the command-line arguments. These arguments control various aspects of the liquidity pool interaction, like swap amounts and liquidity provision. We then create new wallet called `wallet`. This wallet will be used for conducting transactions. We proceed and set the network configuration to the latest stable testnet. Through the `faucet_api` we add tokens to the wallet. This simulates the process of acquiring tokens from an external source. We go on and define the contract addresses. In the part, addresses of three different contracts (CW20 token, pair, and liquidity token contracts) are defined. These contracts are essential for interacting with the liquidity pool. Finally we print the initial pool state. This provides an initial snapshot of the liquidity pool before any actions are taken.
-
-
-
-
-
-
-
- ```py copy filename="aerial_liquidity_pool.py"
-
- # Swap atestfet for CW20 tokens
- swap_amount = str(args.swap_amount)
- native_denom = "atestfet"
-
- tx = pair_contract.execute(
- {
- "swap": {
- "offer_asset": {
- "info": {"native_token": {"denom": native_denom}},
- "amount": swap_amount,
- }
- }
- },
- sender=wallet,
- funds=swap_amount + native_denom,
- )
-
- print(f"Swapping {swap_amount + native_denom} for CW20 Tokens...")
- tx.wait_to_complete()
-
- print("Pool (after swap): ")
- print(pair_contract.query({"pool": {}}), "\n")
-
- # To provide cw20 token to LP, increase your allowance first
- cw20_liquidity_amount = str(args.cw20_liquidity_amount)
- native_liquidity_amount = str(args.native_liquidity_amount)
-
- tx = token_contract.execute(
- {
- "increase_allowance": {
- "spender": pair_contract_address,
- "amount": cw20_liquidity_amount,
- "expires": {"never": {}},
- }
- },
- wallet,
- )
-
- print("Increasing Allowance...")
- tx.wait_to_complete()
-
-```
-
-
-
-
-
-
- In this part of the main() function, the script swaps a specified amount of atestfet tokens for CW20 tokens using the `pair_contract`. This is done by constructing a transaction with the `"swap"` operation. `swap_amount` is the amount of atestfet tokens to swap, retrieved from the command-line arguments. `native_denom` is set to `"atestfet"` which is the native token denomination. The transaction is executed with the `execute()` method, specifying the `"swap"` operation. The `sender` parameter is set to the user's `wallet`, and the `funds` parameter is set to the amount being swapped in addition to the native denomination. The script then waits for the transaction to complete, and after this, a message is printed to indicate the swap operation has occurred. Within the function, we then provide CW20 tokens to the liquidity pool. The script first increases the allowance for the pair contract to spend CW20 tokens from the user's wallet. The `cw20_liquidity_amount` is the amount of CW20 tokens to provide to the LP, retrieved from the command-line arguments. The `native_liquidity_amount` is the amount of atestfet tokens to provide to the LP, also retrieved from the command-line arguments. A transaction is created with the `"increase_allowance"` operation using the `execute()` method. The transaction specifies the `spender` (`pair_contract_address`), the `amount `to allow spending (`cw20_liquidity_amount`), and an `expires` parameter set to `never`. The script waits for the transaction to complete, and after this, a message is printed to indicate that the allowance has been increased.
-
-
-
-
-
-
-
- ```py copy filename="aerial_liquidity_pool.py"
-
- # Provide Liquidity
- # Liquidity should be added so that the slippage tolerance parameter isn't exceeded
-
- tx = pair_contract.execute(
- {
- "provide_liquidity": {
- "assets": [
- {
- "info": {"token": {"contract_addr": token_contract_address}},
- "amount": cw20_liquidity_amount,
- },
- {
- "info": {"native_token": {"denom": native_denom}},
- "amount": native_liquidity_amount,
- },
- ],
- "slippage_tolerance": "0.1",
- }
- },
- sender=wallet,
- funds=native_liquidity_amount + native_denom,
- )
-
- print(
- f"Providing {native_liquidity_amount + native_denom} and {cw20_liquidity_amount}CW20 tokens to Liquidity Pool..."
- )
- tx.wait_to_complete()
-
- print("Pool (after providing liquidity): ")
- print(pair_contract.query({"pool": {}}), "\n")
-
- # Withdraw Liquidity
- LP_token_balance = liq_token_contract.query(
- {"balance": {"address": str(wallet.address())}}
- )["balance"]
-
- withdraw_msg = '{"withdraw_liquidity": {}}'
- withdraw_msg_bytes = withdraw_msg.encode("ascii")
- withdraw_msg_base64 = base64.b64encode(withdraw_msg_bytes)
- msg = str(withdraw_msg_base64)[2:-1]
-
- tx = liq_token_contract.execute(
- {
- "send": {
- "contract": pair_contract_address,
- "amount": LP_token_balance,
- "msg": msg,
- }
- },
- sender=wallet,
- )
-
- print(f"Withdrawing {LP_token_balance} from pool's total share...")
- tx.wait_to_complete()
-
- print("Pool (after withdrawing liquidity): ")
- print(pair_contract.query({"pool": {}}), "\n")
-
-
- if __name__ == "__main__":
- main()
-
-```
-
-
-
-
-
-
- Within the `main()` script we would need to provide liquidity to the pool, ensuring that the slippage tolerance parameter isn't exceeded. Liquidity is added by creating a transaction with the `"provide_liquidity"` operation. The assets being provided include CW20 tokens and atestfet tokens. These are specified in a list within the `"assets"` field of the operation. The script also sets a slippage tolerance of `0.1`, meaning that the price impact of the liquidity provision must be within 10% of the expected value. The transaction is executed with `execute()` method, specifying the `"provide_liquidity"` operation. The `sender` parameter is set to the user's wallet, and the `funds` parameter includes the amount of atestfet tokens being provided. A message is printed indicating the amount of CW20 and atestfet tokens being provided to the liquidity pool.
-
- Afterwards, the script initiates a withdrawal of liquidity from the pool. This involves creating a transaction with the `"withdraw_liquidity"` operation. The LP token balance is queried using `query()` method to determine the amount of LP tokens held by the user. A withdrawal message is constructed in JSON format and then encoded and base64-encoded to be included in the transaction. The transaction is executed with the `execute()`, specifying the `"send"` operation. The `contract` parameter is set to the pair contract address, the `amount` parameter is set to the LP token balance, and the `msg` parameter includes the withdrawal message. A message is printed indicating the amount of LP tokens being withdrawn from the pool. Also, the LP balance is printed after withdrawal take place.
-
- In summary, the main function orchestrates a series of actions, simulating interactions with a liquidity pool. These actions include swapping tokens, providing liquidity, and withdrawing liquidity, and the state of the pool is printed at different stages to provide feedback to the user.
-
-5. Save the script.
-
-The overall script should be as follows:
-
-
-
-
-
-
-
- ```py copy filename="aerial_liquidity_pool.py"
-
- import argparse
- import base64
- from cosmpy.aerial.client import LedgerClient, NetworkConfig
- from cosmpy.aerial.contract import LedgerContract
- from cosmpy.aerial.faucet import FaucetApi
- from cosmpy.aerial.wallet import LocalWallet
-
-
- def _parse_commandline():
- parser = argparse.ArgumentParser()
- parser.add_argument(
- "swap_amount",
- type=int,
- nargs="?",
- default=10000,
- help="atestfet swap amount to get some cw20 tokens on wallet's address",
- )
- parser.add_argument(
- "cw20_liquidity_amount",
- type=int,
- nargs="?",
- default=100,
- help="amount of cw20 tokens that will be provided to LP",
- )
- parser.add_argument(
- "native_liquidity_amount",
- type=int,
- nargs="?",
- default=2470,
- help="amount of atestfet tokens that will be provided to LP",
- )
- return parser.parse_args()
-
-
- def main():
- """Run main."""
- args = _parse_commandline()
-
- # Define any wallet
- wallet = LocalWallet.generate()
-
- # Network configuration
- ledger = LedgerClient(NetworkConfig.latest_stable_testnet())
-
- # Add tokens to wallet
- faucet_api = FaucetApi(NetworkConfig.latest_stable_testnet())
- faucet_api.get_wealth(wallet.address())
-
- # Define cw20, pair and liquidity token contracts
- token_contract_address = (
- "fetch1qr8ysysnfxmqzu7cu7cq7dsq5g2r0kvkg5e2wl2fnlkqss60hcjsxtljxl"
- )
- pair_contract_address = (
- "fetch1vgnx2d46uvyxrg9pc5mktkcvkp4uflyp3j86v68pq4jxdc8j4y0s6ulf2a"
- )
- liq_token_contract_address = (
- "fetch1alzhf9yhghud3qhucdjs895f3aek2egfq44qm0mfvahkv4jukx4qd0ltxx"
- )
-
- token_contract = LedgerContract(
- path=None, client=ledger, address=token_contract_address
- )
- pair_contract = LedgerContract(
- path=None, client=ledger, address=pair_contract_address
- )
- liq_token_contract = LedgerContract(
- path=None, client=ledger, address=liq_token_contract_address
- )
-
- print("Pool (initial state): ")
- print(pair_contract.query({"pool": {}}), "\n")
-
- # Swap atestfet for CW20 tokens
- swap_amount = str(args.swap_amount)
- native_denom = "atestfet"
-
- tx = pair_contract.execute(
- {
- "swap": {
- "offer_asset": {
- "info": {"native_token": {"denom": native_denom}},
- "amount": swap_amount,
- }
- }
- },
- sender=wallet,
- funds=swap_amount + native_denom,
- )
-
- print(f"Swapping {swap_amount + native_denom} for CW20 Tokens...")
- tx.wait_to_complete()
-
- print("Pool (after swap): ")
- print(pair_contract.query({"pool": {}}), "\n")
-
- # To provide cw20 token to LP, increase your allowance first
- cw20_liquidity_amount = str(args.cw20_liquidity_amount)
- native_liquidity_amount = str(args.native_liquidity_amount)
-
- tx = token_contract.execute(
- {
- "increase_allowance": {
- "spender": pair_contract_address,
- "amount": cw20_liquidity_amount,
- "expires": {"never": {}},
- }
- },
- wallet,
- )
-
- print("Increasing Allowance...")
- tx.wait_to_complete()
-
- # Provide Liquidity
- # Liquidity should be added so that the slippage tolerance parameter isn't exceeded
-
- tx = pair_contract.execute(
- {
- "provide_liquidity": {
- "assets": [
- {
- "info": {"token": {"contract_addr": token_contract_address}},
- "amount": cw20_liquidity_amount,
- },
- {
- "info": {"native_token": {"denom": native_denom}},
- "amount": native_liquidity_amount,
- },
- ],
- "slippage_tolerance": "0.1",
- }
- },
- sender=wallet,
- funds=native_liquidity_amount + native_denom,
- )
-
- print(
- f"Providing {native_liquidity_amount + native_denom} and {cw20_liquidity_amount}CW20 tokens to Liquidity Pool..."
- )
- tx.wait_to_complete()
-
- print("Pool (after providing liquidity): ")
- print(pair_contract.query({"pool": {}}), "\n")
-
- # Withdraw Liquidity
- LP_token_balance = liq_token_contract.query(
- {"balance": {"address": str(wallet.address())}}
- )["balance"]
-
- withdraw_msg = '{"withdraw_liquidity": {}}'
- withdraw_msg_bytes = withdraw_msg.encode("ascii")
- withdraw_msg_base64 = base64.b64encode(withdraw_msg_bytes)
- msg = str(withdraw_msg_base64)[2:-1]
-
- tx = liq_token_contract.execute(
- {
- "send": {
- "contract": pair_contract_address,
- "amount": LP_token_balance,
- "msg": msg,
- }
- },
- sender=wallet,
- )
-
- print(f"Withdrawing {LP_token_balance} from pool's total share...")
- tx.wait_to_complete()
-
- print("Pool (after withdrawing liquidity): ")
- print(pair_contract.query({"pool": {}}), "\n")
-
-
- if __name__ == "__main__":
- main()
-
-```
-
-
-
-
-
-
diff --git a/pages/guides/fetch-network/cosmpy/use-cases/oracles.mdx b/pages/guides/fetch-network/cosmpy/use-cases/oracles.mdx
deleted file mode 100644
index 506b97185..000000000
--- a/pages/guides/fetch-network/cosmpy/use-cases/oracles.mdx
+++ /dev/null
@@ -1,602 +0,0 @@
-import { CodeGroup, CodeSegment, DocsCode, GithubCodeSegment } from "../../../../../components/code";
-
-# Oracles
-
-## Introduction
-
-**Oracles** are entities that can update state variables in smart contracts and whose goal is usually to accurately estimate or predict some real world quantity or quantities. These quantities can then be used in the logic of other smart contracts. This guide shows how to write a CosmPy script that deploys and updates an oracle contract with a coin price, and another script that deploys a contract that queries this coin price.
-
-## Walk-through
-
-Here we provide an overview guide for setting up your own aerial oracle in few steps.
-
-We initially need to download the binaries for both contracts, which can be done as follows:
-
- ```
- wget https://raw.githubusercontent.com/fetchai/agents-aea/develop/packages/fetchai/contracts/oracle/build/oracle.wasm
- wget https://raw.githubusercontent.com/fetchai/agents-aea/develop/packages/fetchai/contracts/oracle_client/build/oracle_client.wasm
- ```
-
-### Aerial oracle
-
-1. First of all, create a Python script and name it:
-
-
-
- ```py copy filename="mac"
- touch aerial_oracle.py
- ```
-
-
-
- ```py copy filename="windows"
- echo. > aerial_oracle.py
- ```
-
-
-
- ```py copy filename="ubuntu"
- touch aerial_oracle.py
- ```
-
-
-
-2. We would then also require the following imports:
-
-
-
-
-
-
-
- ```py copy filename="aerial_oracle.py"
-
- import argparse
- from time import sleep
-
- import requests
-
- from cosmpy.aerial.client import LedgerClient, NetworkConfig
- from cosmpy.aerial.contract import LedgerContract
- from cosmpy.aerial.faucet import FaucetApi
- from cosmpy.aerial.wallet import LocalWallet
- from cosmpy.crypto.address import Address
-
-```
-
-
-
-
-
-
-3. We then need to choose a data source for the coin price, the update interval, the decimal precision, and the decimal timeout for the oracle value:
-
-
-
-
-
-
-
- ```py copy filename="aerial_oracle.py"
-
- COIN_PRICE_URL = (
- "https://api.coingecko.com/api/v3/simple/price?ids=fetch-ai&vs_currencies=usd"
- )
- UPDATE_INTERVAL_SECONDS = 10
- ORACLE_VALUE_DECIMALS = 5
- DEFAULT_TIMEOUT = 60.0
-
-```
-
-
-
-
-
-
-4. We then proceed and define a `_parse_commandline()` function by first importing the `argparse` module, which is a standard Python module for parsing command-line arguments:
-
-
-
-
-
-
-
- ```py copy filename="aerial_oracle.py"
-
- def _parse_commandline():
- parser = argparse.ArgumentParser()
- parser.add_argument(
- "contract_path", help="The path to the oracle contract to upload"
- )
- parser.add_argument(
- "contract_address",
- nargs="?",
- type=Address,
- help="The address of the oracle contract if already deployed",
- )
- return parser.parse_args()
-
-```
-
-
-
-
-
-
- This first creates an argument `parser` object. The `ArgumentParser` class provides a way to specify the arguments your script should accept and automatically generates help messages and error messages. We then use `add_argument()` to add a positional argument named `contract_path`. This argument is required and should be a path to the oracle contract that you want to upload. The help argument provides a description of what this argument does. We further add another positional argument named `contract_address`. This argument is optional (`nargs="?"` allows it to be omitted), and it should be of type `Address`. The `type` argument specifies the type of the argument. In this case, `Address` is a custom type or class used to represent addresses. The `help` argument provides a description of what this argument does. At the end, we parse the command-line arguments provided when the script is executed. It returns an object that contains the values of the parsed arguments.
-
-5. We then need to proceed and define our `main()` function:
-
-
-
-
-
-
-
- ```py copy filename="aerial_oracle.py"
-
- def main():
- """Run main."""
- args = _parse_commandline()
-
- wallet = LocalWallet.generate()
-
- ledger = LedgerClient(NetworkConfig.fetchai_stable_testnet())
- faucet_api = FaucetApi(NetworkConfig.fetchai_stable_testnet())
-
- wallet_balance = ledger.query_bank_balance(wallet.address())
-
- while wallet_balance < (10 ** 18):
- print("Providing wealth to wallet...")
- faucet_api.get_wealth(wallet.address())
- wallet_balance = ledger.query_bank_balance(wallet.address())
-
- contract = LedgerContract(args.contract_path, ledger, address=args.contract_address)
-
- if not args.contract_address:
- instantiation_message = {"fee": "100"}
- contract.deploy(instantiation_message, wallet, funds="1atestfet")
-
- print(f"Oracle contract deployed at: {contract.address}")
-
- grant_role_message = {"grant_oracle_role": {"address": wallet}}
- contract.execute(grant_role_message, wallet).wait_to_complete()
-
- print(f"Oracle role granted to address: {wallet}")
-
- while True:
- resp = requests.get(COIN_PRICE_URL, timeout=DEFAULT_TIMEOUT).json()
- price = resp["fetch-ai"]["usd"]
- value = int(price * 10 ** ORACLE_VALUE_DECIMALS)
-
- update_message = {
- "update_oracle_value": {
- "value": str(value),
- "decimals": str(ORACLE_VALUE_DECIMALS),
- }
- }
- contract.execute(update_message, wallet).wait_to_complete()
-
- print(f"Oracle value updated to: {price} USD")
- print(f"Next update in {UPDATE_INTERVAL_SECONDS} seconds...")
- sleep(UPDATE_INTERVAL_SECONDS)
-
-
- if __name__ == "__main__":
- main()
-
-```
-
-
-
-
-
-
- This defines our `main()` function. When we run the script, the code inside `main()` will be executed. `args = _parse_commandline()` calls the `_parse_commandline()` function that we defined earlier. It parses the command-line arguments and returns an object (`args`) containing the values of the parsed arguments. We then generate a new local wallet, and then create a client for interacting with a blockchain ledger, using `LedgerClient()` class. We configured it to use the Fetch.ai stable testnet. We then create a client for interacting with a faucet API and query the balance of the wallet's address using the `query_bank_balance()` method. We also define an initial `while` loop which continues as long as the `wallet_balance` is less than `10**18`. Inside this first loop: it prints a message indicating that wealth is being provided to the wallet, then it calls the faucet API to get wealth for the wallet, and it updates the `wallet_balance` by querying the bank balance again.
-
- After this, we create a `contract` object using `LedgerContract()`: this takes the path to the oracle contract file, the ledger client, and optionally, the contract address. `if not args.contract_address:` condition checks if `args.contract_address` is not provided. If it has not been provided, it means the contract has not been deployed yet. We then set up an instantiation message with a fee of 100. We can then deploy the contract using the provided instantiation message, the wallet, and a specified fund source (`"1atestfet"` in this case).
-
- The `print()` function prints the address of the deployed oracle contract. After this, we define a `grant_role_message` object which sets up a message to grant the oracle role to the address associated with the wallet, and execute the message to grant the oracle role and wait for the transaction to complete. The following `print()` function prints a message indicating that the oracle role has been granted to the address associated with the wallet.
-
- We can finally define a second `while` loop which runs indefinitely: it sends a GET request to a URL (`COIN_PRICE_URL`) to retrieve coin prices, then extracts the price in USD. It then calculates a value based on the price and the specified decimal precision (`ORACLE_VALUE_DECIMALS`), and sets up an update message with the new oracle value. Lastly, it executes the update message, waits for the transaction to complete, prints the updated oracle value and indicates when the next update will occur.
-
- This script let us interact with a blockchain ledger, deploy a contract, and perform oracle-related tasks such as updating values based on external data.
-
-6. Save the script.
-
-The overall script should be as follows:
-
-
-
-
-
-
-
- ```py copy filename="aerial_oracle.py"
-
- import argparse
- from time import sleep
-
- import requests
-
- from cosmpy.aerial.client import LedgerClient, NetworkConfig
- from cosmpy.aerial.contract import LedgerContract
- from cosmpy.aerial.faucet import FaucetApi
- from cosmpy.aerial.wallet import LocalWallet
- from cosmpy.crypto.address import Address
-
- COIN_PRICE_URL = (
- "https://api.coingecko.com/api/v3/simple/price?ids=fetch-ai&vs_currencies=usd"
- )
- UPDATE_INTERVAL_SECONDS = 10
- ORACLE_VALUE_DECIMALS = 5
- DEFAULT_TIMEOUT = 60.0
-
-
- def _parse_commandline():
- parser = argparse.ArgumentParser()
- parser.add_argument(
- "contract_path", help="The path to the oracle contract to upload"
- )
- parser.add_argument(
- "contract_address",
- nargs="?",
- type=Address,
- help="The address of the oracle contract if already deployed",
- )
- return parser.parse_args()
-
-
- def main():
- """Run main."""
- args = _parse_commandline()
-
- wallet = LocalWallet.generate()
-
- ledger = LedgerClient(NetworkConfig.fetchai_stable_testnet())
- faucet_api = FaucetApi(NetworkConfig.fetchai_stable_testnet())
-
- wallet_balance = ledger.query_bank_balance(wallet.address())
-
- while wallet_balance < (10 ** 18):
- print("Providing wealth to wallet...")
- faucet_api.get_wealth(wallet.address())
- wallet_balance = ledger.query_bank_balance(wallet.address())
-
- contract = LedgerContract(args.contract_path, ledger, address=args.contract_address)
-
- if not args.contract_address:
- instantiation_message = {"fee": "100"}
- contract.deploy(instantiation_message, wallet, funds="1atestfet")
-
- print(f"Oracle contract deployed at: {contract.address}")
-
- grant_role_message = {"grant_oracle_role": {"address": wallet}}
- contract.execute(grant_role_message, wallet).wait_to_complete()
-
- print(f"Oracle role granted to address: {wallet}")
-
- while True:
- resp = requests.get(COIN_PRICE_URL, timeout=DEFAULT_TIMEOUT).json()
- price = resp["fetch-ai"]["usd"]
- value = int(price * 10 ** ORACLE_VALUE_DECIMALS)
-
- update_message = {
- "update_oracle_value": {
- "value": str(value),
- "decimals": str(ORACLE_VALUE_DECIMALS),
- }
- }
- contract.execute(update_message, wallet).wait_to_complete()
-
- print(f"Oracle value updated to: {price} USD")
- print(f"Next update in {UPDATE_INTERVAL_SECONDS} seconds...")
- sleep(UPDATE_INTERVAL_SECONDS)
-
-
- if __name__ == "__main__":
- main()
-
-```
-
-
-
-
-
-
-### Oracle client
-
-Now, we will write a script that deploys a contract that can request the oracle value in exchange for the required fee.
-
-1. Let's first create a Python script and name it:
-
-
-
- ```py copy filename="mac"
- touch aerial_oracle_client.py
- ```
-
-
-
- ```py copy filename="windows"
- echo. > aerial_oracle_client.py
- ```
-
-
-
- ```py copy filename="ubuntu"
- touch aerial_oracle_client.py
- ```
-
-
-
-2. We start by importing the needed classes and define a `REQUEST_INTERVAL_SECONDS` variable:
-
-
-
-
-
-
-
- ```py copy filename="aerial_oracle_client.py"
-
- import argparse
- from time import sleep
-
- from cosmpy.aerial.client import LedgerClient, NetworkConfig
- from cosmpy.aerial.contract import LedgerContract
- from cosmpy.aerial.faucet import FaucetApi
- from cosmpy.aerial.wallet import LocalWallet
- from cosmpy.crypto.address import Address
-
- REQUEST_INTERVAL_SECONDS = 10
-
-```
-
-
-
-
-
-
-3. Like before, we proceed and define a `_parse_commandline()` function:
-
-
-
-
-
-
-
- ```py copy filename="aerial_oracle_client.py"
-
- def _parse_commandline():
- parser = argparse.ArgumentParser()
- parser.add_argument(
- "contract_path", help="The path to the oracle client contract to upload"
- )
- parser.add_argument(
- "oracle_contract_address",
- type=Address,
- help="The address of the oracle contract",
- )
- parser.add_argument(
- "contract_address",
- nargs="?",
- type=Address,
- help="The address of the oracle client contract if already deployed",
- )
- return parser.parse_args()
-
-```
-
-
-
-
-
-
- This `_parse_commandline()` function is designed to parse command-line arguments. We first create a `parser` object. This object is used to specify what command-line arguments the program should expect. We then use the `add_argument()` method to define the arguments that the program expects. In this function, there are three arguments being defined:
-
- - `contract_path`: this is a required argument. It expects a string representing the path to the oracle client contract to upload.
- - `oracle_contract_address`: this is also a required argument. It expects an `Address` object representing the address of the oracle contract.
- - `contract_address`: this is an optional argument. It expects an `Address` object and is used to specify the address of the oracle client contract if it has already been deployed. The `nargs="?"` indicates that this argument is optional.
-
- The function returns an object containing the parsed values.
-
-4. We can now define our `main()` function.
-
-
-
-
-
-
-
- ```py copy filename="aerial_oracle_client.py"
-
- def main():
- """Run main."""
- args = _parse_commandline()
-
- wallet = LocalWallet.generate()
-
- ledger = LedgerClient(NetworkConfig.fetchai_stable_testnet())
- faucet_api = FaucetApi(NetworkConfig.fetchai_stable_testnet())
-
- wallet_balance = ledger.query_bank_balance(wallet.address())
-
- while wallet_balance < (10**18):
- print("Providing wealth to wallet...")
- faucet_api.get_wealth(wallet.address())
- wallet_balance = ledger.query_bank_balance(wallet.address())
-
- contract = LedgerContract(args.contract_path, ledger, address=args.contract_address)
-
- if not args.contract_address:
- instantiation_message = {
- "oracle_contract_address": str(args.oracle_contract_address)
- }
- contract.deploy(instantiation_message, wallet)
-
- print(f"Oracle client contract deployed at: {contract.address}")
-
- while True:
- request_message = {"query_oracle_value": {}}
- contract.execute(
- request_message, wallet, funds="100atestfet"
- ).wait_to_complete()
-
- result = contract.query({"oracle_value": {}})
- print(f"Oracle value successfully retrieved: {result}")
-
- sleep(REQUEST_INTERVAL_SECONDS)
-
- if __name__ == "__main__":
- main()
-
-```
-
-
-
-
-
-
- The first line calls the `_parse_commandline()` function that we defined earlier. It will parse the command-line arguments and return an object (`args`) containing the parsed values. We proceed and generate a new local wallet, `wallet`, and then create a new `ledger` object for interacting with the blockchain or ledger system, using `LedgerClient()`. Afterwards, we create a `FaucetApi` object, `faucet_api`, which is used for interacting with the faucet service. We use the `query_bank_balance()` method to query the balance associated with the wallet's address. We then define a `while` loop which will continue as long as the `wallet_balance` is less than `10**18`. This is to ensure the wallet has a sufficient balance. Afterwards, we use the `get_wealth()` method to add wealth to the wallet, and then create a new `LedgerContract()` object which takes the `contract_path`, the `ledger` object, and an optional `contract_address`. `if not args.contract_address:` checks if `args.contract_address` is not provided. If it has not been provided, it means that the contract has not been deployed yet. We then create an `instantiation_message`, which contains the data needed for deploying the contract. `contract.deploy()` deploys the contract with the provided `instantiation_message` and the `wallet`. The code then prints out the address of the deployed contract. Finally, we define a second loop starting with `while True:` which repeatedly executes the following steps:
-
- - It creates a request message, which is used to query the oracle value.
- - It executes the contract function call with the request message, using the wallet for authorization. The funds argument is set to `"100atestfet"`.
- - It queries the contract for the oracle value.
- - It prints out the retrieved oracle value.
- - It finally waits for a specified number of seconds (defined by `REQUEST_INTERVAL_SECONDS`) before the next iteration. This is likely to prevent overloading the system with requests.
-
-5. Save the script.
-
-The overall script should be as follows:
-
-
-
-
-
-
-
- ```py copy filename="aerial_oracle_client.py"
-
- import argparse
- from time import sleep
-
- from cosmpy.aerial.client import LedgerClient, NetworkConfig
- from cosmpy.aerial.contract import LedgerContract
- from cosmpy.aerial.faucet import FaucetApi
- from cosmpy.aerial.wallet import LocalWallet
- from cosmpy.crypto.address import Address
-
- REQUEST_INTERVAL_SECONDS = 10
-
- def _parse_commandline():
- parser = argparse.ArgumentParser()
- parser.add_argument(
- "contract_path", help="The path to the oracle client contract to upload"
- )
- parser.add_argument(
- "oracle_contract_address",
- type=Address,
- help="The address of the oracle contract",
- )
- parser.add_argument(
- "contract_address",
- nargs="?",
- type=Address,
- help="The address of the oracle client contract if already deployed",
- )
- return parser.parse_args()
-
- def main():
- """Run main."""
- args = _parse_commandline()
-
- wallet = LocalWallet.generate()
-
- ledger = LedgerClient(NetworkConfig.fetchai_stable_testnet())
- faucet_api = FaucetApi(NetworkConfig.fetchai_stable_testnet())
-
- wallet_balance = ledger.query_bank_balance(wallet.address())
-
- while wallet_balance < (10**18):
- print("Providing wealth to wallet...")
- faucet_api.get_wealth(wallet.address())
- wallet_balance = ledger.query_bank_balance(wallet.address())
-
- contract = LedgerContract(args.contract_path, ledger, address=args.contract_address)
-
- if not args.contract_address:
- instantiation_message = {
- "oracle_contract_address": str(args.oracle_contract_address)
- }
- contract.deploy(instantiation_message, wallet)
-
- print(f"Oracle client contract deployed at: {contract.address}")
-
- while True:
- request_message = {"query_oracle_value": {}}
- contract.execute(
- request_message, wallet, funds="100atestfet"
- ).wait_to_complete()
-
- result = contract.query({"oracle_value": {}})
- print(f"Oracle value successfully retrieved: {result}")
-
- sleep(REQUEST_INTERVAL_SECONDS)
-
- if __name__ == "__main__":
- main()
-
-```
-
-
-
-
-
-
-Bear in mind that specific data related to the oracle's address and contract need to be provided by hand based on your personalized information!
diff --git a/pages/guides/fetch-network/cosmpy/use-cases/stake-auto-compounder.mdx b/pages/guides/fetch-network/cosmpy/use-cases/stake-auto-compounder.mdx
deleted file mode 100644
index e28d7a421..000000000
--- a/pages/guides/fetch-network/cosmpy/use-cases/stake-auto-compounder.mdx
+++ /dev/null
@@ -1,432 +0,0 @@
-import { CodeGroup, CodeSegment, DocsCode, GithubCodeSegment } from "../../../../../components/code";
-
-# Stake auto-compounder
-
-## Introduction
-
-The Stake Auto-Compounder is a CosmPy based use case developed using Python and designed to automate the process of staking tokens in a blockchain network, claiming rewards, and compounding those rewards by re-delegating them to a validator. When an account delegates tokens to a network's validator, it will start generating rewards proportionally to the amount of [`Stake` ↗️](/guides/fetch-network/cosmpy/staking) delegated. But since rewards are not automatically added to your stake and therefore do not contribute to future rewards, we can perform a compounding strategy to generate exponential rewards.
-
-## Delegate your tokens
-
-The first thing we need to do is delegate some tokens to a `validator`. You can do so by using a [`Wallet` ↗️](/guides/fetch-network/cosmpy/creating-wallet) and specifying the validator address and amount. you can delegate tokens to a specific validator by using the `delegate_tokens` method of the `ledger_client` object and specifying the validator's address, the amount of tokens and the wallet from which the delegation is made:
-
- ```py copy
- validators = ledger_client.query_validators()
-
- # choose any validator
- validator = validators[0]
-
- key = PrivateKey("FX5BZQcr+FNl2usnSIQYpXsGWvBxKLRDkieUNIvMOV7=")
- wallet = LocalWallet(key)
-
- # delegate some tokens to this validator
- tx = ledger_client.delegate_tokens(validator.address, 9000000000000000000, wallet)
- tx.wait_to_complete()
- ```
-
-## Auto-compounder
-
-We can write a script helping us claiming rewards and delegating the rewarded tokens back to the `validator` of choice. This way we keep growing our `Stake` given the generated compounded rewards on such staked amount. We first need to define the `time limit` and the compounding `period`.
-
-Importantly, bear in mind that each time an account performs a claim or a delegate a transaction, it has to pay certain fees. Therefore, the compounding period has to be long enough to generate sufficient rewards to exceed the fees that will be paid in each transaction and generate a profit.
-
-After having defined such parameters, we can then start a timer that claims rewards and delegates them in each time period:
-
- ```py copy
- time_check = 0
- start_time = time.monotonic()
- time.sleep(period)
-
- # query, claim and delegate rewards after time period
- while time_check < time_limit:
-
- begin = time.monotonic()
-
- summary = ledger_client.query_staking_summary(wallet.address())
- print(f"Staked: {summary.total_staked}")
-
- balance_before = ledger_client.query_bank_balance(wallet.address())
-
- tx = ledger_client.claim_rewards(validator.address, wallet)
- tx.wait_to_complete()
-
- balance_after = ledger_client.query_bank_balance(wallet.address())
-
- # reward after any fees
- true_reward = balance_after - balance_before
-
- if true_reward > 0:
-
- print(f"Staking {true_reward} (reward after fees)")
-
- tx = ledger_client.delegate_tokens(validator.address, true_reward, wallet)
- tx.wait_to_complete()
-
- else:
- print("Fees from claim rewards transaction exceeded reward")
-
- end = time.monotonic()
-
- time.sleep(period-(end-begin))
- time_check = time.monotonic() - start_time
- ```
-
- In the code snippet above we defined a while loop running until the timer exceeds the `time limit`. Each loop will last the time specified in `period`. We query the balance before and after claiming rewards to get the value of the reward after any fees. If the true reward value is positive, we delegate those tokens to the validator, if it is negative, it means that the fees from claiming and delegating transactions exceeded the rewards, and therefore we will not delegate.
-
-## Walk-through
-
-Below we provide a step-by-step guide to create an auto compounder using the `cosmpy.aerial` package.
-
-1. First of all, create a Python script and name it:
-
-
-
- ```py copy filename="mac"
- touch aerial_compounder.py
- ```
-
-
-
- ```py copy filename="windows"
- echo. > aerial_compounder.py
- ```
-
-
-
- ```py copy filename="ubuntu"
- touch aerial_compounder.py
- ```
-
-
-
-2. We need to import the necessary modules, including `argparse`, `time`, and various modules from the `cosmpy.aerial` package:
-
-
-
-
-
-
-
- ```py copy filename="aerial_compounder.py"
-
- import argparse
- import time
-
- from cosmpy.aerial.client import LedgerClient
- from cosmpy.aerial.config import NetworkConfig
- from cosmpy.aerial.faucet import FaucetApi
- from cosmpy.aerial.wallet import LocalWallet
-
-```
-
-
-
-
-
-
-3. We now need to define a `_parse_commandline()` function responsible for parsing command-line arguments when the script is being executed:
-
-
-
-
-
-
-
- ```py copy filename="aerial_compounder.py"
-
- def _parse_commandline():
- parser = argparse.ArgumentParser()
- parser.add_argument(
- "initial_stake",
- type=int,
- nargs="?",
- default=9000000000000000000,
- help="Initial amount of atestfet to delegate to validator",
- )
- parser.add_argument(
- "time_limit",
- type=int,
- nargs="?",
- default=600,
- help="total time",
- )
- parser.add_argument(
- "period",
- type=int,
- nargs="?",
- default=100,
- help="compounding period",
- )
-
- return parser.parse_args()
-
-```
-
-
-
-
-
-
- We first create a `parser` instance of the `ArgumentParser` class using the `argparse` module. Argument parsers are used to specify and parse command-line arguments. The `add_argument()` method is used to specify the arguments that the script will accept. It takes several parameters, including:
-
- - `name`: the name of the argument.
- - `type`: the type to which the argument should be converted (in this case, `int`).
- - `nargs`: the number of arguments expected (in this case, `"?"` means zero or one argument).
- - `default`: the default value if the argument is not provided.
- - `help`: a brief description of the argument, which will be displayed if the user asks for help with the script.
-
- Three arguments are defined in this function:
-
- - `initial_stake`: the initial amount of tokens to delegate to a validator. It expects an integer and has a default value of `9000000000000000000`.
- - `time_limit`: the total time limit for the compounder. It expects an integer (representing seconds) and has a default value of `600` seconds (10 minutes).
- - `period`: the compounding period, which is the interval between each compounding operation. It expects an integer (also in seconds) and has a default value of `100` seconds.
-
- The last line of the snippet above, `parser.parse_args()`, parses the command-line arguments provided when the script is executed. The function returns the parsed arguments object.
-
-4. We are now ready to define our `main()` function:
-
-
-
-
-
-
-
- ```py copy filename="aerial_compounder.py"
-
- def main():
- """Run main."""
- args = _parse_commandline()
-
- ledger = LedgerClient(NetworkConfig.fetchai_stable_testnet())
- faucet_api = FaucetApi(NetworkConfig.fetchai_stable_testnet())
-
- # get all the active validators on the network
- validators = ledger.query_validators()
-
- # choose any validator
- validator = validators[0]
-
- alice = LocalWallet.generate()
-
- wallet_balance = ledger.query_bank_balance(alice.address())
- initial_stake = args.initial_stake
-
- while wallet_balance < (initial_stake):
- print("Providing wealth to wallet...")
- faucet_api.get_wealth(alice.address())
- wallet_balance = ledger.query_bank_balance(alice.address())
-
- # delegate some tokens to this validator
- tx = ledger.delegate_tokens(validator.address, initial_stake, alice)
- tx.wait_to_complete()
-
- # set time limit and compounding period in seconds
- time_limit = args.time_limit
- period = args.period
-
- time_check = 0
- start_time = time.monotonic()
- time.sleep(period)
-
- # query, claim and stake rewards after time period
- while time_check < time_limit:
-
- begin = time.monotonic()
-
- summary = ledger.query_staking_summary(alice.address())
- print(f"Staked: {summary.total_staked}")
-
- balance_before = ledger.query_bank_balance(alice.address())
-
- tx = ledger.claim_rewards(validator.address, alice)
- tx.wait_to_complete()
-
- balance_after = ledger.query_bank_balance(alice.address())
-
- # reward after any fees
- true_reward = balance_after - balance_before
-
- if true_reward > 0:
-
- print(f"Staking {true_reward} (reward after fees)")
-
- tx = ledger.delegate_tokens(validator.address, true_reward, alice)
- tx.wait_to_complete()
-
- else:
- print("Fees from claim rewards transaction exceeded reward")
-
- print()
-
- end = time.monotonic()
- time.sleep(period - (end - begin))
- time_check = time.monotonic() - start_time
-
-
- if __name__ == "__main__":
- main()
-
-```
-
-
-
-
-
-
- The first line calls the `_parse_commandline()` function we defined earlier. It returns an object with the parsed command-line arguments. We then create two objects:
-
- - A `ledger` instance of the `Ledger Client` class configured for the Fetch.ai stable testnet. This client will be used to interact with the blockchain network.
- - A `faucet_api` instance of the `Faucet API` class configured for the Fetch.ai stable testnet. This API is used for providing additional funds to the wallet if needed.
-
- We then need to get all the active validators on the network by using the `query_validators()` method. After this, we choose a validator and create a new wallet named `alice` using `LocalWallet.generate()` and check the balance of the `alice` wallet. If the balance is less than the initial stake, it enters a loop to provide wealth to the wallet using the faucet API until the balance reaches the specified initial stake. We can now delegate the initial stake of tokens to the chosen validator using the `delegate_tokens()` method.
-
- We proceed by setting time limits and periods. `time_limit = args.time_limit` sets the time limit based on the command-line argument, whereas `period = args.period` sets the compounding period based on the command-line argument. After this, we define the compounding loop, similar to what was described in the first part of this guide: it iterates over a specified time period, queries staking summary, claims rewards, and either stakes the rewards or skips if fees exceed rewards. Time management is important here: indeed, the loop keeps track of time using `time.monotonic()` to ensure it does not exceed the specified time limit. It waits for the specified period before starting the next compounding cycle.
-
-5. Save the script.
-
-The overall script should look as follows:
-
-
-
-
-
-
-
- ```py copy filename="aerial_compounder.py"
-
- import argparse
- import time
-
- from cosmpy.aerial.client import LedgerClient
- from cosmpy.aerial.config import NetworkConfig
- from cosmpy.aerial.faucet import FaucetApi
- from cosmpy.aerial.wallet import LocalWallet
-
-
- def _parse_commandline():
- parser = argparse.ArgumentParser()
- parser.add_argument(
- "initial_stake",
- type=int,
- nargs="?",
- default=9000000000000000000,
- help="Initial amount of atestfet to delegate to validator",
- )
- parser.add_argument(
- "time_limit",
- type=int,
- nargs="?",
- default=600,
- help="total time",
- )
- parser.add_argument(
- "period",
- type=int,
- nargs="?",
- default=100,
- help="compounding period",
- )
-
- return parser.parse_args()
-
-
- def main():
- """Run main."""
- args = _parse_commandline()
-
- ledger = LedgerClient(NetworkConfig.fetchai_stable_testnet())
- faucet_api = FaucetApi(NetworkConfig.fetchai_stable_testnet())
-
- # get all the active validators on the network
- validators = ledger.query_validators()
-
- # choose any validator
- validator = validators[0]
-
- alice = LocalWallet.generate()
-
- wallet_balance = ledger.query_bank_balance(alice.address())
- initial_stake = args.initial_stake
-
- while wallet_balance < (initial_stake):
- print("Providing wealth to wallet...")
- faucet_api.get_wealth(alice.address())
- wallet_balance = ledger.query_bank_balance(alice.address())
-
- # delegate some tokens to this validator
- tx = ledger.delegate_tokens(validator.address, initial_stake, alice)
- tx.wait_to_complete()
-
- # set time limit and compounding period in seconds
- time_limit = args.time_limit
- period = args.period
-
- time_check = 0
- start_time = time.monotonic()
- time.sleep(period)
-
- # query, claim and stake rewards after time period
- while time_check < time_limit:
-
- begin = time.monotonic()
-
- summary = ledger.query_staking_summary(alice.address())
- print(f"Staked: {summary.total_staked}")
-
- balance_before = ledger.query_bank_balance(alice.address())
-
- tx = ledger.claim_rewards(validator.address, alice)
- tx.wait_to_complete()
-
- balance_after = ledger.query_bank_balance(alice.address())
-
- # reward after any fees
- true_reward = balance_after - balance_before
-
- if true_reward > 0:
-
- print(f"Staking {true_reward} (reward after fees)")
-
- tx = ledger.delegate_tokens(validator.address, true_reward, alice)
- tx.wait_to_complete()
-
- else:
- print("Fees from claim rewards transaction exceeded reward")
-
- print()
-
- end = time.monotonic()
- time.sleep(period - (end - begin))
- time_check = time.monotonic() - start_time
-
-
- if __name__ == "__main__":
- main()
-
-```
-
-
-
-
-
-
diff --git a/pages/guides/fetch-network/cosmpy/use-cases/stake-optimizer.mdx b/pages/guides/fetch-network/cosmpy/use-cases/stake-optimizer.mdx
deleted file mode 100644
index ed8e8f6c2..000000000
--- a/pages/guides/fetch-network/cosmpy/use-cases/stake-optimizer.mdx
+++ /dev/null
@@ -1,488 +0,0 @@
-import { CodeGroup, CodeSegment, DocsCode, GithubCodeSegment } from "../../../../../components/code";
-
-# Stake optimizer
-
-## Getting started
-
-Whenever we delegate tokens to a validator for a determined period, you can use the [`auto-compounder` ↗️](/guides/fetch-network/cosmpy/use-cases/stake-auto-compounder) to get increasing rewards. You can maximize your rewards for a given staking period by selecting an optimal compounding period. To do this, you will need to follow these steps:
-
- - **Set and query variables**: when calculating staking rewards, you need to set and query variables such as staking parameters, transaction fees, and network parameters.
- - **Calculate reward rate**: after you select and query all the variables needed, you will calculate the reward rate.
- - **Calculate optimal compounding period**: you will calculate the optimal compounding period that will maximize your rewards.
-
-First of all, we need to define a network to work with:
-
-```py copy
-from cosmpy.aerial.client import LedgerClient
-from cosmpy.aerial.config import NetworkConfig
-
-ledger = LedgerClient(NetworkConfig.fetchai_stable_testnet())
-```
-
-## Set and query variables
-### Staking variables
-
-First, we need to define the desired amount and the total period that we would like to stake in: `initial_stake` and `total_period` variables. Here we will stake 50 TESTFET for 60000 minutes. For this guide, we will work with minutes as a time unit:
-
-```py copy
-initial_stake = 50000000000000000000
-total_period = 60000
-```
-
-### Validator selection and variables
-
-We are now ready to select a validator to delegate our tokens. We can do this by analyzing which one has the lowest commission and a reasonable amount of stake delegated compared to the total stake.
-
-```py copy
-from cosmpy.protos.cosmos.staking.v1beta1.query_pb2 import QueryValidatorsRequest
-
-req = QueryValidatorsRequest()
-resp = ledger.staking.Validators(req)
-
-# Calculate the total stake currently in the testnet
-# Status = 3 means that the validator is bonded
-validators_stake = [int(validator.tokens) for validator in resp.validators if validator.status == 3]
-total_stake = sum(validators_stake)
-
-# For every bonded validator, we print commission and percentage of total stake
-print("MONIKER COMMISSION % of TOTAL STAKE")
-for validator in resp.validators:
- if validator.status == 3:
- moniker = validator.description.moniker
- commission = int(validator.commission.commission_rates.rate)/1e18*100
- print(moniker[:10]," ", commission,"% ", round(int(validator.tokens)/total_stake*100,3),"%")
-```
-
-Once you run the code above, you will observe each validator commission rate and its percentage delegated of the total stake. The most important parameter to observe in each validator is the commission it takes from rewards. We should always select a validator with the lower commission as long as it has a reasonable stake compared with the total stake.
-
-```py copy
-# get all the active validators on the network
-validators = ledger.query_validators()
-
-# Query info of selected validator
-selected_validator = "validator0"
-validator = [v for v in validators if v.moniker == selected_validator][0]
-query_validator = [v for v in resp.validators if v.description.moniker == selected_validator][0]
-
-# Set the commission %
-commission = int(query_validator.commission.commission_rates.rate)/1e18
-
-# Set percentage delegated of total stake
-pct_delegated = initial_stake/total_stake
-```
-
-In this case, at the moment the code is run, all validators have the same commission, therefore, we simply select the validator with the highest stake, which is validator0. Feel free to select the most convenient validator when you run the code above. We will save the variables `commission` and the fraction `pct_delegated` of our `initial_stake` to the `total_stake` to use them both later on.
-
-### Estimate transaction fees
-
-We now need to know an estimate of the transaction fees we will face every time we claim rewards and delegate tokens. For that, both claim rewards and delegate tokens transactions were combined into a single multi-msg transaction to simulate the total fees.
-
-```py copy
-from cosmpy.aerial.client.distribution import create_withdraw_delegator_reward
-from cosmpy.aerial.client.staking import create_delegate_msg
-from cosmpy.aerial.tx import SigningCfg
-from cosmpy.aerial.wallet import LocalWallet
-from cosmpy.crypto.keypairs import PrivateKey
-from cosmpy.crypto.address import Address
-from cosmpy.aerial.tx import Transaction
-
-# Use any address with at least the amount of initial_stake available
-key = PrivateKey("XZ5BZQcr+FNl2usnSIQYpXsGWvBxKLRDkieUNIvMOV7=")
-alice = LocalWallet(key)
-alice_address = Address(key)._display
-
-tx = Transaction()
-
-# Add delegate msg
-tx.add_message(create_delegate_msg(alice_address,validator.address,initial_stake,"atestfet"))
-
-# Add claim reward msg
-tx.add_message(create_withdraw_delegator_reward(alice_address, validator.address))
-
-account = ledger.query_account(alice.address())
-tx.seal(SigningCfg.direct(alice.public_key(), account.sequence),fee="",gas_limit=0)
-tx.sign(alice.signer(), ledger.network_config.chain_id, account.number)
-tx.complete()
-
-# simulate the fee for the transaction
-_, str_tx_fee = ledger.estimate_gas_and_fee_for_tx(tx)
-```
-
-Since the output of this function is a string, we need to convert it to an int and round it up to get a more conservative estimate for the `fee`.
-
-```py copy
-denom = "atestfet"
-tx_fee = str_tx_fee[:-len(denom)]
-
-# Add a 20% to the fee estimation to get a more conservative estimate
-fee = int(tx_fee) * 1.20
-```
-
-### Query network variables
-
-There are three network variables that we need to query since they will contribute to the staking rewards calculation: `total_supply`, `inflation`, and `community_tax`.
-
-```py copy
-# Total Supply of tokens
-req = QueryTotalSupplyRequest()
-resp = ledger.bank.TotalSupply(req)
-total_supply = float(json.loads(resp.supply[0].amount))
-
-# Inflation
-req = QueryParamsRequest(subspace="mint", key="InflationRate")
-resp = ledger.params.Params(req)
-inflation = float(json.loads(resp.param.value))
-
-# Community Tax
-req = QueryParamsRequest(subspace="distribution", key="communitytax")
-resp = ledger.params.Params(req)
-community_tax = float(json.loads(resp.param.value))
-```
-
-### Calculate reward rate
-
-We can now proceed to calculate a theoretical staking rewards rate using the variables gathered above. These are: `inflation`, `total_supply`, `pct_delegated`, `community_tax` and `commission`:
-
-```py copy
-# Calculate annual reward
-annual_reward = (inflation * total_supply) *pct_delegated* (1- community_tax)*(1- commission)
-
-# Convert from annual reward to minute reward
-minute_reward = annual_reward/360/24/60
-
-# Set the rate
-rate = minute_reward/initial_stake
-```
-
-### Calculate optimal compounding period
-
-We can calculate the optimal compounding period that maximizes our staking rewards analytically by using the following formula:
-
-
-
- Where:
-
- - M = Total stake at time D
- - S = Initial Stake
- - f = Transaction Fee
- - k = Reward Rate
- - m = Number Of Compounding Transactions
- - n = Compounding Period
- - D = m x n = Total Staking Time
-
-We will now find the value that maximizes reward by taking the first derivative with respect to _n_ and finding the root in the interval _(0,D]_:
-
-```py copy
-import numpy as np
-from sympy.utilities.lambdify import lambdify, implemented_function
-from sympy import *
-from scipy.optimize import brentq
-
-f = fee
-S = initial_stake
-k = rate
-D = total_period
-
-# x will represent n
-x = Symbol("x")
-
-# Define the function
-M = (S*(1+(k*x))**(D/x))+((1-((1+(k*x))**(D/x)))/(k*x))*f
-Mx = lambdify(x,M)
-
-# Take the first derivative with respect to x
-M_prime = M.diff(x)
-Mx_prime = lambdify(x,M_prime)
-
-# Find the maximum reward value by finding the root of the function
-optimal_period = brentq(Mx_prime, 0.1, D)
-
-print("optimal_period: ", analytical_optimal_period, " minutes")
-```
-
-You can make use of the `optimal_period` value in the staking [`auto-compounder` ↗️](/guides/fetch-network/cosmpy/use-cases/stake-auto-compounder) to maximize your rewards.
-
-You can also plot the function along with the optimal period to observe the results in the following manner:
-
-```py copy
-import matplotlib.pyplot as plt
-
-plot = plt.figure(0,figsize=(6,4), dpi=100)
-
-y = np.linspace(1,300, 100)
-plt.plot(y,Mx(y),"k", label = 'analytical function')
-plt.axvline(x = optimal_period, color = 'g', linewidth = 2, label = f'optimal period: {round(optimal_period)}')
-plt.legend()
-
-plt.xlabel("Compounding periods")
-plt.ylabel('Total Reward')
-plt.title('Maximizing Rewards')
-plt.grid()
-```
-
-
-
-Finally, we can compare the compounding staking rewards to a simple non-compounding strategy:
-
-```py copy
-# Compounding Strategy
-comp_rewards = []
-rewards = 0
-period = optimal_period
-S = initial_stake
-for i in range(total_period):
- rewards = rewards + (S*rate)
- if i%period == 0:
- S = S + rewards - fee
- rewards = 0
- comp_rewards.append(S)
-S = S + rewards - (fee/2)
-comp_rewards.append(S)
-
-# Simple Strategy
-s_reward = initial_stake*rate
-simple_rewards = [initial_stake+(s_reward*i) for i in range(comp_period)]
-
-# Plots
-plot = plt.figure(0,figsize=(12,4), dpi=100)
-
-plt.subplot(1,2,1)
-plt.plot(comp_rewards, label = "Compounded Rewards")
-plt.plot(simple_rewards, label = "Simple Rewards")
-plt.xlabel("time in minutes")
-plt.ylabel('Reward')
-plt.title('Staking Rewards')
-plt.legend()
-
-plt.subplot(1,2,2)
-
-plt.plot(total_rewards, label = "Compounded Rewards")
-plt.plot(simple_rewards, label = "Simple Rewards")
-plt.xlabel("time in minutes")
-plt.ylabel('Reward')
-plt.title('Staking Rewards (log scale)')
-plt.legend()
-
-plt.yscale('log')
-```
-
-
-
-Now that we have presented the concepts and ideas behind the stake optimizer, have a look at the abbreviated version of the code provided below:
-
-
-
-
-
-
-
- ```py copy filename="aerial_stake_optimizer.py"
-
- import json
-
- from cosmpy.aerial.client import LedgerClient, NetworkConfig
- from cosmpy.aerial.client.distribution import create_withdraw_delegator_reward
- from cosmpy.aerial.client.staking import create_delegate_msg
- from cosmpy.aerial.faucet import FaucetApi
- from cosmpy.aerial.tx import SigningCfg, Transaction
- from cosmpy.aerial.wallet import LocalWallet
- from cosmpy.protos.cosmos.bank.v1beta1.query_pb2 import QueryTotalSupplyRequest
- from cosmpy.protos.cosmos.params.v1beta1.query_pb2 import QueryParamsRequest
- from cosmpy.protos.cosmos.staking.v1beta1.query_pb2 import QueryValidatorsRequest
-
-
- # This function returns the total reward for given:
- # * f -> fee
- # * S -> Initial Stake
- # * k -> Reward Rate
- # * D -> Total staking period
- # * x -> Compounding Period
- def M(x, f, S, k, D):
- """
- Calculate the total reward.
-
- :param x: Compounding Period
- :param f: fee
- :param S: Initial Stake
- :param k: Reward Rate
- :param D: Total staking period
-
- :return: Total reward
- """
- return (S * (1 + (k * x)) ** (D / x)) + (
- (1 - ((1 + (k * x)) ** (D / x))) / (k * x)
- ) * f
-
-
- def main():
- """Run main."""
- ledger = LedgerClient(NetworkConfig.fetchai_stable_testnet())
- faucet_api = FaucetApi(NetworkConfig.fetchai_stable_testnet())
-
- # Set initial stake and desired stake period
- initial_stake = 50000000000000000000
- total_period = 60000
-
- req = QueryValidatorsRequest()
- resp = ledger.staking.Validators(req)
-
- # Calculate the total staked in the testnet
-
- total_stake = 0
- # validator.status == 3 refers to bonded validators
- validators_stake = [
- int(validator.tokens) for validator in resp.validators if validator.status == 3
- ]
- total_stake = sum(validators_stake)
-
- # Get validators commissions
- validators_commission = [
- int(validator.commission.commission_rates.rate)
- for validator in resp.validators
- if validator.status == 3
- ]
-
- validators = ledger.query_validators()
- validator = "not_selected"
-
- # Choose a threshold for a validators minimum percentage of total stake delegated
- stake_threshold = 0.10
-
- for _i in range(len(validators_commission)):
-
- # Choose validator with lower commission
- validator_index = validators_commission.index(min(validators_commission))
-
- # Verify that it meets the minimum % threshold
- validator_stake_pct = validators_stake[validator_index] / total_stake
- if validator_stake_pct >= stake_threshold:
- # Set the selected validator
- validator = validators[validator_index]
- break
-
- # We omit this validator by setting his commission to infinity
- validators_commission[validator_index] = float("inf")
-
- if validator == "not_selected":
- # Restart validators_commission list with original values
- validators_commission = [
- int(validator.commission.commission_rates.rate)
- for validator in resp.validators
- if validator.status == 3
- ]
-
- print("No validator meets the minimum stake threshold requirement")
-
- # Proceed to select the validator with the lowest commission
- validator_index = validators_commission.index(min(validators_commission))
- validator = validators[validator_index]
-
- # Query validator commission
- commission = float(resp.validators[0].commission.commission_rates.rate) / 1e18
-
- # Set percentage delegated of total stake
- pct_delegated = initial_stake / total_stake
-
- # Estimate fees for claiming and delegating rewards
-
- alice = LocalWallet.generate()
- alice_address = str(alice.address())
-
- alice_balance = ledger.query_bank_balance(alice.address())
-
- while alice_balance < initial_stake:
- print("Providing wealth to alice...")
- faucet_api.get_wealth(alice.address())
- alice_balance = ledger.query_bank_balance(alice.address())
-
- tx = Transaction()
-
- # Add delegate msg
- tx.add_message(
- create_delegate_msg(alice_address, validator.address, initial_stake, "atestfet")
- )
-
- # Add claim reward msg
- tx.add_message(create_withdraw_delegator_reward(alice_address, validator.address))
-
- account = ledger.query_account(alice.address())
-
- tx.seal(
- SigningCfg.direct(alice.public_key(), account.sequence), fee="", gas_limit=0
- )
- tx.sign(alice.signer(), ledger.network_config.chain_id, account.number)
- tx.complete()
-
- # simulate the fee for the transaction
- _, str_tx_fee = ledger.estimate_gas_and_fee_for_tx(tx)
-
- denom = "atestfet"
- tx_fee = str_tx_fee[: -len(denom)]
-
- # Add a 20% to the fee estimation to get a more conservative estimate
- fee = int(tx_fee) * 1.20
-
- # Query chain variables
-
- # Total Supply of tokens
- req = QueryTotalSupplyRequest()
- resp = ledger.bank.TotalSupply(req)
- total_supply = float(json.loads(resp.supply[0].amount))
-
- # Inflation
- req = QueryParamsRequest(subspace="mint", key="InflationRate")
- resp = ledger.params.Params(req)
- inflation = float(json.loads(resp.param.value))
-
- # Community Tax
- req = QueryParamsRequest(subspace="distribution", key="communitytax")
- resp = ledger.params.Params(req)
- community_tax = float(json.loads(resp.param.value))
-
- # Annual reward calculation
- annual_reward = (
- (inflation * total_supply)
- * pct_delegated
- * (1 - community_tax)
- * (1 - commission)
- )
-
- # Convert from annual reward to minute reward
- minute_reward = annual_reward / 360 / 24 / 60
- rate = minute_reward / initial_stake
-
- # Compute optimal period
- f = fee
- S = initial_stake
- k = rate
- D = total_period
-
- # List of compounding periods
- X = list(range(1, D))
-
- # Evaluate function M on each compounding period
- R = [M(x, f, S, k, D) for x in X]
-
- # Fnd the period that maximizes rewards
- optimal_period = R.index(max(R)) + 1
-
- # These values can be used in aerial_compounder.py to maximize rewards
- print("total period: ", total_period, "minutes")
- print("optimal compounding period: ", optimal_period, "minutes")
-
-
- if __name__ == "__main__":
- main()
-
-```
-
-
-
-
-
-
diff --git a/pages/guides/fetch-network/cosmpy/use-cases/swap_automation.mdx b/pages/guides/fetch-network/cosmpy/use-cases/swap_automation.mdx
deleted file mode 100644
index c0f82730a..000000000
--- a/pages/guides/fetch-network/cosmpy/use-cases/swap_automation.mdx
+++ /dev/null
@@ -1,610 +0,0 @@
-import { CodeGroup, CodeSegment, DocsCode, GithubCodeSegment } from "../../../../../components/code";
-
-# Swap automation 🔄
-
-## Introduction
-
-The following guide demonstrates an automated swapping strategy for a liquidity pool on the Fetch.ai network. It interacts with a liquidity pool contract and performs swaps between two different tokens (atestfet and CW20 tokens) based on specified price thresholds. A mean-reversion strategy expects the prices to return to "normal" levels or a certain moving average following a temporary price spike. We can construct a similar strategy using the Liquidity Pool, where we will set upper and lower bound prices that will trigger a sell and a buy transaction respectively. If the behavior of the LP prices works as expected always returning to a certain moving average, we could profit by selling high and buying low. We will do this by swapping atestfet and cw20 with the Liquidity Pool, we refer to a sell transaction when we sell atestfet and get CW20 tokens, a buy transaction would be exactly the opposite.
-
-## Walk-through
-
-1. Let's start by creating a Python script and name it:
-
-
-
- ```py copy filename="mac"
- touch aerial_swap_automation.py
- ```
-
-
-
- ```py copy filename="windows"
- echo. > aerial_swap_automation.py
- ```
-
-
-
- ```py copy filename="ubuntu"
- touch aerial_swap_automation.py
- ```
-
-
-
-2. Let's then import the needed classes:
-
-
-
-
-
-
-
- ```py copy filename="aerial_swap_automation.py"
-
- import argparse
- from time import sleep
-
- from cosmpy.aerial.client import LedgerClient, NetworkConfig
- from cosmpy.aerial.contract import LedgerContract
- from cosmpy.aerial.faucet import FaucetApi
- from cosmpy.aerial.wallet import LocalWallet
-
-```
-
-
-
-
-
-
-3. We then need to define a `swap_native_for_cw20()` function which performs a swap from native tokens (atestfet) to CW20 tokens within a liquidity pool:
-
-
-
-
-
-
-
- ```py copy filename="aerial_swap_automation.py"
-
- def swap_native_for_cw20(swap_amount, pair_contract, wallet):
- """
- Swap Native for cw20.
-
- :param swap_amount: swap amount
- :param pair_contract: pair contract address
- :param wallet: wallet address
-
- """
- tx = pair_contract.execute(
- {
- "swap": {
- "offer_asset": {
- "info": {"native_token": {"denom": "atestfet"}},
- "amount": str(swap_amount),
- }
- }
- },
- sender=wallet,
- funds=str(swap_amount) + "atestfet",
- )
- print("swapping native for cw20 tokens")
- tx.wait_to_complete()
-
-```
-
-
-
-
-
-
- Within the function, we defined the following parameters:
-
- - `swap_amount`: this parameter specifies the amount of native tokens to be swapped for CW20 tokens.
-
- - `pair_contract`: this parameter represents the contract address of the liquidity pool pair where the swap will occur.
-
- - `wallet`: this parameter represents the wallet address that will perform the swap.
-
- The function constructs a transaction to execute the swap operation. The `execute()` method is called on the `pair_contract` with a dictionary specifying the `"swap"` operation. Inside the `"swap"` operation, the `offer_asset` field is set to the following:
-
- - `info`: this field specifies that the swap involves native tokens (`native_token`) with the denomination `"atestfet"`.
- - `amount`: this field specifies the amount of native tokens to be swapped, which is converted to a string.
-
- The `sender` parameter is set to the `wallet` address, indicating that the wallet will initiate the swap. The `funds` parameter is set to a string representing the total amount of funds being used for the swap, which includes the `swap_amount` and `"atestfet"`. Finally, the function waits for the transaction to complete and prints a message indicating that native tokens are being swapped for CW20 tokens.
-
-4. We then need to define a `swap_cw20_for_native()` function which performs a swap from CW20 tokens to native tokens (atestfet) within a liquidity pool:
-
-
-
-
-
-
-
- ```py copy filename="aerial_swap_automation.py"
-
- def swap_cw20_for_native(swap_amount, pair_contract_address, token_contract, wallet):
- """
- Swap cw20 for native.
-
- :param swap_amount: swap amount
- :param pair_contract_address: pair contract address
- :param token_contract: token contract
- :param wallet: wallet address
-
- """
- tx = token_contract.execute(
- {
- "send": {
- "contract": pair_contract_address,
- "amount": str(swap_amount),
- "msg": "eyJzd2FwIjp7fX0=",
- }
- },
- wallet,
- )
- print("swapping cw20 for native tokens")
- tx.wait_to_complete()
-
-```
-
-
-
-
-
-
- Within the function, we defined the following parameters:
-
- - `swap_amount`: this parameter specifies the amount of CW20 tokens to be swapped for native tokens.
- - `pair_contract_address`: this parameter represents the contract address of the liquidity pool pair where the swap will occur.
- - `token_contract`: this parameter represents the contract for the CW20 token.
- - `wallet`: This parameter represents the wallet address that will perform the swap.
-
- The function constructs a transaction to execute the swap operation: the `execute()` method is called on the `token_contract` with a dictionary specifying the `"send"` operation. Inside this operation, the contract field is set to `pair_contract_address`, indicating that the CW20 tokens will be sent to the liquidity pool. The `amount` field is set to the `swap_amount`, which is converted to a string. The `msg` field is set to the base64 encoded message `"eyJzd2FwIjp7fX0="`, which likely contains additional instructions or parameters for the swap. The `wallet` address is specified as the sender of the transaction. Finally, the function waits for the transaction to complete and prints a message indicating that CW20 tokens are being swapped for native tokens.
-
-5. We now would need to proceed by defining a `_parse_commandline()` function:
-
-
-
-
-
-
-
- ```py copy filename="aerial_swap_automation.py"
-
- def _parse_commandline():
- """Commandline parser."""
- parser = argparse.ArgumentParser()
-
- parser.add_argument(
- "trading_wallet",
- type=int,
- nargs="?",
- default=1000000,
- help="initial atestfet balance to perform swaps using the liquidity pool",
- )
- parser.add_argument(
- "upper_bound",
- type=int,
- nargs="?",
- default=20.5,
- help="price upper bound that will trigger a swap from cw20 to native tokens",
- )
- parser.add_argument(
- "lower_bound",
- type=int,
- nargs="?",
- default=19.5,
- help="price lower bound that will trigger a swap from native to cw20 tokens",
- )
- parser.add_argument(
- "commission",
- type=int,
- nargs="?",
- default=0.003,
- help="LP commission, for terraswap the default is 0.3%",
- )
- parser.add_argument(
- "interval_time",
- type=int,
- nargs="?",
- default=5,
- help="interval time in seconds to query liquidity pool price",
- )
-
- return parser.parse_args()
-
-```
-
-
-
-
-
-
- This function is responsible for parsing command line arguments in the script. It uses the `argparse.ArgumentParser()` class to define and handle the expected command line arguments:
-
- - `trading_wallet`: this argument represents the initial balance of atestfet in the trading wallet. It's an optional argument, and if not provided, it defaults to `1000000`.
- - `upper_bound`: this argument specifies the upper price threshold that will trigger a swap from cw20 to native tokens . If not provided, it defaults to `20.5`.
- - `lower_bound`: this argument sets the lower price threshold that will trigger a swap from native to cw20 tokens. It defaults to `19.5` if not provided.
- - `commission`: this argument defines the commission rate for the liquidity pool. The default is `0.003`, representing 0.3%.
- - `interval_time`: this argument determines the interval (in seconds) at which the script queries the liquidity pool price. If not provided, it defaults to `5` seconds.
-
- The function then returns an object containing the parsed arguments. These arguments can be accessed later in the script to control the behavior of the swap automation.
-
-6. We are ready to write down our `main()` function:
-
-
-
-
-
-
-
- ```py copy filename="aerial_swap_automation.py"
-
- def main():
- """Run main."""
- args = _parse_commandline()
-
- # Define any wallet
- wallet = LocalWallet.generate()
-
- # Network configuration
- ledger = LedgerClient(NetworkConfig.latest_stable_testnet())
-
- # Add tokens to wallet
- faucet_api = FaucetApi(NetworkConfig.latest_stable_testnet())
-
- wallet_balance = ledger.query_bank_balance(wallet.address())
-
- while wallet_balance < (10 ** 18):
- print("Providing wealth to wallet...")
- faucet_api.get_wealth(wallet.address())
- wallet_balance = ledger.query_bank_balance(wallet.address())
-
- # Define cw20, pair and liquidity token contracts
- token_contract_address = (
- "fetch1qr8ysysnfxmqzu7cu7cq7dsq5g2r0kvkg5e2wl2fnlkqss60hcjsxtljxl"
- )
- pair_contract_address = (
- "fetch1vgnx2d46uvyxrg9pc5mktkcvkp4uflyp3j86v68pq4jxdc8j4y0s6ulf2a"
- )
-
- token_contract = LedgerContract(
- path=None, client=ledger, address=token_contract_address
- )
- pair_contract = LedgerContract(
- path=None, client=ledger, address=pair_contract_address
- )
-
- # tokens in trading wallet (currency will vary [atestfet,cw20] )
- currency = "atestfet"
- tokens = args.trading_wallet
-
- # Swap thresholds
- upper_bound = args.upper_bound
- lower_bound = args.lower_bound
-
- # LP commission
- commission = args.commission
-
- # Wait time
- interval = args.interval_time
-
- while True:
-
- # Query LP status
- pool = pair_contract.query({"pool": {}})
- native_amount = int(pool["assets"][1]["amount"])
- cw20_amount = int(pool["assets"][0]["amount"])
-
- if currency == "atestfet":
- # Calculate received cw20 tokens if atestfet tokens are given to LP
- tokens_out = round(
- ((cw20_amount * tokens) / (native_amount + tokens)) * (1 - commission)
- )
-
- # Sell price of atestfet => give atestfet, get cw20
- sell_price = tokens / tokens_out
- print("atestfet sell price: ", sell_price)
- if sell_price <= lower_bound:
- swap_native_for_cw20(tokens, pair_contract, wallet)
- tokens = int(
- token_contract.query(
- {"balance": {"address": str(wallet.address())}}
- )["balance"]
- )
-
- # Trading wallet currency changed to cw20
- currency = "CW20"
- else:
- # Calculate received atestfet tokens if cw20 tokens are given to LP
- tokens_out = round(
- ((native_amount * tokens) / (cw20_amount + tokens)) * (1 - commission)
- )
-
- # Buy price of atestfet => give cw20, get atestfet
- buy_price = tokens_out / tokens
- print("atestfet buy price: ", buy_price)
- if buy_price >= upper_bound:
- swap_cw20_for_native(
- tokens, pair_contract_address, token_contract, wallet
- )
- tokens = tokens_out
-
- # Trading wallet currency changed to cw20
- currency = "atestfet"
-
- sleep(interval)
-
-
- if __name__ == "__main__":
- main()
-
-```
-
-
-
-
-
-
- Within the `main()` function, the `_parse_commandline()` function is used to parse command line arguments. It sets various parameters such as the initial trading wallet balance, upper and lower price bounds for triggering swaps, liquidity pool commission, and interval time for querying the liquidity pool price, and all of these values are store in the `args` variable. After this, a new wallet is generated using the `generate()` method of the `LocalWallet` class, and network configuration is set up using the `LedgerClient()` class. Tokens are added to the wallet by using the Faucet API. This happens within a `while` loop which continues until the wallet balance reaches at least `10**18`. The wallet balance is retrieved using the `query_bank_balance()`. Afterwards, we need to define the addresses of the CW20, pair, and liquidity token contracts, as well as initialize various variables based on the command line arguments, including the initial wallet balance, `upper_bound` and `lower_bound` price bounds for swaps, LP commission rate, and the interval at which to check the liquidity pool price.
-
- We then define a loop (`while True`), which:
-
- - Queries the liquidity pool status (`pair_contract.query({"pool": {}})`) to get the current amounts of native tokens (`atestfet`) and CW20 tokens.
- - Checks the current currency in the trading wallet (`currency`), which can be either native or CW20 tokens.
- - If the current `currency` is `atestfet`, it calculates the potential amount of CW20 tokens that would be received if native tokens were given to the liquidity pool. This is done based on the ratio of CW20 tokens to the total of native tokens and current wallet tokens, with a deduction for the LP commission. It calculates a `sell_price` as the ratio of the current wallet tokens to tokens swapped out.
- - If the sell price is lower than or equal to the specified `lower_bound`, it triggers the `swap_native_for_cw20()` function, which swaps atestfet tokens for CW20 tokens.
- - After the successful swap, it updates the tokens variable to the new balance of CW20 tokens and changes the currency to `"CW20"`.
- - If the current currency is `"CW20"`, it calculates the potential amount of atestfet tokens that would be received if CW20 tokens are given to the liquidity pool. This is done based on the ratio of native tokens to the total of CW20 tokens and current wallet tokens, with a deduction for the LP commission. It calculates a `buy_price` as the ratio of potential atestfet tokens to the current wallet tokens.
- - If the `buy_price` is higher than or equal to the specified `upper_bound`, it triggers the `swap_cw20_for_native()` function, which swaps CW20 tokens for atestfet tokens.
- - After the successful swap, it updates the tokens variable to the new balance of atestfet tokens and changes the currency to `"atestfet"`.
- The loop then waits for the specified `interval` before checking the liquidity pool status and performing the next iteration.
-
-7. Save the script.
-
-The overall script should be as follows:
-
-
-
-
-
-
-
- ```py copy filename="aerial_swap_automation.py"
-
- import argparse
- from time import sleep
-
- from cosmpy.aerial.client import LedgerClient, NetworkConfig
- from cosmpy.aerial.contract import LedgerContract
- from cosmpy.aerial.faucet import FaucetApi
- from cosmpy.aerial.wallet import LocalWallet
-
-
- def swap_native_for_cw20(swap_amount, pair_contract, wallet):
- """
- Swap Native for cw20.
-
- :param swap_amount: swap amount
- :param pair_contract: pair contract address
- :param wallet: wallet address
-
- """
- tx = pair_contract.execute(
- {
- "swap": {
- "offer_asset": {
- "info": {"native_token": {"denom": "atestfet"}},
- "amount": str(swap_amount),
- }
- }
- },
- sender=wallet,
- funds=str(swap_amount) + "atestfet",
- )
- print("swapping native for cw20 tokens")
- tx.wait_to_complete()
-
-
- def swap_cw20_for_native(swap_amount, pair_contract_address, token_contract, wallet):
- """
- Swap cw20 for native.
-
- :param swap_amount: swap amount
- :param pair_contract_address: pair contract address
- :param token_contract: token contract
- :param wallet: wallet address
-
- """
- tx = token_contract.execute(
- {
- "send": {
- "contract": pair_contract_address,
- "amount": str(swap_amount),
- "msg": "eyJzd2FwIjp7fX0=",
- }
- },
- wallet,
- )
- print("swapping cw20 for native tokens")
- tx.wait_to_complete()
-
-
- def _parse_commandline():
- """Commandline parser."""
- parser = argparse.ArgumentParser()
-
- parser.add_argument(
- "trading_wallet",
- type=int,
- nargs="?",
- default=1000000,
- help="initial atestfet balance to perform swaps using the liquidity pool",
- )
- parser.add_argument(
- "upper_bound",
- type=int,
- nargs="?",
- default=20.5,
- help="price upper bound that will trigger a swap from cw20 to native tokens",
- )
- parser.add_argument(
- "lower_bound",
- type=int,
- nargs="?",
- default=19.5,
- help="price lower bound that will trigger a swap from native to cw20 tokens",
- )
- parser.add_argument(
- "commission",
- type=int,
- nargs="?",
- default=0.003,
- help="LP commission, for terraswap the default is 0.3%",
- )
- parser.add_argument(
- "interval_time",
- type=int,
- nargs="?",
- default=5,
- help="interval time in seconds to query liquidity pool price",
- )
-
- return parser.parse_args()
-
-
- def main():
- """Run main."""
- args = _parse_commandline()
-
- # Define any wallet
- wallet = LocalWallet.generate()
-
- # Network configuration
- ledger = LedgerClient(NetworkConfig.latest_stable_testnet())
-
- # Add tokens to wallet
- faucet_api = FaucetApi(NetworkConfig.latest_stable_testnet())
-
- wallet_balance = ledger.query_bank_balance(wallet.address())
-
- while wallet_balance < (10 ** 18):
- print("Providing wealth to wallet...")
- faucet_api.get_wealth(wallet.address())
- wallet_balance = ledger.query_bank_balance(wallet.address())
-
- # Define cw20, pair and liquidity token contracts
- token_contract_address = (
- "fetch1qr8ysysnfxmqzu7cu7cq7dsq5g2r0kvkg5e2wl2fnlkqss60hcjsxtljxl"
- )
- pair_contract_address = (
- "fetch1vgnx2d46uvyxrg9pc5mktkcvkp4uflyp3j86v68pq4jxdc8j4y0s6ulf2a"
- )
-
- token_contract = LedgerContract(
- path=None, client=ledger, address=token_contract_address
- )
- pair_contract = LedgerContract(
- path=None, client=ledger, address=pair_contract_address
- )
-
- # tokens in trading wallet (currency will vary [atestfet,cw20] )
- currency = "atestfet"
- tokens = args.trading_wallet
-
- # Swap thresholds
- upper_bound = args.upper_bound
- lower_bound = args.lower_bound
-
- # LP commission
- commission = args.commission
-
- # Wait time
- interval = args.interval_time
-
- while True:
-
- # Query LP status
- pool = pair_contract.query({"pool": {}})
- native_amount = int(pool["assets"][1]["amount"])
- cw20_amount = int(pool["assets"][0]["amount"])
-
- if currency == "atestfet":
- # Calculate received cw20 tokens if atestfet tokens are given to LP
- tokens_out = round(
- ((cw20_amount * tokens) / (native_amount + tokens)) * (1 - commission)
- )
-
- # Sell price of atestfet => give atestfet, get cw20
- sell_price = tokens / tokens_out
- print("atestfet sell price: ", sell_price)
- if sell_price <= lower_bound:
- swap_native_for_cw20(tokens, pair_contract, wallet)
- tokens = int(
- token_contract.query(
- {"balance": {"address": str(wallet.address())}}
- )["balance"]
- )
-
- # Trading wallet currency changed to cw20
- currency = "CW20"
- else:
- # Calculate received atestfet tokens if cw20 tokens are given to LP
- tokens_out = round(
- ((native_amount * tokens) / (cw20_amount + tokens)) * (1 - commission)
- )
-
- # Buy price of atestfet => give cw20, get atestfet
- buy_price = tokens_out / tokens
- print("atestfet buy price: ", buy_price)
- if buy_price >= upper_bound:
- swap_cw20_for_native(
- tokens, pair_contract_address, token_contract, wallet
- )
- tokens = tokens_out
-
- # Trading wallet currency changed to cw20
- currency = "atestfet"
-
- sleep(interval)
-
-
- if __name__ == "__main__":
- main()
-
-```
-
-
-
-
-
-
diff --git a/pages/guides/fetch-network/cosmpy/use-cases/wallet-top-up.mdx b/pages/guides/fetch-network/cosmpy/use-cases/wallet-top-up.mdx
deleted file mode 100644
index e93f0ed7d..000000000
--- a/pages/guides/fetch-network/cosmpy/use-cases/wallet-top-up.mdx
+++ /dev/null
@@ -1,664 +0,0 @@
-import { CodeGroup, CodeSegment, DocsCode, GithubCodeSegment } from "../../../../../components/code";
-
-# Wallet top-up 💵
-
-## Introduction
-
-The following guide is about how to top-up a wallet using the CosmPy library. To top-up a wallet, you need to create different wallets. In particular, if you are performing multiple transactions from a certain `task_wallet`, you can set an algorithm to keep that wallet address topped-up. For this use case, we will use three different wallets: `wallet`, `authz_wallet`, and `task_wallet`. `wallet` will be the main wallet address that we don't want to give full access to, therefore we will authorize `authz_wallet` to send a certain amount of tokens from `wallet` to `task_wallet` every time `task_wallet` balance falls below a certain `minimum_balance` threshold. This way, `task_wallet` can keep performing transactions using the main wallet's tokens by being topped-up by `authz_wallet`.
-
-## Walk-through
-
-### Aerial authorization: authorization address and authorization wallet
-
-1. Let's start by creating a Python script for this:
-
-
-
- ```py copy filename="mac"
- touch aerial_authz.py
- ```
-
-
-
- ```py copy filename="windows"
- echo. > aerial_authz.py
- ```
-
-
-
- ```py copy filename="ubuntu"
- touch aerial_authz.py
- ```
-
-
-
-2. First of all, we need to import the necessary classes:
-
-
-
-
-
-
-
- ```py copy filename="aerial_authz.py"
-
- import argparse
- from datetime import datetime, timedelta
-
- from google.protobuf import any_pb2, timestamp_pb2
-
- from cosmpy.aerial.client import LedgerClient, NetworkConfig
- from cosmpy.aerial.client.utils import prepare_and_broadcast_basic_transaction
- from cosmpy.aerial.faucet import FaucetApi
- from cosmpy.aerial.tx import Transaction
- from cosmpy.aerial.wallet import LocalWallet
- from cosmpy.protos.cosmos.authz.v1beta1.authz_pb2 import Grant
- from cosmpy.protos.cosmos.authz.v1beta1.tx_pb2 import MsgGrant
- from cosmpy.protos.cosmos.bank.v1beta1.authz_pb2 import SendAuthorization
- from cosmpy.protos.cosmos.base.v1beta1.coin_pb2 import Coin
-
-```
-
-
-
-
-
-
-3. We then proceed and define a `_parse_commandline()` function:
-
-
-
-
-
-
-
- ```py copy filename="aerial_authz.py"
-
- def _parse_commandline():
- parser = argparse.ArgumentParser()
- parser.add_argument(
- "authz_address",
- help="address that will be granted authorization to send tokens from wallet",
- )
- parser.add_argument(
- "total_authz_time",
- type=int,
- nargs="?",
- default=10,
- help="authorization time for authz_address in minutes",
- )
- parser.add_argument(
- "spend_limit",
- type=int,
- nargs="?",
- default=1000000000000000000,
- help="maximum tokens that authz_wallet will be able to spend from wallet",
- )
-
- return parser.parse_args()
-
-```
-
-
-
-
-
-
- The `_parse_commandline()` function is using the `argparse` module to define a command-line interface for this script. It expects and processes three command-line arguments:
-
- 1. `authz_address`: this is a required argument. It expects the user to provide an address that will be granted authorization to send tokens from a wallet.
-
- 2. `total_authz_time`: this is an optional argument. If provided, it should be an integer representing the authorization time for the `authz_address` in minutes. If not provided, it defaults to `10` minutes.
-
- 3. `spend_limit`: this is another optional argument. If provided, it should be an integer representing the maximum tokens that the `authz_wallet` will be able to spend from the wallet. If not provided, it defaults to `1000000000000000000`.
-
- The `help` parameter provides a description of what each argument is for, which can be helpful for users who might not be familiar with the script. After defining these arguments, the function uses `parser.parse_args()` to process the command-line arguments provided by the user and return them as an object containing the values provided for `authz_address`, `total_authz_time`, and `spend_limit`.
-
-4. We can then define our `main()` function:
-
-
-
-
-
-
-
- ```py copy filename="aerial_authz.py"
-
- def main():
- """Run main."""
- args = _parse_commandline()
-
- wallet = LocalWallet.generate()
-
- authz_address = args.authz_address
-
- ledger = LedgerClient(NetworkConfig.fetchai_stable_testnet())
- faucet_api = FaucetApi(NetworkConfig.fetchai_stable_testnet())
-
- total_authz_time = args.total_authz_time
- wallet_balance = ledger.query_bank_balance(wallet.address())
-
- amount = args.spend_limit
-
- while wallet_balance < (amount):
- print("Providing wealth to wallet...")
- faucet_api.get_wealth(wallet.address())
- wallet_balance = ledger.query_bank_balance(wallet.address())
-
- spend_amount = Coin(amount=str(amount), denom="atestfet")
-
- # Authorize authz_wallet to send tokens from wallet
- authz_any = any_pb2.Any()
- authz_any.Pack(
- SendAuthorization(spend_limit=[spend_amount]),
- "",
- )
-
- expiry = timestamp_pb2.Timestamp()
- expiry.FromDatetime(datetime.now() + timedelta(seconds=total_authz_time * 60))
- grant = Grant(authorization=authz_any, expiration=expiry)
-
- msg = MsgGrant(
- granter=str(wallet.address()),
- grantee=authz_address,
- grant=grant,
- )
-
- tx = Transaction()
- tx.add_message(msg)
-
- tx = prepare_and_broadcast_basic_transaction(ledger, tx, wallet)
- tx.wait_to_complete()
-
-
- if __name__ == "__main__":
- main()
-
-```
-
-
-
-
-
-
- In the first line we define a variable `args` using `_parse_commandline()` function defined previously to retrieve the command-line arguments `authz_address`, `total_authz_time`, and `spend_limit`. The values are stored in the `args` variable. We then generate a new wallet using the `generate()` method of the `LocalWallet` class, and then set the `authz_address` variable to retrieve the `authz_address` from the command-line arguments previously defined. This is the address that will be granted authorization to send tokens from the wallet. We then initialize a `ledger` object using the `LedgerClient` class and configure it to connect to the Fetch.ai stable testnet. We also initialize a `faucet_api` object using the `FaucetApi` class to provide access to a faucet API on the Fetch.ai stable testnet.
-
- `total_authz_time` retrieves the total authorization time (in minutes) from the command-line arguments. We proceed by checking the balance of the wallet by querying the ledger, using the `query_bank_balance()` method. We can then define a loop that continues until the wallet balance is greater than the specified spend amount (`amount`). Within the loop, it requests additional tokens from the faucet using `faucet_api.get_wealth()` and updates the wallet balance.
-
- Below, we define the `spend_amount` variable using a Coin object representing the spend amount. In this case, it's specified in the "atestfet" denomination. We then constructs an authorization object (`authz_any`) using `SendAuthorization`. It sets an expiration time for the authorization, and creates an instance of `MsgGrant` message type, specifying the `granter` (the wallet's address), `grantee` (the `authz_address`), and the `grant` (the authorization object). A new transaction (`tx`) is finally created, and `msg` is added to it. The transaction is then prepared and broadcasted using `prepare_and_broadcast_basic_transaction()`. Finally, the script waits for the transaction to complete.
-
-5. Save the script.
-
-The overall script should be as follows.
-
-
-
-
-
-
-
- ```py copy filename="aerial_authz.py"
-
- import argparse
- from datetime import datetime, timedelta
-
- from google.protobuf import any_pb2, timestamp_pb2
-
- from cosmpy.aerial.client import LedgerClient, NetworkConfig
- from cosmpy.aerial.client.utils import prepare_and_broadcast_basic_transaction
- from cosmpy.aerial.faucet import FaucetApi
- from cosmpy.aerial.tx import Transaction
- from cosmpy.aerial.wallet import LocalWallet
- from cosmpy.protos.cosmos.authz.v1beta1.authz_pb2 import Grant
- from cosmpy.protos.cosmos.authz.v1beta1.tx_pb2 import MsgGrant
- from cosmpy.protos.cosmos.bank.v1beta1.authz_pb2 import SendAuthorization
- from cosmpy.protos.cosmos.base.v1beta1.coin_pb2 import Coin
-
-
- def _parse_commandline():
- parser = argparse.ArgumentParser()
- parser.add_argument(
- "authz_address",
- help="address that will be granted authorization to send tokens from wallet",
- )
- parser.add_argument(
- "total_authz_time",
- type=int,
- nargs="?",
- default=10,
- help="authorization time for authz_address in minutes",
- )
- parser.add_argument(
- "spend_limit",
- type=int,
- nargs="?",
- default=1000000000000000000,
- help="maximum tokens that authz_wallet will be able to spend from wallet",
- )
-
- return parser.parse_args()
-
-
- def main():
- """Run main."""
- args = _parse_commandline()
-
- wallet = LocalWallet.generate()
-
- authz_address = args.authz_address
-
- ledger = LedgerClient(NetworkConfig.fetchai_stable_testnet())
- faucet_api = FaucetApi(NetworkConfig.fetchai_stable_testnet())
-
- total_authz_time = args.total_authz_time
- wallet_balance = ledger.query_bank_balance(wallet.address())
-
- amount = args.spend_limit
-
- while wallet_balance < (amount):
- print("Providing wealth to wallet...")
- faucet_api.get_wealth(wallet.address())
- wallet_balance = ledger.query_bank_balance(wallet.address())
-
- spend_amount = Coin(amount=str(amount), denom="atestfet")
-
- # Authorize authz_wallet to send tokens from wallet
- authz_any = any_pb2.Any()
- authz_any.Pack(
- SendAuthorization(spend_limit=[spend_amount]),
- "",
- )
-
- expiry = timestamp_pb2.Timestamp()
- expiry.FromDatetime(datetime.now() + timedelta(seconds=total_authz_time * 60))
- grant = Grant(authorization=authz_any, expiration=expiry)
-
- msg = MsgGrant(
- granter=str(wallet.address()),
- grantee=authz_address,
- grant=grant,
- )
-
- tx = Transaction()
- tx.add_message(msg)
-
- tx = prepare_and_broadcast_basic_transaction(ledger, tx, wallet)
- tx.wait_to_complete()
-
-
- if __name__ == "__main__":
- main()
-
-```
-
-
-
-
-
-
-### Aerial top-up
-
-We are now ready to write a Python script which automates the process of topping-up the designated wallet (`task_wallet`) from the main wallet (`wallet`) after authorization from `authz_wallet`, whenever the balance of `task_wallet` falls below a certain threshold (`minimum_balance`).
-
-1. Let's create a Python script for this and name it:
-
-
-
- ```py copy filename="mac"
- touch aerial_topup.py
- ```
-
-
-
- ```py copy filename="windows"
- echo. > aerial_topup.py
- ```
-
-
-
- ```py copy filename="ubuntu"
- touch aerial_topup.py
- ```
-
-
-
-2. Let's then import the needed modules such as `argparse` for command-line argument parsing and modules from the `cosmpy` library for blockchain interaction:
-
-
-
-
-
-
-
- ```py copy filename="aerial_topup.py"
-
- import argparse
- import time
-
- from google.protobuf import any_pb2
-
- from cosmpy.aerial.client import LedgerClient, NetworkConfig
- from cosmpy.aerial.client.utils import prepare_and_broadcast_basic_transaction
- from cosmpy.aerial.faucet import FaucetApi
- from cosmpy.aerial.tx import Transaction
- from cosmpy.aerial.wallet import LocalWallet
- from cosmpy.protos.cosmos.authz.v1beta1.tx_pb2 import MsgExec
- from cosmpy.protos.cosmos.bank.v1beta1.tx_pb2 import MsgSend
- from cosmpy.protos.cosmos.base.v1beta1.coin_pb2 import Coin
-
-```
-
-
-
-
-
-
-3. We then define a `_parse_commandline()` function that sets up command-line arguments:
-
-
-
-
-
-
-
- ```py copy filename="aerial_topup.py"
-
- def _parse_commandline():
- parser = argparse.ArgumentParser()
- parser.add_argument("wallet_address", help="main wallet address")
- parser.add_argument(
- "task_wallet_address", help="wallet address that will perform transactions"
- )
- parser.add_argument(
- "top_up_amount",
- type=int,
- nargs="?",
- default=10000000000000000,
- help="top-up amount from wallet address to task_wallet address",
- )
- parser.add_argument(
- "minimum_balance",
- type=int,
- nargs="?",
- default=1000000000000000,
- help="minimum task_wallet address balance that will trigger top-up",
- )
- parser.add_argument(
- "interval_time",
- type=int,
- nargs="?",
- default=5,
- help="interval time in seconds to query task_wallet's balance",
- )
-
- return parser.parse_args()
-
-```
-
-
-
-
-
-
- Above we defined different arguments including the addresses of the main wallet (`wallet_address`) and the task wallet (`task_wallet_address`), the top-up amount from `wallet_address` to `task_wallet_address` (`top_up_amount`), the minimum balance for `task_wallet_address` (`minimum_balance`), and the interval time in seconds to query `task_wallet_address`'s balance (`interval_time`).
-
- After these arguments are defined, the function uses `parser.parse_args()` to process the command-line arguments provided by the user. The values are then returned as an object, where each attribute corresponds to the name of the argument. This allows the script to access and utilize these values during execution.
-
-4. We are now ready to define our `main()` function:
-
-
-
-
-
-
-
- ```py copy filename="aerial_topup.py"
-
- def main():
- """Run main."""
- ledger = LedgerClient(NetworkConfig.fetchai_stable_testnet())
- args = _parse_commandline()
-
- wallet_address = args.wallet_address
-
- task_wallet_address = args.task_wallet_address
-
- # Use aerial_authz.py to authorize authz_wallet address to send tokens from wallet
- authz_wallet = LocalWallet.generate()
- faucet_api = FaucetApi(NetworkConfig.fetchai_stable_testnet())
-
- wallet_balance = ledger.query_bank_balance(authz_wallet.address())
-
- while wallet_balance < (10 ** 18):
- print("Providing wealth to wallet...")
- faucet_api.get_wealth(authz_wallet.address())
- wallet_balance = ledger.query_bank_balance(authz_wallet.address())
-
- ledger = LedgerClient(NetworkConfig.latest_stable_testnet())
-
- # Top-up amount
- amount = args.top_up_amount
- top_up_amount = Coin(amount=str(amount), denom="atestfet")
-
- # Minimum balance for task_wallet
- minimum_balance = args.minimum_balance
-
- # Interval to query task_wallet's balance
- interval_time = args.interval_time
-
- while True:
-
- wallet_balance = ledger.query_bank_balance(wallet_address)
-
- if wallet_balance < amount:
- print("Wallet doesn't have enough balance to top-up task_wallet")
- break
-
- task_wallet_balance = ledger.query_bank_balance(task_wallet_address)
-
- if task_wallet_balance < minimum_balance:
- print("topping up task wallet")
- # Top-up task_wallet
- msg = any_pb2.Any()
- msg.Pack(
- MsgSend(
- from_address=wallet_address,
- to_address=task_wallet_address,
- amount=[top_up_amount],
- ),
- "",
- )
-
- tx = Transaction()
- tx.add_message(MsgExec(grantee=str(authz_wallet.address()), msgs=[msg]))
-
- tx = prepare_and_broadcast_basic_transaction(ledger, tx, authz_wallet)
- tx.wait_to_complete()
-
- time.sleep(interval_time)
-
-
- if __name__ == "__main__":
- main()
-
-```
-
-
-
-
-
-
- Here we defined the `main()` function which orchestrates all of the operations. It first initializes a `ledger` object to interact with the blockchain using the `LedgerClient()` class. It then parses command-line arguments using `_parse_commandline()` and stores them in the `args` variable. The function then retrieves wallet addresses for `wallet` and `task_wallet` from `args`. The function then uses `aerial_authz.py` script previously created above to authorize `authz_wallet` address to send tokens from `wallet`. If the balance of `authz_wallet` is below `10**18`, it uses a faucet API to provide wealth to the wallet until it reaches this threshold. Within the script, we then re-initialize the ledger object with the latest stable testnet configuration. We then proceed to set the top-up amount, the minimum balance, and interval timer thresholds from `args`. The script then enters an infinite loop (`while True`) in which it queries the balance of the main `wallet`. Checks if the main wallet has enough balance to top-up `task_wallet`. Queries the balance of `task_wallet`: if its balance falls below the specified minimum, it initiates a top-up by first creating a message to send tokens from `wallet_address` to `task_wallet_address`, then constructing a transaction (`tx`) with the authorization and message. It then prepares, broadcasts the transaction, and waits for a specified interval before repeating the process.
-
-5. Save the script.
-
-The overall script should be as follows:
-
-
-
-
-
-
-
- ```py copy filename="aerial_topup.py"
-
- import argparse
- import time
-
- from google.protobuf import any_pb2
-
- from cosmpy.aerial.client import LedgerClient, NetworkConfig
- from cosmpy.aerial.client.utils import prepare_and_broadcast_basic_transaction
- from cosmpy.aerial.faucet import FaucetApi
- from cosmpy.aerial.tx import Transaction
- from cosmpy.aerial.wallet import LocalWallet
- from cosmpy.protos.cosmos.authz.v1beta1.tx_pb2 import MsgExec
- from cosmpy.protos.cosmos.bank.v1beta1.tx_pb2 import MsgSend
- from cosmpy.protos.cosmos.base.v1beta1.coin_pb2 import Coin
-
-
- def _parse_commandline():
- parser = argparse.ArgumentParser()
- parser.add_argument("wallet_address", help="main wallet address")
- parser.add_argument(
- "task_wallet_address", help="wallet address that will perform transactions"
- )
- parser.add_argument(
- "top_up_amount",
- type=int,
- nargs="?",
- default=10000000000000000,
- help="top-up amount from wallet address to task_wallet address",
- )
- parser.add_argument(
- "minimum_balance",
- type=int,
- nargs="?",
- default=1000000000000000,
- help="minimum task_wallet address balance that will trigger top-up",
- )
- parser.add_argument(
- "interval_time",
- type=int,
- nargs="?",
- default=5,
- help="interval time in seconds to query task_wallet's balance",
- )
-
- return parser.parse_args()
-
-
- def main():
- """Run main."""
- ledger = LedgerClient(NetworkConfig.fetchai_stable_testnet())
- args = _parse_commandline()
-
- wallet_address = args.wallet_address
-
- task_wallet_address = args.task_wallet_address
-
- # Use aerial_authz.py to authorize authz_wallet address to send tokens from wallet
- authz_wallet = LocalWallet.generate()
- faucet_api = FaucetApi(NetworkConfig.fetchai_stable_testnet())
-
- wallet_balance = ledger.query_bank_balance(authz_wallet.address())
-
- while wallet_balance < (10 ** 18):
- print("Providing wealth to wallet...")
- faucet_api.get_wealth(authz_wallet.address())
- wallet_balance = ledger.query_bank_balance(authz_wallet.address())
-
- ledger = LedgerClient(NetworkConfig.latest_stable_testnet())
-
- # Top-up amount
- amount = args.top_up_amount
- top_up_amount = Coin(amount=str(amount), denom="atestfet")
-
- # Minimum balance for task_wallet
- minimum_balance = args.minimum_balance
-
- # Interval to query task_wallet's balance
- interval_time = args.interval_time
-
- while True:
-
- wallet_balance = ledger.query_bank_balance(wallet_address)
-
- if wallet_balance < amount:
- print("Wallet doesn't have enough balance to top-up task_wallet")
- break
-
- task_wallet_balance = ledger.query_bank_balance(task_wallet_address)
-
- if task_wallet_balance < minimum_balance:
- print("topping up task wallet")
- # Top-up task_wallet
- msg = any_pb2.Any()
- msg.Pack(
- MsgSend(
- from_address=wallet_address,
- to_address=task_wallet_address,
- amount=[top_up_amount],
- ),
- "",
- )
-
- tx = Transaction()
- tx.add_message(MsgExec(grantee=str(authz_wallet.address()), msgs=[msg]))
-
- tx = prepare_and_broadcast_basic_transaction(ledger, tx, authz_wallet)
- tx.wait_to_complete()
-
- time.sleep(interval_time)
-
-
- if __name__ == "__main__":
- main()
-
-```
-
-
-
-
-
-
diff --git a/pages/guides/fetch-network/different-ways-to-stake-the-fet-token.mdx b/pages/guides/fetch-network/different-ways-to-stake-the-fet-token.mdx
deleted file mode 100644
index 9406ad208..000000000
--- a/pages/guides/fetch-network/different-ways-to-stake-the-fet-token.mdx
+++ /dev/null
@@ -1,204 +0,0 @@
-import { Callout } from 'nextra/components'
-
-# Different ways of staking FET
-
-Below you can find different ways one can stake FET.
-
-## STAKING/UNSTAKING ON FETCH MAINNET FOR BINANCE USERS
-
-[Binance has completed the Fetch.ai (FET) mainnet integration ↗️](https://www.binance.com/en/support/announcement/f68b1651b8df40998e109588007bb517).
-
-This means Binance has integrated Native FET tokens which can be staked easily on Cosmostation without relying on the token bridge.
-
-Below you can find the detailed user journey:
-
-
-
-
-For any additional clarification, please feel free to refer to the section **Applicable for users holding FET on Binance** below.
-
-### How to stake FET using Ledger on Cosmostation _Web Wallet_: applicable for users holding FET on Binance
-
-Please, follow the steps below:
-
- 1. Let's first head over to [Cosmostation Web Wallet ↗️](https://wallet.cosmostation.io/?network=fetchai) (Fetch.ai chain) and create an address for Fetch.ai chain. There is a detailed pdf from the Cosmostation team explaining how to create an account using ledger and how to use the web wallet.
-
- 2. Once done, we would need to send a small amount of FET as test from your Binance account to your generated Cosmostation address. Make sure the addresses are correct and above all the chain chosen for your generated address is Fetch.ai chain on Cosmostation web wallet.
-
- 3. If the tokens arrive successfully, then send the remaining amount.
-
- 4. Then, we would need to delegate to the preferred validators and start staking.
-
-### How to stake on Fetch Mainnet using Cosmostation _Mobile Wallets_: applicable for users holding FET on Binance
-
-Please, follow the steps below:
-
- 1. First of all, we need to consider if we wish to stake FET using Cosmostation iOS or Android mobile apps. For Mobile users: [iOS ↗️](https://apps.apple.com/us/app/cosmostation/id1459830339) and [Android ↗️](https://play.google.com/store/apps/details?id=wannabit.io.cosmostaion&hl=en&gl=US).
-
- 2. We then need to create a Cosmostation address for Fetch.ai chain. Head over to [Cosmostation FAQs ↗️](https://guide.cosmostation.io/) for a better understanding on how to create a wallet and check your address.
-
- 3. Then, we need to send a small amount of $FET from your Binance account to your generated cosmostation address. Make sure the addresses are correct and above all the chain chosen for your generated address is Fetch.ai chain on Cosmostation.
-
- 4. If the tokens arrive, then send the remaining amount.
-
- 5. Then, we would need to delegate to the preferred validators and start staking.
-
-## STAKING/UNSTAKING ON FETCH MAINNET FOR USERS WITH ACCESS TO MIGRATED TOKENS
-
-
- Our staking program has moved from Ethereum and we have successfully migrated all the tokens on September 15, 2021 — which you can access on our [ASI ALliance browser wallet ↗️](https://chromewebstore.google.com/detail/asi-alliance-wallet/ellkdbaphhldpeajbepobaecooaoafpg?hl=en-GB).
-
-
-**If you want to access your migrated tokens, here is how you do it.**
-
- - For those who staked on **staking.fetch.ai** using only Metamask — [Here is the guide ↗️](https://medium.com/fetch-ai/staking-migration-guide-how-to-participate-69a60cb5e2eb).
-
- - For those who staked on **staking.fetch.ai** using ledger — [Here is the guide ↗️](https://medium.com/fetch-ai/token-migration-guide-for-hardware-wallets-8c2b99cdced7) (refer to Key Migration Desktop).
-
- **IMPORTANTLY, BE SURE TO CREATE YOUR COSMOSTATION ADDRESS ONLY FOR FETCH.AI CHAIN.**
-
-Head over to [Cosmostation FAQs ↗️](https://guide.cosmostation.io/) for a better understanding on how to create a wallet and check your address.
-
-Below, you can find the detailed user journey explaining how to stake on our Mainnet if you have your tokens on the Fetch browser wallet.
-
-
-
-To unstake your tokens, you can use our [guide ↗️](/guides/fetch-network/how-to-convert-fet-to-and-from-erc20) which explains how to convert and send native and ERC-20 FET tokens back to your metamask using the Fetch browser wallet.
-
-
-
-## STAKING/UNSTAKING ON FETCH MAINNET IF YOU HAVE ERC-20 TOKENS ON OTHER EXCHANGES
-
-With the exception of Binance and HitBTC all other exchanges including Coinbase currently hold ERC-20 FET. To stake on Mainnet, you must use our [Token bridge ↗️](https://token-bridge.fetch.ai/) and metamask.
-
-Please feel free to refer to the section **Applicable for users on exchanges with ERC-20 FET** at the below sections of this page.
-
-For **Mobile users**: have a look at the **Staking on Fetch Mainnet using Cosmostation Mobile Wallet** guide above.
-
-
-
-To unstake your tokens, you can use our [guide ↗️](/guides/fetch-network/how-to-convert-fet-to-and-from-erc20) which explains how to convert and send native and ERC-20 FET tokens back to your metamask using the Fetch browser wallet.
-
-
-
-For **Ledger users** on exchanges with ERC-20 FET, follow the guide for staking on **Fetch Mainnet using Ledger and Cosmostation Web Wallet: applicable for users on exchanges with ERC20 FET** below.
-
-
-
-### How to stake FET using Ledger on Cosmostation Web Wallet: applicable for users on exchanges with ERC20 FET
-
-
- **Disclaimer**: The guide is a courtesy of [Cros-Net ↗️](https://cros-nest.com/) which is a validator on Fetch.ai Mainnet.
-
-
-What do you need:
-
- - Ledger Nano and a Desktop PC, as mobile devices are not yet supported.
- - Ledger Live software installed on your PC and an empty MetaMask wallet on your Brave/Chrome Browser. FET ERC20 tokens (except HitBTC all other exchanges
-
-Head over here — [Cosmostation web application ↗️](https://wallet.cosmostation.io/) (Cosmos Web Wallet) to stake the ERC20 Fetch coins. This guide also assumes you have Fetch.AI tokens stored in your Ledger Nano Wallet ready to be staked.
-
-Please, follow the steps below:
-
- 1. **Install Ethereum and Cosmos Ledger apps**.
- After setting up your device with a PIN and passphrase, you should install both the Ethereum and Cosmos wallets through the Ledger Live app.
-
- 2. **Set specific Ethereum app settings correctly**.
- Open the Ethereum app on your Ledger wallet. Within the app, go to settings. Make sure **Contract Data** is set to **Allow contract data in transactions**. By default this is turned off, it must be turned on so signing the transaction later on won't fail. Now exit the app.
-
- 3. **Obtaining Fetch.ai address**:
-
- - Open Cosmos app on your Ledger.
- - Via Brave/Chrome, go to Cosmos Web Wallet: [Cosmostation ↗️](https://wallet.cosmostation.io/).
- - On the top right corner, drop down menu, make sure it is set to **fetch.ai**.
- - Click **Connect Wallet**. Click **Connect to Ledger**.
- - Your fetch.ai address will appear in the middle of the screen. Make a note of this address as it will be needed later when staking.
- - Logout of Cosmostation website.
- - Close down the Cosmos App on Ledger Wallet and open up Ethereum App.
-
- 4. **Set MetaMask bridge with Ledger Live Wallet**.
-
- - On your Brave/Chrome browser, open the MetaMask wallet. You will now link this wallet with your Ledger via a bridge. Make sure that MetaMask is set to Ethereum Mainnet.
- - Open the MetaMask wallet and click on top right corner where it has your profile icon.
- - Choose **Connect Hardware Wallet**, a dialog will appear asking you to **Open Ledger Live**.
- - Click **Open Ledger Live**. Ledger Live will then ask you to login (if not done so already). Ledger Live will then display **Expose your device accounts through websocket**.
- - Click **Open** to expose the device via web socket. When doing this for the first time, you will receive a message asking if you want to allow Ledger to make outside connections. Click **OK** on this.
- - Once the connection is established and the bridge is set, Ledger Live will display **Ethereum bridge opened**. Now we can communicate between the two wallets in this process.
- - You will also notice that your MetaMask will now have two accounts on Ethereum Mainnet, one which is your original account that was setup with it. The second account is a hardware account linked to Ledger Wallet with **Hardware** displayed next to it.
-
- 5. **Visit the bridge to move coins onto Cosmostation**.
-
- To complete this phase, visit the [bridge ↗️](https://token-bridge.fetch.ai/).
-
- - Make sure MetaMask is unlocked so it can be connected onto this bridge.
- - Make sure MetaMask is set to the HARDWARE wallet and that you have enough Ethereum in there to sign the transaction and pay the fees for transfer.
-
- 6. **Open Wallet and check bridge details**.
-
- The source address (Ethereum address of HARDWARE wallet) will be already filled in, and you will see a blank field for the Native address (this is your Fetch native destination address from **STEP 3**).
-
- 7. **Enter Fetch address details and make transfer**.
-
- Paste your address starting with **fetch1**, that you identified in STEP 2 into the **Native Address** field, enter the amount, and then click the **Transfer** button. The Ethereum address is connected to the site through Metamask or other browser extension, and needs to be the source from which your tokens will move to Mainnet. The Fetch (Native) address is your destination address, to which they will move on main-net.
-
- 8. **Sign the transaction — first one**.
-
- This will trigger a transaction that will ask you to **approve** the bridge contract for holding your tokens. After signing the transaction in your Brave/Chrome browser, be sure to also sign it on your physical device (Ledger Nano), and it will be submitted to the Ethereum blockchain. Once this step is done, you can check your Ledger Live and see that the Fetch Tokens have transferred. As the first transaction is signed, make sure the bridge between Ledger Nano and MetaMask is still running. This is not needed for the second signing below.
-
- 9. **Sign the transaction — second one**.
-
- To complete the tokens transfer, you will be asked to sign a second transaction. In case this step fails, retry the process again from Step 8 above and you will only need to sign once (since Fetch tokens would have been transferred onto Mainnet).
-
- 10. **Check tokens transferred to validator area**.
-
- After completing these steps, your Fetch address will be credited with tokens that you can delegate to a validator of your choice to start earning staking rewards. Login to [Cosmostation ↗️](https://wallet.cosmostation.io/) as you did in Step 3. Your coins should be present at the centre of the dashboard.
-
- 11. **Delegating stake**.
-
- After completing the transfer onto Fetch AI Mainnet and confirming that the coins are now visible on your dashboard, it is time to stake the coins.
-
- - Make sure Ledger is unlocked and Cosmos App is running.
- - Click on Wallet and select **Reward**.
- - This will show a list of validators to delegate to. (In case you get an error when trying to open the **Reward** section, make sure the Cosmos App is unlocked and running on your Ledger).
- - Validators are listed at the bottom of the screen. Choose a validator to delegate to by clicking on the **Delegate** button. A dialog will appear.
- - Enter the amount of Fetch tokens you want to delegate and then click on the **Generate & Sign Transaction** button.
- - Confirm this on your Ledger wallet and your coins will be sent to the validator for staking.
- - Repeat the process if you wish to delegate to other validators.
- - As each validator is added, this will be displayed in the UI of the page.
-
-### How to stake on Fetch Mainnet using Cosmostation Mobile Wallets: applicable for users on exchanges with ERC20 FET
-
-What you will need:
-
- - A Metamask extension for your browser.
-
- - A Cosmostation Wallet: [iOS ↗️](https://apps.apple.com/us/app/cosmostation/id1459830339) or [Android ↗️](https://play.google.com/store/apps/details?id=wannabit.io.cosmostaion&hl=en&gl=US).
-
-Please, follow the steps below:
-
- a. If you do not have the metamask extension installed on your browser. Download it and create an account. Never give out your metamask private key, never give out your mnemonics, and store your password safe.
-
- b. Let's set Metamask to receive FET. Click on add token and click on **custom** and add the ERC20 FET address [0xaea46A60368A7bD060eec7DF8CBa43b7EF41Ad85 ↗️](https://etherscan.io/address/0xaea46A60368A7bD060eec7DF8CBa43b7EF41Ad85)
-
- c. Send your tokens from your exchange to Metamask. We will take Binance as an example here.
-
- - Go to Wallet/Overview FIAT and SPOT.
- - Withdraw your FET and ETH to your metamask account. You will need some ETH to pay for withdrawal. You can also buy ETH on Metamask directly. To withdraw your FET, copy and paste your Metamask address into the field. **Always use the ERC20 network to send your FET**.
-
- _If you’re on any other exchange, please send your tokens directly to Metamask_.
-
- d. Then, we need to wait for Metamask to receive your FET and ETH which may take a few minutes. If you are stuck, please refresh your page but be patient. If you start to get worried, head over to etherscan.io and check your tx hash. If it is successful, it is down to ETH network congestion but your tokens are on their way.
-
- e. Now, download the Cosmostation Wallet for your phone. Create an account on it. Remember to choose Fetch Mainnet when you’re asked to choose a Cosmo network. Once again you will be asked to store your mnemonics so write them down and keep them somewhere safe.
-
- f. After you have successfully created your wallet on the Cosmostation wallet app, you can go to [Token Bridge ↗️](https://token-bridge.fetch.ai/). Ensure your metamask is connected to the token bridge. Once you have your tokens, connect your metamask with [Token Bridge↗️](https://token-bridge.fetch.ai/). A new window will pop up and you will be prompted to approve the request to connect.
-
- g. _Enter your metamask address in the Ethereum Address, your Cosmostation Wallet address in the Native Address field_. Enter the amount of FET you wish to transfer, note that you must send a minimum of 100 FET across the bridge.
-
- h. Let's then enter the amount — click **Transfer** — pay for the first little transaction with ETH to approve — once the transaction is approved, a metamask pop-up should come asking to pay for the swap. Please pay the second transaction with ETH. If the first transaction succeeds but nothing comes on the page to pay the second transaction : just refresh the page, copy-paste your addresses again, enter again the amount, and you should see the **swap** button now.
-
- i. Once you have transferred and swapped on step **g**, check your Cosmostation wallet and wait for a few minutes before the transferred tokens show up.
-
- l. Once they have arrived you can delegate them to a validator of your choice.
-
-**Congratulations you have successfully staked on Fetch.ai Mainnet 2.0!**
diff --git a/pages/guides/fetch-network/how-to-convert-fet-to-and-from-erc20.mdx b/pages/guides/fetch-network/how-to-convert-fet-to-and-from-erc20.mdx
deleted file mode 100644
index a2c355836..000000000
--- a/pages/guides/fetch-network/how-to-convert-fet-to-and-from-erc20.mdx
+++ /dev/null
@@ -1,29 +0,0 @@
-# How to convert native FET to and from ERC-20 FET
-
-On this page you can find instructions on how to convert ERC-20 to native FETs and viceversa. Visit the [Native and ERC-20 FET tokens ↗️](/concepts/fetch-network/native-and-erc20-fet-tokens) page to understand the difference between the two tokens.
-
-**Let's get started!**
-
-## Native to ERC-20 FET
-
- 1. Ensure you have the [ASI Alliance Wallet installed ↗️](/guides/fetch-network/asi-wallet/web-wallet/get-started) and that the native FETs you want to convert are in this wallet.
- 2. Ensure you have the [Metamask wallet ↗️](https://metamask.io/) installed and that your Ethereum account is set up on it. This is where the ERC-20 FETs will go to.
- 3. Go to the [Token Bridge ↗️](https://token-bridge.fetch.ai/).
- 4. Unlock the Metamask wallet if instructed to do so.
- 5. Ensure the **Native to ERC-20** tab is selected.
- 6. Hit **Connect Browser Wallet** and allow the token bridge to connect to your ASI Alliance Wallet.
- 7. The fields will be automatically populated with the addresses on the two wallets. Ensure these are correct.
- 8. Under **Amount**, enter the amount of tokens you wish to convert.
- 9. Hit **Transfer**.
-
-## ERC-20 to Native FET
-
- 1. Ensure you have the [Metamask wallet ↗️](https://metamask.io/) installed and that the ERC-20 FETs you want to convert are in this wallet.
- 2. Ensure you have the [ASI Alliance Wallet installed ↗️](/guides/fetch-network/asi-wallet/web-wallet/get-started) and that your Fetch.ai account is set up on it. This is where the native FETs will go to.
- 3. Go to the [Token Bridge ↗️](https://token-bridge.fetch.ai/).
- 4. Unlock the Metamask wallet if instructed to do so.
- 5. Ensure the **ERC-20 to Native** tab is selected.
- 6. The Ethereum address should be automatically filled in with the address of the active account on your Metamask wallet. Ensure that it is correct.
- 7. Insert your ASI Alliance Wallet address in the **Native Address** section.
- 8. Under **Amount**, enter the amount of tokens you wish to convert.
- 9. Hit **Transfer** and allow the Token Bridge to connect with your wallet.
diff --git a/pages/guides/fetch-network/how-to-stake.mdx b/pages/guides/fetch-network/how-to-stake.mdx
deleted file mode 100644
index 1fe44b558..000000000
--- a/pages/guides/fetch-network/how-to-stake.mdx
+++ /dev/null
@@ -1,68 +0,0 @@
-import { Callout } from 'nextra/components'
-
-# How to stake FET with the ASI Alliance Wallet
-
-Staking is the process of delegating to a validator. Delegators bond their funds to validator nodes and in doing so support the security and longevity of the network.
-
-As a consequence of the provided support for the network delegators receive rewards in the form of FET. Rewards are paid on a per-block basis and added to the existing rewards.
-
-
- Your funds never leave your wallet throughout the staking duration. You can remove your stake at any time.
- Once you remove your stake you'll have to wait for 21 days before your FET is available. This is the standard waiting time across Cosmos SDK based blockchain projects and acts as a security measure for the network.
-
-
-Additional information on different ways to stake FET tokens can be found [here ↗️](/guides/fetch-network/different-ways-to-stake-the-fet-token). Also, checkout the following guides for a better understanding of the staking process both on **ASI Alliance Web** and **Mobile** Wallet:
-
-- [Stake on ASI Alliance Mobile Wallet ↗️](/guides/fetch-network/asi-wallet/mobile-wallet/stake)
-- [Stake on ASI Alliance Web Wallet ↗️](/guides/fetch-network/asi-wallet/web-wallet/stake)
-
-## Staking
-
-1. Download and install the ASI Alliance browser extension wallet [ASI Alliance Wallet ↗️](https://fetch.ai/get-fetch-wallet)
-
-2. If this is your first time setting up the wallet select the **Create new account** option. If you have an existing account select the **Import existing account** option and restore your wallet by inputting your seed phrase. If you're using a ledger hardware wallet select the **Connect ledger** option.
-
-
- Here, you will find a list of every active [validator ↗️](/concepts/fetch-network/ledger/validators) with whom you can stake your FETs. You can also see the amount of FET staked to each validator and their commission rates.
-
- The validators on this page are ordered according to the number of FETs delegated to them and not their reputation or benefits. Visit the [Choosing a validator ↗️](/guides/fetch-network/re-delegating-staked-fet-token#choosing-a-validator) section for further details on key points to be considered when choosing a validator.
-
-
-3. Log into the wallet and select **Stake** . This will open up the staking interface. Here you can browse all validators and select one or multiple validators to stake with.
-
-
- You can check the details of any validator, including their _voting power_, _self-bonded rate_, _uptime_, _active/inactive status_ at any given time, as well as _contact information_, by heading over to [this page ↗️](https://explore.fetch.ai/validators). For a visualization of the validators' _voting power_ (more is NOT better) check out [this page](https://explore.fetch.ai/voting-power-distribution).
-
-
-4. Choose the FET amount you wish to stake and select the validator of your choice.
-
-
- Don't forget to leave at least 1 available undelegated FET in your wallet. This minimum amount is necessary to pay for transaction fees, claim staking rewards, redelegate and remove your stake. The transaction fee is minimal but it is not zero. This is why it's important to have at least 1 available FET.
-
-
-6. Your ASI Alliance wallet will show you a summary of the transaction. Review it and if you are satisfied confirm the transaction by clicking **Approve** to complete the staking process.
-
-### Claim your staking rewards
-
-1. First of all, ensure you are logged into your [ASI Alliance Wallet ↗️](/guides/fetch-network/asi-wallet/web-wallet/get-started).
-2. From the wallet dashboard select **Claim**.
-
-
- This will claim the total rewards accrued across every validator that you have delegated to.
-
-
-3. The wallet shows you a summary of the transaction. Review it and if you are happy, hit **Approve** to complete the operation.
-
-Upon completion, you will see the rewards added to your **Total Balance**
-
-## Remove your Stake
-
-1. Log into your wallet
-2. In the wallet dashboard click on the **Stake** button. This will open a secondary dashboard.
-3. On the secondary dashboard click on **My Stake**
-4. Select the validator and amount you wish to remove from staking.
-5. The wallet will show you a summary of the transaction. Review it and if you are happy hit **Approve** to complete the operation.
-
-
- When you remove your stake, there is an unbonding (also known as, cooldown) period of 21 days. In your staking dashboard, the **Unbonding Delegations** section shows you the stakes you have removed which are now in the unbonding period. You can also see the amount of FET unbonded and the number of days remaining from the unbonding period. This is how long you need to wait before being able to withdraw the funds to your wallet.
-
diff --git a/pages/guides/fetch-network/ibc-transfers.mdx b/pages/guides/fetch-network/ibc-transfers.mdx
deleted file mode 100644
index f30420a7d..000000000
--- a/pages/guides/fetch-network/ibc-transfers.mdx
+++ /dev/null
@@ -1,102 +0,0 @@
-import { Callout } from 'nextra/components'
-
-# IBC CUDOS Tokens Transfer
-
-## Overview
-
-The Artificial Superintelligence Alliance (ASI) network facilitates CUDOS token reconciliation following the CUDOS network's merger into the ASI Alliance network. This process allows users to migrate their CUDOS tokens to FET tokens based on a pre-agreed conversion rate via the [Companion App ↗️](https://companion.fetch.ai/fetchhub-4/reconciliation) UI.
-
-By following the appropriate steps for either claiming locked tokens or converting liquid tokens, users can securely complete their migration using the Companion App. Ensuring the correct wallet connection is essential for claiming tokens, while for conversion, it is simply a matter of having available liquid CUDOS tokens in the account.
-
-## Claim and Convert options
-
-Users may face two different scenarios when migrating their tokens:
-
-### 1. Claiming locked CUDOS tokens
-
-If CUDOS tokens were previously sent via IBC (Inter-Blockchain Communication) back to their native CUDOS Mainnet chain **after** it was decommissioned, then these tokens became locked forever. Users can claim these locked tokens as FET ones via the [Companion App ↗️](https://companion.fetch.ai/fetchhub-4/reconciliation).
-
-The most crucial aspect of claiming locked tokens is selecting the correct wallet account (with the correct ASI address) in the [ASI Alliance Web Wallet ↗️](/guides/fetch-network/asi-wallet/web-wallet/get-started) extension, otherwise users won't be able to see their claimable tokens in the Companion app UI and consequently claim them. The correct ASI account must be derived from the very same private key as the original sender's account used to transfer CUDOS tokens from the source chain (e.g. Osmosis) to the already decommissioned CUDOS mainnet, which caused the tokens to become locked. Depending on how the original sender's account was created (respectively how the user/owner is usually accessing it), there are two possible ways how to add it to the ASI Wallet Extension:
-
-- **Software wallet**: users will need to provide the same mnemonic seed phrase and HD Derivation path as when the user created the original sender's account .
-
-- **Hardware wallet**: users will need to add the same Ledger Hardware Wallet and use the correct HD Derivation path. In this case, there is no need for a seed phrase, since it is represented by the Ledger Hardware Wallet itself.
-
-If all parameters are correctly provided, the user will end up with the correct ASI wallet account in the ASI Wallet Extension.
-
-#### Walk-through to claim locked CUDOS tokens
-
-1. Open the [Companion App ↗️](https://companion.fetch.ai/fetchhub-4/reconciliation).
-2. Head over to the **Reconciliation** tab.
-
- 
-
-3. Switch to the **CUDOS tokens** tab.
-4. Connect your ASI Web Wallet. If you do not have one, download it from [here ↗️](/guides/fetch-network/asi-wallet/web-wallet/get-started).
-5. You need to ensure that you use the exact wallet address that was originally used to lock CUDOS tokens from the source network. You can add such a wallet within the ASI Wallet by clicking the 3 dots menu button:
-
- 
-
- Then, click **Add a new wallet**.
-
- 
-
- Click **Import existing wallet**.
-
- 
-
- Choose to import a wallet based on a seed phrase (if you have a software wallet) or by connecting a hardware wallet.
-
- 
-
- By using a _software wallet_, you need to import the wallet using the **same** seed phrase as the one related to the wallet you used to lock the CUDOS tokens on the source network.
-
- 
-
- If you know the _HD derivation path_ for your original wallet address, provide it alongside the seed phrase, by clicking the **Advanced Options** button.
-
-
- The **HD derivation path** presents multiple fields that need to be populated: **account**, **exchange** and **index**. These fields of HD path determine the private key of the account, which is going to be imported to the ASI wallet. If they (and seed phrase) are provided correctly, the resulting derived private key will be exactly the same, as the one used to derive the source account used to initially transfer CUDOS tokens from original source chain (e.g. Osmosis) to the decommissioned CUDOS Mainnet chain, thus effectively locking them.
-
-
- 
-
- Click **Next**.
-
-6. Once you connect the new account successfully, the Companion App UI will refresh, and you should be able to check the **Claim** section with the available amount of CUDOS tokens that can be actually claimed.
-
- 
-
-7. Check that the amount is displayed correctly, then proceed to submit the claim request by clicking the **Execute** button.
-
-8. Confirm the transaction within the ASI Wallet and wait for processing.
-
-9. The FET tokens will be credited to your connected ASI account upon successful claim processing.
-
-### 2. Converting liquid CUDOS tokens
-
-If users hold liquid CUDOS tokens on IBC-supported networks, they can convert them to FET tokens using the Companion App.
-
-First, they will need to transfer them via IBC to the ASI Alliance Network, and then convert them to FET tokens using the dedicated Companion App UI.
-
-
- At the moment, _only_ CUDOS tokens on the **Osmosis** and **Archway** networks are supported. In addition, _CUDOS tokens on the Archway network will need to be first transferred over IBC to the Osmosis network, and then from there to the ASI Main network_.
-
-
-During this process, the ASI account itself (its address) is not relevant for the conversion process (opposite to the claiming process described above). **_All that matters is the ownership of CUDOS tokens_**. The Companion App UI will automatically populate the **Convert** field based on the available balance of CUDOS tokens once the ASI account is connected to the app itself.
-
-#### Walk-through to convert liquid CUDOS tokens
-
-1. Open the [Companion App ↗️](https://companion.fetch.ai/fetchhub-4/reconciliation).
-2. Head over to the **Reconciliation** tab.
-3. Connect your [ASI wallet ↗️](/guides/fetch-network/asi-wallet/web-wallet/get-started). Ensure it holds liquid CUDOS tokens on any IBC-supported network. These can be transferred from the source wallet to the ASI wallet straightforwardly.
-4. Navigate to the **CUDOS** tab within the **Reconciliation** page.
-
-
- The available balance of CUDOS tokens should be displayed automatically based on the amount available of liquid CUDOS tokens on your connected wallet.
-
-
-5. Select the amount you wish to convert.
-6. Press **Execute** button.
-7. Confirm the transaction on the wallet and wait for processing.
-8. The corresponding amount of FET tokens will be credited to your ASI wallet upon successful conversion.
diff --git a/pages/guides/fetch-network/intro-fet-token.mdx b/pages/guides/fetch-network/intro-fet-token.mdx
deleted file mode 100644
index 97c8c12aa..000000000
--- a/pages/guides/fetch-network/intro-fet-token.mdx
+++ /dev/null
@@ -1,103 +0,0 @@
-import { Callout } from 'nextra/components'
-
-# Getting Started with FET Token for Agent development
-
-
- This is currently a work in progress and may be subject to further updates and revisions.
-
-
-## Introduction
-
-The FET token was created to facilitate payments in an AI driven world. Where Agents send micro payments to one another which traditional currencies do not support. The FET token is the currency of the **Artificial Superintelligence (ASI) Alliance**, uniting **Fetch.ai**, **Ocean Protocol**, and **SingularityNET**. FET token enabled decentralized AI services, governance, and computational resources.
-
-Whether enabling microtransactions for autonomous [Agents ↗️](/guides/agents/getting-started/whats-an-agent), supporting network operations through staking, or unlocking access to AI tools, the FET token plays a central role into advancing the infrastructure of decentralized AI functionalities. Alrighty, let's get started with the FET token.
-
-## Understanding the FET Token
-
-The FET token is central to enabling the agentic-driven future on the Fetch.ai mainnet and within the broader ASI ecosystem. Its key utilities include:
-
- - **Network Operations**: FET tokens secure the Fetch.ai mainnet through staking and enable decentralized governance.
- - **Agent-Based Systems**: FET is used to register, and interact with autonomous AI agents in Fetch.ai’s ecosystem.
- - **Decentralized Transactions**: FET enables low-cost micropayments and smart contract interactions.
- - **AI Marketplace Access**: Use FET for accessing AI tools, datasets, and compute resources.
-
-## Acquiring FET Tokens
-
-Exchanges are the simplest way to get FET tokens.
-
-Visit a trusted exchange such as Coinbase or Binance. You may need to create an account, which will involve you
-passing [KYC ↗️](https://www.gov.uk/government/publications/know-your-customer-guidance/know-your-customer-guidance-accessible-version). Once your account is enabled, you can buy FET token. You can buy this with most global
-currencies, just check on the exchange which currencies they accept.
-
-## Storing FET
-
-Ideally you would be sending this FET to your agent to transact on the network. However, if you'd like greater
-security or accessibility..
-
-For short-term storage goals, the ASI Wallet is an excellent choice; it provides direct functionalities for daily activities such as staking and interacting with Agents.
-
-For long-term storage goals, you can enhance security by integrating your ASI Wallet with a hardware wallet like Ledger, offering robust protection for your assets. Follow this guide [here ↗️](/guides/fetch-network/asi-wallet/asi-wallet-hardware-connection-guide) if you wish to set up the ASI Alliance extension wallet with a Ledger hardware wallet.
-
-## How to transfer tokens to your Agents
-
-You can download and use the uAgents library to create autonomous Agents capable of interacting with other Agents in a decentralized environment. Check out this guide [here ↗️](/guides/agents/getting-started/installing-uagent) to get started with Agents development.
-
-In order to get your Agent up and running within the ASI ecosystem, you will need to retrieve the Agent's address and fund it with FET tokens to make it correctly register within the network.
-
-
- When creating your account, it is crucial to securely store your [seed phrase ↗️](/guides/agents/getting-started/seedphrase). The seed phrase is essential for accessing your Agent's identity and controlling any funds it holds. Treat it with the highest level of security to prevent unauthorized access!
-
-
-### Getting your Agent address to send tokens to your Agent
-
-The following Python script demonstrates how to create and initialize an Agent using the `uagents` and `cosmpy` libraries, to connect it to the Fetch.ai Mainnet, and retrieve its address and balance information:
-
- ```py copy filename="agent_address_and_balance.py"
- from uagents import Agent, Context
- import cosmpy
-
- from cosmpy.aerial.client import LedgerClient, NetworkConfig
-
- agent = Agent(name="alice", seed="", port=8000, test=False, endpoint=["http://localhost:8000/submit"])
-
- @agent.on_event("startup")
- async def introduce_agent(ctx: Context):
- ctx.logger.info(f"ASI network address:{agent.wallet.address()}")
- ledger_client = LedgerClient(NetworkConfig.fetch_mainnet())
- address: str = agent.wallet.address()
- balances = ledger_client.query_bank_all_balances(address)
- ctx.logger.info(f"Balance of addr: {balances}")
-
- if __name__ == "__main__":
- agent.run()
-
- ```
-
-**You must update the seed value, and store it safely. Losing this value will lose you your tokens.**
-
-In the code example above an Agent named `alice` is initialized with a specified `name`, `port`, `endpoint`, and `seed`
-parameters. When the Agent starts up, it logs the wallet address and queries the balance using the `LedgerClient` connected to the Fetch.ai Mainnet. Finally, the script runs the Agent, which processes the `startup` event and retrieves the balance, allowing the Agent to interact with the Fetch.ai network.
-
-Once you run the above Agent script, you will see your Agent address and balance printed out. You will see something similar to the following output:
-
- ```
- INFO: [alice]: Registration on Almanac API successful
- INFO: [alice]: Registering on almanac contract...
- INFO: [alice]: Registering on almanac contract...complete
- INFO: [alice]: Agent inspector available at https://agentverse.ai/inspect/?uri=http%3A//127.0.0.1%3A8000&address=agent1qdxdrwqek4pt9xt8kggcxus0zm54d4vgdznrs6y5acn26paphervwfj7pdd
- INFO: [alice]: Starting server on http://0.0.0.0:8000 (Press CTRL+C to quit)
- INFO: [alice]: ASI network address:fetch1ujr7wyuvza7uwnkr3usv53hjlwjvu8s7l06vzf
- INFO: [alice]: Balance of addr: []
- ```
-
-You can now use this address to transfer your purchased FET tokens from the exchange to this Agent's address. This
-should be as simple as withdrawing native FET, by selecting the Fetch.ai Mainnet network when withdrawing. Some
-exchanges do not support Native FET, and you will need to use the [token bridge](https://token-bridge.fetch.ai/),
-luckily we have [a guide for that too](/guides/fetch-network/how-to-convert-fet-to-and-from-erc20)
-
-Check out the following resources for more information on Agents and how these integrate within the ASI Ecosystem and perform operations using FET tokens:
-
-- [Agents - uAgents Framework ↗️](/guides/agents/getting-started/whats-an-agent)
-- [The Agentverse ↗️](/concepts/agent-services/agentverse-intro)
-- [AI Engine ↗️](/concepts/ai-engine/ai-engine-intro)
-- [DeltaV ↗️](/concepts/ai-engine/deltav)
diff --git a/pages/guides/fetch-network/jenesis/_meta.json b/pages/guides/fetch-network/jenesis/_meta.json
deleted file mode 100644
index e7e6ba741..000000000
--- a/pages/guides/fetch-network/jenesis/_meta.json
+++ /dev/null
@@ -1,18 +0,0 @@
-{
- "install": {
- "title": "Installation",
- "tags": ["Intermediate", "Python", "Web3"],
- "timestamp": true
- },
- "getting-started": {
- "title": "Getting started",
- "tags": ["Intermediate", "Python", "Web3"],
- "timestamp": true
- },
- "keys": {
- "title": "Keys",
- "tags": ["Intermediate", "Python", "Web3"],
- "timestamp": true
- },
- "contracts": { "title": "Working with contracts", "timestamp": true }
-}
diff --git a/pages/guides/fetch-network/jenesis/contracts/_meta.json b/pages/guides/fetch-network/jenesis/contracts/_meta.json
deleted file mode 100644
index 75dfef089..000000000
--- a/pages/guides/fetch-network/jenesis/contracts/_meta.json
+++ /dev/null
@@ -1,27 +0,0 @@
-{
- "add-profiles": {
- "title": "How to add profiles",
- "tags": ["Intermediate", "Python", "Web3"],
- "timestamp": true
- },
- "add-contracts": {
- "title": "How to add contract templates",
- "tags": ["Intermediate", "Python", "Web3"],
- "timestamp": true
- },
- "compile-contracts": {
- "title": "How to compile contracts",
- "tags": ["Intermediate", "Python", "Web3"],
- "timestamp": true
- },
- "deploy-contracts": {
- "title": "How to deploy contracts",
- "tags": ["Intermediate", "Python", "Web3"],
- "timestamp": true
- },
- "contracts-interaction": {
- "title": "Contract interaction",
- "tags": ["Intermediate", "Python", "Web3"],
- "timestamp": true
- }
-}
diff --git a/pages/guides/fetch-network/jenesis/contracts/add-contracts.mdx b/pages/guides/fetch-network/jenesis/contracts/add-contracts.mdx
deleted file mode 100644
index 74c595ae9..000000000
--- a/pages/guides/fetch-network/jenesis/contracts/add-contracts.mdx
+++ /dev/null
@@ -1,163 +0,0 @@
-import { Callout } from 'nextra/components'
-
-# How to add contract templates
-
-## Introduction
-
-Once you have successfully [created your project ↗️](/guides/fetch-network/jenesis/getting-started#create-a-new-project), you can add **contract templates**.
-
-A **contract template** is a pre-defined, reusable blueprint or pattern for creating a smart contract in a blockchain environment. It provides a structured starting point with predefined functionalities, variables, and logic that can be customized to suit specific use cases.
-
-
- A contract template is a specific implementation that can be added to a project. These templates serve as a foundation for creating contracts by providing pre-configured settings, initial code, and common functionalities. They streamline the process of developing contracts by offering a structured starting point that developers can build upon. By using contract templates, developers can save time and effort in setting up the basic structure and functionalities of their contracts, allowing them to focus on customizing and implementing the specific features required for their use case.
-
-
-## Overview
-
-If you want to add a template to a contract, you first need to navigate into your project's directory and run the following command:
-
- ```
- jenesis add contract
- ```
-
-You can find all the contract templates available in [Jenesis Templates ↗️](https://github.com/fetchai/jenesis-templates) GitHub repository. As for an overview, the available templates are the following:
-
- - **starter**: a bare-bones contract that sets and increments a counter, [here ↗️](https://github.com/fetchai/jenesis-templates/tree/master/contracts/starter).
-
- - **token**: a fungible token contract, [here ↗️](https://github.com/fetchai/jenesis-templates/tree/master/contracts/cw20-base).
-
- - **proxy**: a basic proxy contract, [here ↗️](https://github.com/fetchai/jenesis-templates/tree/master/contracts/cw1-subkeys)
-
- - **multisig**: a fixed multisig contract, [here ↗️](https://github.com/fetchai/jenesis-templates/tree/master/contracts/cw3-fixed-multisig).
-
- - **nft**: a general token contract supporting nfts, [here ↗️](https://github.com/fetchai/jenesis-templates/tree/master/contracts/cw721-base).
-
- - **oracle**: a contract storing a value to be requested for a fee, [here ↗️](https://github.com/fetchai/jenesis-templates/tree/master/contracts/oracle).
-
- - **oracle-client**: a contract for requesting a value for a fee from a specified oracle contract, [here ↗️](https://github.com/fetchai/jenesis-templates/tree/master/contracts/oracle_client).
-
-### Example: CW-20 basic template for fungible token contract
-
-The **cw20-base** template is designed for creating CW-20 tokens on the Fetch.ai blockchain. CW-20 tokens are a standard interface for fungible tokens. This template provides a solid starting point for developers looking to create their own custom CW-20 tokens, complete with essential functionalities like transfers, approvals, and querying balances.
-
-The steps needed to add the **cw20-base** template with the name `my_token` are provided below:
-
- ```
- jenesis add contract cw20-base my_token
- ```
-
-If you need multiple deployments of the same contract, you can use the `--deployments` or `-d` flag to specify multiple deployments and name them:
-
- ```
- jenesis add contract [--deployments ]
- ```
-
- Jenesis will add the deployments to all profiles for the specified contract.
-
-In the example below, `token_1` and `token_2` deployments have been added. This will allow you to deploy `my_token` contract with two different configurations. You can add as many deployments as we wish:
-
- ```
- jenesis add contract cw20-base my_token -d token_1 token_2
- ```
-
-If no deployments are selected when adding a contract, the default deployment name will be equal to the contract name.
-
-The `add contract` command will add a contract template to our jenesis project inside `contracts/my_token/` folder. It will also update the `jenesis.toml` configuration file with the contract information:
-
- ```toml
- [profile.testing.contracts.token_1]
- name = "token_1"
- contract = "my_token"
- network = "fetchai-testnet"
- deployer_key = ""
- init_funds = ""
-
- [profile.testing.contracts.token_2]
- name = "token_2"
- contract = "my_token"
- network = "fetchai-testnet"
- deployer_key = ""
- init_funds = ""
-
- [profile.testing.contracts.token_1.init]
-
- [profile.testing.contracts.token_2.init]
- ```
-
-The `deployer_key` field can be manually specified. You can choose any private key locally available to deploy any specific contract. You can also leave this field empty since the `deploy` command has an optional argument to deploy all contracts inside a specified profile with the same key, overriding this `deployer_key` argument in the `jenesis.toml` file. Checkout the [deploy contracts ↗️](/guides/fetch-network/jenesis/contracts/deploy-contracts) guide for more information.
-
-Finally, the `init` section contains the parameters needed in the instantiation message for this contract to be deployed. The required parameters are taken from the schema file inside the `contracts` directory. Since this contract template doesn't include a schema, it will be generated when [compiling ↗️](/guides/fetch-network/jenesis/contracts/compile-contracts) the `my_token` contract loading the init fields to the `jenesis.toml` file. You will need to manually add the values for these parameters in their correct variable type, which are listed on the schema file. For this **my_token** contract, you need to fill the `init` fields for each deployment after [compiling ↗️](/guides/fetch-network/jenesis/contracts/compile-contracts).
-
-Below, we can find an example for this:
-
- ```
- [profile.testing.contracts.token_1.init]
- decimals = 6
- name = "my_token_name"
- symbol = "SYMBOL"
- initial_balances = [{ address = "fetch1d25ap9danl4726uk2nt307y630v87h3h2vq6pl", amount = "5000"}]
-
- [profile.testing.contracts.token_2.init]
- decimals = 6
- name = "my_token_name_2"
- symbol = "SYMBOL"
- initial_balances = [{ address = "fetch1d25ap9danl4726uk2nt307y630v87h3h2vq6pl", amount = "2000"}]
- ```
-
-If your contract requires nested instantiation messages, you may add fields following this structure:
-
- ```
- [profile.testing.contracts.example-nested-contract.init]
- price = {amount = 1000, denom = DLS}
- info = {performance = {max_speed = 200, unit = kph}, fuel = {consumption = 7, unit = kmpl}}
- ```
-
-
-Before editing the `jenesis.toml` configuration file with the desired `deployer_key` and `init` parameters, make sure to first [compile ↗️](/guides/fetch-network/jenesis/contracts/compile-contracts) your contract. All configuration parameters will restart every time a contract is compiled if the schema has changed
-
-
-You can also add contracts manually by copying and pasting the contract directory from another project you may have. However, they would need to follow the same directory structure as the [starter ↗️](https://github.com/fetchai/jenesis-templates/tree/master/contracts/starter) template.
-
-When adding a contract manually, you need to update the `jenesis.toml` file with the contract information by running the following command:
-
- ```
- jenesis update
- ```
-
-The `update` command will automatically detect which contract is missing in the `jenesis.toml` configuration file by revising the contracts directory.
-
-#### Add contract deployments
-
-You can also add further deployments for a given contract by specifying the contract name and the deployment name.
-
-If you want to add a third token called `token_3` using `my_token` contract, you can run:
-
- ```
- jenesis add deployment my_token token_3
- ```
-
-This will automatically create another deployment entry called `token_3`.
-
-#### Attach deployed contracts
-
-If you add a contract into the project's contract folder that has already been deployed in the network, you can attach the deployment to your project for future interaction using the `attach` command.
-
-You can add a deployment to your project by running the following command:
-
- ```
- jenesis add contract cw20-base my_token -d token_1
- ```
-
-Then, you would need to compile the contract:
-
- ```
- jenesis compile
- ```
-
-You can also attach the contract. In this case, you will need to specify the deployment's name and address. You can optionally specify the profile where you wish to insert the contract into. If this is not specified, the deployment will be attached to the default profile, which is the first profile created in our project, unless the `default` settings are manually changed:
-
- ```
- jenesis attach token_1 fetch18xs97q6h9zgh4sz730a42pp0dqa9sh4eef7eutfkv69q3v2y3x8s72pkua
- ```
-
-This will add the relevant deployment information into a `jenesis.lock` file and you will now be able to interact with `token_1` using [contract interactions ↗️](/guides/fetch-network/jenesis/contracts/contracts-interaction).
diff --git a/pages/guides/fetch-network/jenesis/contracts/add-profiles.mdx b/pages/guides/fetch-network/jenesis/contracts/add-profiles.mdx
deleted file mode 100644
index 1fef34d1f..000000000
--- a/pages/guides/fetch-network/jenesis/contracts/add-profiles.mdx
+++ /dev/null
@@ -1,33 +0,0 @@
-# How to add profiles
-
-## Introduction
-
-A contract **profile** is a contract configuration setting that defines various parameters related to a specific network or environment where a contract will be deployed and interacted with.
-
-## Walk-through
-
-You can add more profiles than the one specified using the `new` command, presented in [getting started ↗️](/guides/fetch-network/jenesis/getting-started), by running the following `add profile` command:
-
- ```
- jenesis add profile my_second_profile
- ```
-
-By default, the profile's network will be set to `fetchai-testnet`, but you can specify it using the `--network` optional argument. The following data will be added to the existing information in your `jenesis.toml` file:
-
- ```toml
- [profile.my_second_profile.network]
- name = "fetchai-testnet"
- chain_id = "dorado-1"
- fee_minimum_gas_price = 5000000000
- fee_denomination = "atestfet"
- staking_denomination = "atestfet"
- url = "grpc+https://grpc-dorado.fetch.ai"
- faucet_url = "https://faucet-dorado.fetch.ai"
- is_local = false
-
- [profile.my_second_profile.contracts]
- ```
-
-At the moment, the available network configurations are `fetchai-testnet`, `fetchai-mainnet`, and `fetchai-localnode`, but Jenesis is easily configurable for other networks by directly editing the `jenesis.toml` file.
-
-In the snippet above, a profile named `my_second_profile` is added with default settings for the `fetchai-testnet` network. This allows developers to easily switch between different network configurations when deploying or interacting with contracts.
diff --git a/pages/guides/fetch-network/jenesis/contracts/compile-contracts.mdx b/pages/guides/fetch-network/jenesis/contracts/compile-contracts.mdx
deleted file mode 100644
index ea64a7d80..000000000
--- a/pages/guides/fetch-network/jenesis/contracts/compile-contracts.mdx
+++ /dev/null
@@ -1,23 +0,0 @@
-import { Callout } from 'nextra/components'
-
-# How to compile contracts
-
-You can compile your contracts by running the following command inside your project's directory:
-
- ```
- jenesis compile [--optimize] [--rebuild] [--no-log]
- ```
-
-This will compile all packages in your project's contracts directory and output the wasm code under the artifacts directory.
-
-If you are using a cargo workspace, jenesis will automatically detect this and the compiled contracts will appear in the `contracts/artifacts/`. Otherwise, they will go to the `artifacts` directory under the individual contracts.
-
-The contracts are simply compiled and not optimized by default. For an **optimized build**, use the flag `--optimize` or `-o`.
-
-In case you need to **force a rebuild**, use the flag `--rebuild` or `-r`. To suppress contract compilation logs, use the flag `--no-log`.
-
-In case of **compilation failure**, the logs will show by default.
-
-
- `jenesis compile` requires that docker to be running and configured with permissions for your user.
-
diff --git a/pages/guides/fetch-network/jenesis/contracts/contracts-interaction.mdx b/pages/guides/fetch-network/jenesis/contracts/contracts-interaction.mdx
deleted file mode 100644
index c4ec5a12f..000000000
--- a/pages/guides/fetch-network/jenesis/contracts/contracts-interaction.mdx
+++ /dev/null
@@ -1,177 +0,0 @@
-import { Callout } from 'nextra/components'
-
-# Contract Interaction
-
-## Introduction
-
-**Contract interactions**, in blockchains networks, refers to the process of communicating with deployed smart contracts. This involves querying contract information or executing specific functions defined within the contract. Interactions can include tasks ranging from checking balances to transferring tokens, and so on.
-
-Profiles provide network and contract configurations, while dynamic methods simplify common tasks. Scripts automate interactions for programmatic tasks. This interaction is vital for utilizing decentralized applications and services offered by smart contracts on the blockchain.
-
-## Start an interaction
-
-You can interact with your project's contracts by using the `shell` or `run` commands.
-
-### Getting started
-
-You can reproduce the examples provided here, by initially adding and compiling a basic [starter ↗️](https://github.com/fetchai/jenesis-templates/tree/master/contracts/starter) contract and a [cw-20 token contract ↗️](https://github.com/fetchai/jenesis-templates/tree/master/contracts/cw20-base) to your project with the following commands:
-
- ```bash
- jenesis add contract starter my_first_contract -d deployment_1
- jenesis add contract cw20-base my_token -d token_1
- jenesis compile
- ```
-
-For more information on contract template examples, visit [Jenesis Templates ↗️](https://github.com/fetchai/jenesis-templates)
-
-### Interactive shell
-
-You can open a shell within which you can easily start an interaction with your contracts, by simply running:
-
- ```bash
- jenesis shell
- ```
-
-If a profile is not selected, the default profile will be selected automatically. You can specify any profile using the `--profile` optional argument:
-
- ```bash
- jenesis shell --profile my_profile
- ```
-
-You will observe the following text indicating the available contracts in your project:
-
- ```
- Network: fetchai-testnet
- Detecting contracts...
- C deployment_1
- C token_1
- Detecting contracts...complete
- ```
-
-
- `jenesis shell` currently requires that contract names use accepted python variable names. For example, using `token-1` instead of `token_1` will generate an error when trying to interact with it.**
-
-
-In this case, we can see that `deployment_1` and `token_1` deployments are available for this project. If these contracts have been already deployed, you can directly interact with them by performing contract queries and executions, such as:
-
- ```py copy
- >>> deployment_1.query(args = {'msg_name': {...}}
- >>> deployment_1.execute(args = {'msg_name': {...}}
- ```
-
-A ledger client (`ledger`) and your locally stored wallet keys will also be available in the shell. For example, if you have a local key named `alice`, you will find this under `wallets['alice']` and you can query the balance as follows:
-
- ```py copy
- >>> ledger.query_bank_balance(wallets['alice'])
- 10000000000000000000
- ```
-
-If the ledger is a testnet with a faucet URL, you can get funds using the `faucet`:
-
- ```py copy
- >>> faucet.get_wealth(wallets['alice'])
- ```
-
-### Dynamic methods
-
-Jenesis also attaches the contract query, execution and deploy messages as dynamic methods.
-
-For instance, the following query:
-
- ```py copy
- >>> token_1.query({"balance": {"address": str(wallet.address())}}))
- ```
-
- can also be run as follows:
-
- ```py
- >>> token_1.balance(address=str(wallet.address()))
- {'balance': '4000'}
- ```
-
-Similarly, instead of using `token_1.execute...`, a transfer can be executed with the following:
-
- ```py copy
- >>> token_1.transfer(amount='1000', recipient=str(wallet2.address()), sender=wallet)
- ```
-
-Additionally, Jenesis has an autocompletion helper for query, execution and deployment arguments. It will show automatically when typing in the shell.
-
-We will now show an example assuming that `token_1` deployment contract has only been compiled and not yet deployed, going through _deployment_, _execution_, and _querying_ using dynamic methods.
-
-For this example, we will first generate two wallets. We provide wealth to the sender wallet in atestfet so it can pay for transaction fees:
-
- ```py copy
- >>> wallet = LocalWallet.generate()
- >>> wallet2 = LocalWallet.generate()
- >>> faucet.get_wealth(wallet)
- ```
-
-We can then proceed to deploy `my_token` contract using `token_1` deployment configuration. We define the arguments for the CW-20 token: `name`, `symbol`, `decimal`, and the `address` that will be funded with these CW-20 tokens. In this case, we will fund wallet's address with 5000 tokens:
-
- ```py copy
- >>> token_1.deploy(name="Crab Coin", symbol="CRAB", decimals=6, initial_balances=[{ "address": str(wallet.address()), "amount" : "5000"}], sender=wallet)
- ```
-
-We can **query wallet balance** to make sure it has been funded with cw20 tokens. Run the following:
-
- ```py copy
- >>> token_1.balance(address=str(wallet.address()))
- {'balance': '5000'}
- ```
-
-We can now execute a CW-20 token **transfer** of 1000 tokens from wallet to wallet2:
-
- ```py copy
- >>> token_1.transfer(amount='1000', recipient=str(wallet2.address()), sender=wallet)
- ```
-
-Finally, we **query both wallets' balance**:
-
- ```py copy
- >>> token_1.balance(address=str(wallet.address()))
- {'balance': '4000'}
- >>> token_1.balance(address=str(wallet2.address()))
- {'balance': '1000'}
- ```
-
-We can observe that _wallet has sent 1000 tokens to wallet2_.
-
-### Executing scripts
-
-You can also assemble the above commands into a script that is executable by the `run` command, in the following way:
-
- ```py copy
- from cosmpy.aerial.wallet import LocalWallet
-
- wallet = LocalWallet.generate()
- faucet.get_wealth(wallet.address())
- wallet2 = LocalWallet.generate()
-
- token_1.deploy(name="Crab Coin", symbol="CRAB", decimals=6, initial_balances=[{ "address": str(wallet.address()), "amount" : "5000"}], sender=wallet)
-
- print("wallet initial cw20 MT balance: ", token_1.balance(address=str(wallet.address())))
-
- tx = token_1.transfer(amount='1000', recipient=str(wallet2.address()), sender=wallet)
- print("transferring 1000 cw20 MT tokens from wallet to wallet2")
- tx.wait_to_complete()
-
- print("wallet final cw20 MT balance: ", token_1.balance(address=str(wallet.address())))
- print("wallet2 final cw20 MT balance: ", token_1.balance(address=str(wallet2.address())))
- ```
-
-If you paste the above code into the file `script.py` inside the project's directory, you can run it with:
-
- ```
- jenesis run script.py
- ```
-
-And you will observe the same output as before. You can also specify the profile as an optional argument using `--profile`.
-
-Finally, you can pass arguments to the script just as you would to a standard Python script by placing all the arguments to the script after the `--` delimiter:
-
- ```
- jenesis run script.py [--profile profile_name] -- arg1 arg2 --key1 value1 --key2 value2
- ```
-
-For a better understanding, visit the [CosmPy ↗️](/guides/fetch-network/cosmpy/install) documentation for more contract interaction examples.
diff --git a/pages/guides/fetch-network/jenesis/contracts/deploy-contracts.mdx b/pages/guides/fetch-network/jenesis/contracts/deploy-contracts.mdx
deleted file mode 100644
index 45b67005e..000000000
--- a/pages/guides/fetch-network/jenesis/contracts/deploy-contracts.mdx
+++ /dev/null
@@ -1,60 +0,0 @@
-import { Callout } from 'nextra/components'
-
-# How to deploy contracts
-
-Once you have successfully compiled your contracts, you need to make sure to fill out the necessary instantiation message information under the `init` field in the `jenesis.toml` file.
-
-
-`jenesis deploy` currently requires that each contract's directory name matches the `.wasm` file name under the `artifacts` directory**.
-
-
-You can **deploy all the contracts inside a profile**, by following one of these two options:
-
- 1. You can fill the `deployer_key` field for each contract inside the `jenesis.toml` file (keys can be different for each contract) and run the following command:
-
- ```
- jenesis deploy [--profile profile_name]
- ```
-
- Each contract inside the specified profile will be deployed with the specified key.
-
- 2. You can simply specify a certain key as an argument of the deploy command:
-
- ```
- jenesis deploy key_name [--profile profile_name]
- ```
-
- The `deployer_key` field will be ignored in this case and all contracts inside the specified profile will be deployed using the key `key_name`.
-
-After running either of the commands mentioned above, all the deployment information will be saved in the `jenesis.lock` file inside your project's directory and depicted as follows:
-
- ```toml
- [profile.testing.my_first_contract]
- checksum = "ecf640a7512be3777c72ec42aff01fdb22897b71953011af3c41ee5dbf3d3bc5"
- digest = "be4a4bdfeb4ed8f504c7b7ac84e31ad3876627398a6586b49cac586633af8b85"
- address = "fetch16l239ggyr4z7pvsxec0ervlyw03mn6pz62l9ss6la94cf06awv0q36cq7u"
- code_id = 2594
- ```
-
-## Deploy contracts depending on other deployments
-
-You can point to other contract addresses in any contract's instantiation message if required.
-
-For instance, if you have contracts `A`, `B`, and `C` within our project, but contract `A` requires contract's `B` deployment address in its instantiation message and contract `B` requires contract's `C` deployment address, these will need to be deployed in the following order: `C`, `B`, `A`.
-
-In order to provide this information to `Jenesis` you will need to specify where exactly these contract addresses need to be inserted inside the instantiation messages. You can do this by writing the `$` symbol followed by the contract name in the corresponding field in the init parameters:
-
- ```toml
- [profile.testing.contracts.A.init]
- name = "A"
- token_contract_address = "$B"
-
- [profile.testing.contracts.B.init]
- token_name = "my_token"
- liquidity_contract_address = "$C"
-
- [profile.testing.contracts.C.init]
- count = 5
- ```
-
-Finally, `Jenesis` will detect this information and deploy the contracts in the correct order: `C`, `B`, `A`.
diff --git a/pages/guides/fetch-network/jenesis/getting-started.mdx b/pages/guides/fetch-network/jenesis/getting-started.mdx
deleted file mode 100644
index bf1ecaed1..000000000
--- a/pages/guides/fetch-network/jenesis/getting-started.mdx
+++ /dev/null
@@ -1,137 +0,0 @@
-import { Callout } from 'nextra/components'
-
-# Getting started
-
-There are multiple commands integrated into jenesis that allow you to perform a variety of tasks.
-A full list of these commands is provided below:
-
- - `new`
- - `init`
- - `add`
- - `update`
- - `attach`
- - `compile`
- - `keys`
- - `deploy`
- - `run`
- - `shell`
- - `network`
-
-In the following section of this page, we will cover the first commands so to show you **how to create a new project** and **how to configure a network**.
-
-For additional information, have a look at the [Keys ↗️](/guides/fetch-network/jenesis/keys) documentation for information about managing keys using Jenesis and the Working with contracts section, which illustrates different contract related executable operations using Jenesis tools and commands.
-
-**Let's get started!**
-
-## Create a new project
-
-You can create a new project using the `new` command as depicted below:
-
- ```
- jenesis new my_project [--profile my_profile] [--network network_name]
- ```
-
-This will create a new directory called `my_project`. You can use `--profile` and `--network` optional arguments to provide additional arguments for profile and network desired for the project. Whenever these arguments are not used, these will be set to `testing` and `fetchai-testnet` respectively.
-
-Inside this directory for your project, a `jenesis.toml` file will be created containing the following information:
-
- ```toml
- [project]
- name = "my_project"
- authors = [ "Alice Tyler "]
- keyring_backend = "os"
-
- [profile.my_profile]
- default = true
-
- [profile.my_profile.network]
- name = "fetchai-testnet"
- chain_id = "dorado-1"
- fee_minimum_gas_price = 5000000000
- fee_denomination = "atestfet"
- staking_denomination = "atestfet"
- url = "grpc+https://grpc-dorado.fetch.ai"
- faucet_url = "https://faucet-dorado.fetch.ai"
- is_local = false
-
- [profile.my_profile.contracts]
- ```
-
- The project's `name` is the argument passed to the `new` command while the authors field is populated by querying the user's GitHub username and email address. The profile's network will be filled with the relevant configuration variables. The contracts field will remain empty until new contracts are added. This `my_profile` profile will be set as the default profile, this means that every time you use a jenesis command without specifying a profile, `my_profile` will be used.
-
-An empty `contracts` folder will also be created inside `my_project` directory that will eventually contain all the information needed to compile and deploy the desired contracts.
-
-The `init` command is similar to the `new`` command, but in this case, you will not need a project `name` argument since **this command is intended to run inside an existing project directory**:
-
- ```
- jenesis init [--profile my_profile] [--network network_name]
- ```
-
-This command will create the same files and folders inside your project directory as the ones described for the `new` command above.
-
-If using a cargo workspace, you just need to navigate to the top level of your project and run the `init` command shown above. This will create the `jenesis.toml` configuration file inside your workspace including all the relevant information from existing contracts.
-
-## Configure a network
-
-**Jenesis will configure the project to run on the latest stable Fetch.ai testnet by default,**. Use `fetchai-mainnet` to configure for the Fetch.ai mainnet or directly edit the `jenesis.toml` file to configure for other networks.
-
-If you want to test on a local node, you will need to pass the argument `--network fetchai-localnode` when creating a project:
-
- ```
- jenesis new my_project --network fetchai-localnode
- ```
-
-or:
-
- ```
- jenesis init --network fetchai-localnode
- ```
-
-The configuration can be found under the `network` heading in the `jenesis.toml` file and can be changed as desired:
-
- ```toml
- [profile.testing.network]
- name = "fetchai-localnode"
- chain_id = "localnode"
- fee_minimum_gas_price = 5000000000
- fee_denomination = "atestfet"
- staking_denomination = "atestfet"
- url = "grpc+http://127.0.0.1:9090/"
- is_local = true
- keep_running = false
- cli_binary = "fetchd"
- validator_key_name = "validator"
- mnemonic = "gap bomb bulk border original scare assault pelican resemble found laptop skin gesture height inflict clinic reject giggle hurdle bubble soldier hurt moon hint"
- password = "12345678"
- moniker = "test-node"
- genesis_accounts = [ "fetch1vas6cc9650z0s08230ytqjphgzl5tcq9crqhhu",]
- timeout_commit = "5s"
- debug_trace = true
- ```
-
- In particular, **to fund some accounts for testing**, replace the `genesis_accounts` field with the addresses to be funded.
-
-When running any of the commands `deploy`, `run`, `shell`, and `attach`, Jenesis will check for a currently running local node. If there is not one provided, a new one will be created in a docker container.
-
-If you wish to **keep a local node running**, you need to set the `keep_running` parameter to `true`. Otherwise, nodes will be stopped after any of the command mentioned above finish running.
-
-At any time, **you can start or stop a local node from running**, using the following commands:
-
- ```
- jenesis network start [--profile my_profile]
- ```
-or:
-
- ```
- jenesis network stop [--profile my_profile]
- ```
-
-You can also **view the logs from the local node**, by simply running:
-
- ```
- jenesis network logs [--profile my_profile]
- ```
-
-
- Checkout our [GitHub repository ↗️](https://github.com/fetchai/jenesis) for Jenesis.
-
diff --git a/pages/guides/fetch-network/jenesis/install.mdx b/pages/guides/fetch-network/jenesis/install.mdx
deleted file mode 100644
index d735e1815..000000000
--- a/pages/guides/fetch-network/jenesis/install.mdx
+++ /dev/null
@@ -1,28 +0,0 @@
-import { Callout } from 'nextra/components'
-
-# Installation 🛠
-
-## Introduction
-
-**Jenesis** is a command line tool for rapid contract and service development for the Fetch.ai blockchain network and other CosmWasm-enabled blockchains ecosystems.
-
-## System Requirements
-
-If you want to correctly use Jenesis, installation requires:
-
- - **OS**: Linux, MacOS.
- - **Python**: 3.8 to 3.10.
- - **Docker**: 20.10.22 or higher recommended.
- - **Git**: any.
-
-## Installation
-
-You can install Jenesis via [PyPI ↗️](https://pypi.org/project/jenesis/). MAke sure you satisfy the system requirements above provided, then, simply run:
-
- ```
- pip install jenesis
- ```
-
-
- This documentation is currently under construction, and the content may not be up-to-date.
-
diff --git a/pages/guides/fetch-network/jenesis/keys.mdx b/pages/guides/fetch-network/jenesis/keys.mdx
deleted file mode 100644
index 0dd056eff..000000000
--- a/pages/guides/fetch-network/jenesis/keys.mdx
+++ /dev/null
@@ -1,16 +0,0 @@
-# Keys
-
-You can use the `keys` command to either list all the locally available `keys` or show the address of a specific key.
-You can list all the `keys` available by simply running the following command:
-
- ```
- jenesis keys list
- ```
-
-On the other hand, you can look up the address for a specified key by running the `show` command and pass the `key` name as an argument:
-
- ```
- jenesis keys show my_key
- ```
-
-If you wish to access other key functionalities, including _adding new keys_, _looking up an address_, and _recovering keys_, you can use the [Fetchd CLI - Managing Keys ↗️](/guides/fetch-network/ledger/cli/keys) guide.
diff --git a/pages/guides/fetch-network/ledger/_meta.json b/pages/guides/fetch-network/ledger/_meta.json
deleted file mode 100644
index 860fab9ed..000000000
--- a/pages/guides/fetch-network/ledger/_meta.json
+++ /dev/null
@@ -1,43 +0,0 @@
-{
- "installation": {
- "title": "Installation",
- "tags": ["Intermediate", "Python", "Web3"],
- "timestamp": true
- },
- "snapshots": {
- "title": "How to use chain state snapshots",
- "tags": ["Intermediate", "Python", "Web3"],
- "timestamp": true
- },
- "state-sync": {
- "title": "State-synchronization (state-sync)",
- "tags": ["Intermediate", "Python", "Web3"],
- "timestamp": true
- },
- "setup-validator-node": {
- "title": "How to set up a validator node",
- "tags": ["Intermediate", "Python", "Web3"],
- "timestamp": true
- },
- "joining-testnet": {
- "title": "How to join a testnet",
- "tags": ["Intermediate", "Python", "Web3"],
- "timestamp": true
- },
- "single-node-testnet": {
- "title": "How to run a single node test network",
- "tags": ["Intermediate", "Python", "Web3"],
- "timestamp": true
- },
- "governance": {
- "title": "Governance",
- "tags": ["Intermediate", "Python", "Web3"],
- "timestamp": true
- },
- "faucet": {
- "title": "How to get testnet tokens via the Token Faucet",
- "tags": ["Intermediate", "Python", "Web3"],
- "timestamp": true
- },
- "cli": { "title": "CLI - Command Line Interface", "timestamp": true }
-}
diff --git a/pages/guides/fetch-network/ledger/cli/_meta.json b/pages/guides/fetch-network/ledger/cli/_meta.json
deleted file mode 100644
index 6fb538237..000000000
--- a/pages/guides/fetch-network/ledger/cli/_meta.json
+++ /dev/null
@@ -1,32 +0,0 @@
-{
- "intro": {
- "title": "CLI - Introduction",
- "tags": ["Intermediate", "Python", "Web3"],
- "timestamp": true
- },
- "keys": {
- "title": "CLI - Managing keys",
- "tags": ["Intermediate", "Python", "Web3"],
- "timestamp": true
- },
- "tokens": {
- "title": "CLI - Managing tokens",
- "tags": ["Intermediate", "Python", "Web3"],
- "timestamp": true
- },
- "multisig-keys": {
- "title": "CLI - Multisig keys",
- "tags": ["Intermediate", "Python", "Web3"],
- "timestamp": true
- },
- "delegator": {
- "title": "CLI - Delegation",
- "tags": ["Intermediate", "Python", "Web3"],
- "timestamp": true
- },
- "governance-proposals": {
- "title": "Governance proposals",
- "tags": ["Intermediate", "Python", "Web3"],
- "timestamp": true
- }
-}
diff --git a/pages/guides/fetch-network/ledger/cli/delegator.mdx b/pages/guides/fetch-network/ledger/cli/delegator.mdx
deleted file mode 100644
index a0779fdee..000000000
--- a/pages/guides/fetch-network/ledger/cli/delegator.mdx
+++ /dev/null
@@ -1,298 +0,0 @@
-import { Callout } from 'nextra/components'
-
-# CLI - Delegation
-
-Delegations refers to the act of assigning the responsibility of validating transactions and creating new blocks to a specific validator node. Below you can find different operations executable through the [CLI ↗️](/guides/fetch-network/ledger/cli/intro).
-
-## How to query the current staking holdings of validators
-
-You can query the current staking holdings of validators using the `fetchd`CLI, and run the following command:
-
- ```bash
- fetchd query staking validators
- ```
-
-This command will provide information about all the existing validators in the network, including details such as their operator address, consensus public key, status, tokens staked, commission rates, and more.
-
-The output will be a list of validators, each represented in a block of information, similar to the example you provided earlier. This information gives an overview of each validator's status and staked tokens.
-
-On `dorado` test network, this command will produce an output similar to the following:
-
- ```text
- - |
- operatoraddress: fetchvaloper1z72rph6l5j6ex83n4urputykawcqg6t98xul2w
- conspubkey: fetchvalconspub1zcjduepq3urw6c6u0zvqmde4vr4gmy56nnq57shdhg56jynpu8n3s74hrm0q0mzqrx
- jailed: false
- status: 2
- tokens: "1000000000000000000000"
- delegatorshares: "1000000000000000000000.000000000000000000"
- description:
- moniker: validator5
- identity: ""
- website: ""
- security_contact: ""
- details: ""
- unbondingheight: 0
- unbondingcompletiontime: 1970-01-01T00:00:00Z
- commission:
- commission_rates:
- rate: "0.050000000000000000"
- max_rate: "0.100000000000000000"
- max_change_rate: "0.010000000000000000"
- update_time: 2021-02-12T12:41:25.579730119Z
- minselfdelegation: "1000000000000000000000"
- producingblocks: true
- - |
- operatoraddress: fetchvaloper1ysc8n5uspv4698nyk8u75lx98uu92zt7m3udw8
- conspubkey: fetchvalconspub1zcjduepqmxr8gmcs6pwuxpsma264ax59wxtxd3vchrcv2c06deq9986kwt3s0wsk6n
- jailed: false
- status: 2
- tokens: "1000000000000000000000"
- delegatorshares: "1000000000000000000000.000000000000000000"
- description:
- moniker: validator2
- identity: ""
- website: ""
- security_contact: ""
- details: ""
- unbondingheight: 0
- unbondingcompletiontime: 1970-01-01T00:00:00Z
- commission:
- commission_rates:
- rate: "0.050000000000000000"
- max_rate: "0.100000000000000000"
- max_change_rate: "0.010000000000000000"
- update_time: 2021-02-03T13:00:00Z
- minselfdelegation: "1000000000000000000000"
- producingblocks: true
- ...
- ```
-
-Similarly, if you wish to retrieve the same information but now for a **single validator**, use the following command, by providing the `operator_address` of the specific validator:
-
- ```bash
- fetchd query staking validator operator_address
- ```
-
-For instance:
-
- ```bash
- fetchd query staking validator fetchvaloper1z72rph6l5j6ex83n4urputykawcqg6t98xul2w
- ```
-
-This command will provide detailed information about the specific validator, including their commission rates, minimum self-delegation, and other relevant details.
-
-A delegator will be particularly interested in the following keys:
-
- - `commission/commission_rates/rate`: the commission rate on revenue charged to any delegator by the validator.
- - `commission/commission_rates/max_change_rate`: the maximum daily increase of the validator's commission. This parameter cannot be changed by the validator operator.
- - `commission/commission_rates/max_rate`: the maximum commission rate this validator can charge. This parameter cannot be changed by the validator operator.
- - `minselfdelegation`: minimum amount of `atestfet` the validator need to have bonded at all time. If the validator's self-bonded stake falls below this limit, their entire staking pool (i.e. all its delegators) will unbond. This parameter exists as a safeguard for delegators. Indeed, when a validator misbehaves, part of their total stake gets slashed. This includes the validator's self-delegateds stake as well as their delegators' stake. Thus, a validator with a high amount of self-delegated `atestfet` has more skin-in-the-game than a validator with a low amount. The minimum self-bond amount parameter guarantees to delegators that a validator will never fall below a certain amount of self-bonded stake, thereby ensuring a minimum level of skin-in-the-game. This parameter can only be increased by the validator operator.
-
-### How to query the delegations made to a validator
-
-You can **query the list of delegations made to a specific validator** using the `fetchd` command-line interface, and run the following command:
-
- ```bash
- fetchd query staking delegations-to fetchvaloper1z72rph6l5j6ex83n4urputykawcqg6t98xul2w
- ```
-
-Here, replace `VALIDATOR_OPERATOR_ADDRESS` with the actual operator address of the validator you are interested in. For instance:
-
- ```bash
- fetchd query staking delegations-to VALIDATOR_OPERATOR_ADDRESS
- ```
-
-This command will provide information about the delegations made to the specified validator, including details such as the delegator's address, the validator's address, and the amount of shares and tokens delegated.
-
-Below, you can find an example of delegations to `validator2` received on `dorado` testnet:
-
- ```text
- - delegation:
- delegator_address: fetch1z72rph6l5j6ex83n4urputykawcqg6t9zzruef
- validator_address: fetchvaloper1z72rph6l5j6ex83n4urputykawcqg6t98xul2w
- shares: "1000000000000000000000.000000000000000000"
- balance:
- denom: atestfet
- amount: "1000000000000000000000"
- - delegation:
- delegator_address: fetch15fn3meky8ktfry3qm73xkpjckzw4dazxpfx34m
- validator_address: fetchvaloper1z72rph6l5j6ex83n4urputykawcqg6t98xul2w
- shares: "100000.000000000000000000"
- balance:
- denom: atestfet
- amount: "100000"
- ```
-
-This output shows two delegations made to the validator, along with the delegator's address, the validator's address, the number of shares, and the amount of tokens delegated.
-
-### How to query re-delegations
-
-Re-delegation is the process of transferring already delegated tokens from one validator to another. This allows participants to change their delegation strategy without having to unbond and wait for the unbonding period to complete.
-
-Delegators can choose to re-delegate the tokens they already delegated from one validator to another at any time. Re-delegation takes effect immediately, without any waiting period. However, the tokens can not be re-delegated until the initial re-delegation transaction has completed its 21 day completion time. The unlocking time is indicated by the `redelegationentry/completion_time` field in the outputs below.
-
-You can **query the list of re-delegations made from a validator** by using the `fetchd` command-line interface and run the following command:
-
- ```bash
- fetchd query staking redelegations-from VALIDATOR_OPERATOR_ADDRESS
- ```
-
-Replace `VALIDATOR_OPERATOR_ADDRESS` with the actual operator address of the validator you are interested in. For instance:
-
- ```bash
- fetchd query staking redelegations-from fetchvaloper1z72rph6l5j6ex83n4urputykawcqg6t98xul2w
- ```
-
-This command will provide information about the re-delegations made from the specified validator, including details such as the delegator's address, the source validator's address, the destination validator's address, and information about the re-delegation entries. The output will be a list of re-delegations, each represented in a block of information. Below you can find an example output:
-
- ```text
- fetchd query staking redelegations-from fetchvaloper1z72rph6l5j6ex83n4urputykawcqg6t98xul2w
- - redelegation:
- delegator_address: fetch15fn3meky8ktfry3qm73xkpjckzw4dazxpfx34m
- validator_src_address: fetchvaloper1z72rph6l5j6ex83n4urputykawcqg6t98xul2w
- validator_dst_address: fetchvaloper122veneudkzyalay6gusvrhhpp0560mparpanvu
- entries: []
- entries:
- - redelegationentry:
- creation_height: 291037
- completion_time: 2021-03-24T14:24:38.973444629Z
- initial_balance: "50000"
- shares_dst: "50000.000000000000000000"
- balance: "50000"
- - redelegationentry:
- creation_height: 291133
- completion_time: 2021-03-24T14:33:43.425472866Z
- initial_balance: "10000"
- shares_dst: "10000.000000000000000000"
- balance: "10000"
- ```
-
-Here, delegator `fetch15fn3meky8ktfry3qm73xkpjckzw4dazxpfx34m` issued 2 re-delegations from `fetchvaloper1z72rph6l5j6ex83n4urputykawcqg6t98xul2w` to `fetchvaloper122veneudkzyalay6gusvrhhpp0560mparpanvu`:
-
-Similarly, you can obtain the list of re-delegations issued by a delegator by running the following command:
-
- ```bash
- fetchd query staking redelegations fetch15fn3meky8ktfry3qm73xkpjckzw4dazxpfx34m
- ```
-
-### How to query rewards
-
-Once you have delegated tokens to a validator, you will be eligible to a share of the rewards the validator collects.
-
-If you wish to **retrieve all the outstanding rewards for a specific address**, run the following command using the `fetchd` command-line interface, :
-
- ```bash
- fetchd query distribution rewards DELEGATOR_ADDRESS
- ```
-
-You will need to replace `DELEGATOR_ADDRESS` with the actual address of the delegator whose rewards you want to query. For instance:
-
- ```bash
- fetchd query distribution rewards fetch15fn3meky8ktfry3qm73xkpjckzw4dazxpfx34m
- ```
-
-This command will provide information about the rewards earned by the specified delegator, including details such as the validator addresses and the amount of rewards in different denominations. The output will be a list of rewards, each represented in a block of information. Below you can find an example output:
-
- ```text
- rewards:
- - validator_address: fetchvaloper1z72rph6l5j6ex83n4urputykawcqg6t98xul2w
- reward:
- - denom: atestfet
- amount: "0.000000000000200000"
- - validator_address: fetchvaloper1ysc8n5uspv4698nyk8u75lx98uu92zt7m3udw8
- reward:
- - denom: atestfet
- amount: "0.000000000001000000"
- total:
- - denom: atestfet
- amount: "0.000000000001200000"
- ```
-
-In this example, the delegator at `DELEGATOR_ADDRESS` has earned rewards from two different validators on `dorado` test network. The rewards are listed in different denominations, such as `atestfet`.
-
-You can also **filter rewards for a given validator**. For instance, you can filter rewards for `validator5` (`fetchvaloper1z72rph6l5j6ex83n4urputykawcqg6t98xul2w`) as shown below:
-
- ```bash
- fetchd query distribution rewards fetch15fn3meky8ktfry3qm73xkpjckzw4dazxpfx34m fetchvaloper1z72rph6l5j6ex83n4urputykawcqg6t98xul2w
- ```
-
-In the output, we get the rewards from this specific validator:
-
- ```text
- - denom: atestfet
- amount: "0.000000000000200000"
- ```
-
-## Delegator operations
-
-### How to delegate tokens
-
-If you want to delegate `1000000 atestfet` tokens to the `fetchvaloper1z72rph6l5j6ex83n4urputykawcqg6t98xul2w` validator from the account `myKey`, then you will need to use the following command:
-
- ```bash
- fetchd tx staking delegate fetchvaloper1z72rph6l5j6ex83n4urputykawcqg6t98xul2w 1000000atestfet --from myKey
- ```
-
-This will require a confirmation before issuing a transaction. After the transaction gets processed, it should appear under the delegations of the `fetchvaloper1z72rph6l5j6ex83n4urputykawcqg6t98xul2w` validator.
-
-
- Once delegated, tokens can only be _re-delegated_ to another validator, or _unbond_ in order to be returned to their original account. It is important to note that those two operations take **21 days to complete**, period in which the involved tokens will be unavailable.
-
-
-### Re-delegating tokens
-
-**Re-delegating tokens allows you to transfer already delegated tokens from one validator to another**.
-
-From the above example where you delegated `1000000 atestfet` to `fetchvaloper1z72rph6l5j6ex83n4urputykawcqg6t98xul2w`, you can now re-delegate parts or all of those tokens to another validator. For instance, you can re-delegate `400000 atestfet` from `fetchvaloper1z72rph6l5j6ex83n4urputykawcqg6t98xul2w` to `fetchvaloper122veneudkzyalay6gusvrhhpp0560mparpanvu` by running the following command:
-
- ```bash
- fetchd tx staking redelegate fetchvaloper1z72rph6l5j6ex83n4urputykawcqg6t98xul2w fetchvaloper122veneudkzyalay6gusvrhhpp0560mparpanvu 400000atestfet --from myKey
- ```
-
-This will prompt for confirmation and issue a new transaction once accepted.
-
-From here, if you inspect the delegations from our account, you will be able to see that your delegated tokens are now:
-
- - `600000atestfet` to validator `fetchvaloper1z72rph6l5j6ex83n4urputykawcqg6t98xul2w` (our initial 1000000 minus the 400000 re-delegated).
- - `400000atestfet` to validator `fetchvaloper122veneudkzyalay6gusvrhhpp0560mparpanvu`.
-
-Now, those `400000 atestfet` you re-delegated can not be re-delegated anymore for 21 days (the exact date can be found by querying the re-delegation transaction, under the `completion_time` key).
-
-
- It is still possible to unbond those tokens if needed.
-
-
-### How to unbond tokens
-
-**Bonding** refers to the act of locking up a certain amount of cryptocurrency tokens in a wallet or smart contract to participate in the network's consensus mechanism. These tokens are often referred to as the **stake**. Conversely, **unbonding** is the process of withdrawing or releasing the previously bonded tokens. When a user initiates an unbonding transaction, they are indicating that they want to take back their tokens from the staking mechanism.
-
-You can transfer parts or all of our delegated tokens back to your account at any time by running the following command:
-
- ```bash
- fetchd tx staking unbond fetchvaloper1z72rph6l5j6ex83n4urputykawcqg6t98xul2w 300000atestfet --from myKey
- ```
-
-Once again, this will prompt for confirmation and issue a transaction, initiating the transfer of `300000 atestfet` from our stake on `fetchvaloper1z72rph6l5j6ex83n4urputykawcqg6t98xul2w` validator address back to your account. Those tokens will then be available **after a 21 day period** (the exact date can be found by querying the re-delegation transaction, under the `completion_time` key).
-
-### How to withdraw rewards
-
-In order **to transfer rewards to the wallet**, run the following command:
-
- ```bash
- fetchd tx distribution withdraw-rewards validator_address --from myKey
- ```
-
-It requires the validator address from where the reward is withdrawn, and the name of the account private key having delegated tokens to the validator. For instance:
-
- ```bash
- fetchd tx distribution withdraw-rewards fetchvaloper1z72rph6l5j6ex83n4urputykawcqg6t98xul2w --from myKey
- ```
-
-You can **claim all rewards when you have delegated tokens to multiple validators**, by running the following command:
-
- ```bash
- fetchd tx distribution withdraw-all-rewards --from myKey
- ```
-
-The rewards will appear on the account as soon as the transaction is being processed.
diff --git a/pages/guides/fetch-network/ledger/cli/governance-proposals.mdx b/pages/guides/fetch-network/ledger/cli/governance-proposals.mdx
deleted file mode 100644
index aea025fc0..000000000
--- a/pages/guides/fetch-network/ledger/cli/governance-proposals.mdx
+++ /dev/null
@@ -1,111 +0,0 @@
-# Governance proposals 📝
-
-Within any decentralized network, any significant change or adjustment should be proposed and subsequently agreed upon by the community or stakeholders involved. This process ensures that decisions are made collectively, helping to maintain transparency, fairness, and the overall integrity of the network.
-
-Hence, **a governance proposal must be submitted to change any attribute of a network**. This could be a simple poll, a software update or a governing parameter change. Whether it is a minor parameter tweak or a major software update, the proposal process is a crucial step in decentralized systems.
-
-For further information on governance within the Fetch Ledger, have a look at the following [documentation ↗️](/guides/fetch-network/ledger/governance)
-
-### Parameter change
-
-This is an example of the process in which network parameters may be changed through the use of a governance proposal.
-
-The values within this code can be changed in order to alter the minimum deposited fund threshold for a proposal to enter the voting phase, and the length of the deposit stage in which the minimum deposit threshold must be met.
-
- ```
- # A JSON file containing the following code should be created to instantiate the proposal.
- # The two variables of interest are the "amount" which is set from 10000000stake to 1000stake
- # and the "max_deposit_period" which is changed from the default value to 7200000000000
- # equal to 2 hours, instead of the standard 2 days (in nanoseconds).
-
- {
- "title": "Staking Param Change",
- "description": "Update max validators",
- "changes": [
- {
- "subspace": "staking",
- "key": "MaxValidators",
- "value": 105
- }
- ],
- "deposit": "1000000000000000000atestfet"
- }
- ```
- ```
- # Create initial proposal by uploading the JSON file
- # this is signed by a key 'proposer' that provides a portion of the current threshold deposit
- fetchd tx gov submit-proposal --proposal ~/json_path/proposal.json --from proposer
-
- # In order to later refer to this proposal, the proposal_id can be determined
- fetchd query gov proposals
- ```
-
-### Proposal deposit phase
-
-The characteristics of the deposit phase are described by a set of network governance parameters, where the deposit period is two days from the initial proposal deposit until expiration, and a minimum threshold of 10000000 denom as default. The minimum threshold must be met during this deposit period in order to proceed to the voting phase. The proposer may provide all of this threshold, or just some. In which case, supporters of the proposal may donate additional funding towards the goal of meeting the threshold.
-
-At any point of the deposit stage, the deposit pot can be queried:
-
- ```
- # To get the proposal ID, use the txhash obtained when the proposal was submitted and run the following command:
- fetchd query tx
-
- # This command returns a text representation of the current total deposit value of a proposal
- fetchd query gov deposits
-
- # Other users may contribute to funding the proposal using
- fetchd tx gov deposit --from contributor
- ```
-
-### Proposal voting and querying
-
-After the deposit period has passed, there are two outcomes:
-
- - The current minimum threshold is met.
- - The value is not met and the funds are returned.
-
-In the first case this proposal is submitted and to be voted on, returning a tally at the end of the voting period.
-
-In order to submit a vote on a proposal that has passed into the voting phase, all staked users except the proposer may do so using this command.
-
- ```
- # Submit a vote from a key 'voter' with the desired outcome of the voter
- fetchd tx gov vote --from voter
- ```
-
-The current voting turnout and tally can be queried, which displays a list of all voters and their choice:
-
- ```
- # The current voting statistics can be printed using
- fetchd query gov votes
- ```
-
-#### Example output
-
- ```
- votes:
- - option: VOTE_OPTION_YES
- proposal_id: "1"
- voter: fetch1dmehhhvul8y7slqs3zu2z3fede9kzlnyupd9rr
- - option: VOTE_OPTION_NO
- proposal_id: "1"
- voter: fetch1064endj5ne5e868asnf0encctwlga4y2jf3h28
- - option: VOTE_OPTION_YES
- proposal_id: "1"
- voter: fetch1k3ee923osju93jm03fkfmewnal39fjdbakje1x
- ```
-
-### Voting outcome
-
-Once the voting period has ended, the results are used to determine the next step of the proposal.
-The potential outcomes include:
-
- - **Majority _yes_ vote**
- - The proposal passes through and the users act according to the proposal type - e.g. A Software update proposal passes, and users begin uptake of the new version.
-
- - **Majority _no_ vote**
- - The funds deposited to pass into the voting stage are returned, and there is no governance change.
-
- - **Majority _no with veto_ vote**
- - This outcome is indicative of a proposal which may undermine the current governance system, e.g. a proposal to set the deposit threshold or voting period to an absurd value.
- - All funds deposited in the proposal are to be burned subject to this outcome, and there is no governance change.
diff --git a/pages/guides/fetch-network/ledger/cli/intro.mdx b/pages/guides/fetch-network/ledger/cli/intro.mdx
deleted file mode 100644
index 03b947862..000000000
--- a/pages/guides/fetch-network/ledger/cli/intro.mdx
+++ /dev/null
@@ -1,27 +0,0 @@
-# CLI - Introduction 🚀
-
-The Command Line Interface (CLI) client provides all the capabilities for interacting with the [Fetch ledger ↗️](/concepts/fetch-network/ledger/intro), such as creating addresses, sending transactions and the governance capabilities. Before starting with the Command Line client, you need to follow the [installation instructions ↗️](/guides/fetch-network/ledger/installation) for the Fetch Ledger.
-
-## Connecting to a network
-
-Users have the choice to either synchronize an entire blockchain by connecting a node to the network or directly link to existing publicly accessible nodes.
-
-### Connecting to fetchhub mainnet
-
-To connect to the **Fetch Mainnet** run the following configuration steps:
-
- ```bash
- fetchd config chain-id fetchhub-4
- fetchd config node https://rpc-fetchhub.fetch.ai:443
- ```
-
-### Connecting to Dorado Test Network
-
-To connect to the **Dorado Testnet** run the following configuration steps:
-
- ```bash
- fetchd config chain-id dorado-1
- fetchd config node https://rpc-dorado.fetch.ai:443
- ```
-
-Checkout the [network information ↗️](/references/ledger/active-networks) page for more detailed information on the available networks.
diff --git a/pages/guides/fetch-network/ledger/cli/keys.mdx b/pages/guides/fetch-network/ledger/cli/keys.mdx
deleted file mode 100644
index cc9e7a3ef..000000000
--- a/pages/guides/fetch-network/ledger/cli/keys.mdx
+++ /dev/null
@@ -1,132 +0,0 @@
-import { Callout } from 'nextra/components'
-
-# CLI - Managing keys 🔑
-
-Managing keys is an essential part of working with the Ledger, since all interactions are authenticated with these keys.
-
-## How to add keys
-
-If you want to **create a new local key**, you would need to run the following command:
-
- ```bash
- fetchd keys add
- ```
-
-
- These keys are stored locally on your system. By default, these keys will be stored in the OS level keychain, however, in general these keys are considered less secure than using a hardware device
-
-
-After running the above command, `fetchd` will print out a summary of the new key being produced. An output example is shown below:
-
- ```text
- - name: test
- type: local
- address: fetch142tawq2rj397mctc3jtw9dfzf03ns0ze4swat0
- pubkey: fetchpub1addwnpepqvtmze0ekffynnjx9n85g6sexzl49ze2vpgc2f52fteyyghjtvvqw682nkx
- mnemonic: ""
- threshold: 0
- pubkeys: []
- ```
-
-This will be followed by a 24-word mnemonic that can be used to re-generate the private key and address for the account.want
-
-
- Keep this safe if ever use it to control Mainnet tokens!
-
-
-## How to look up for an address
-
-A common operation that you may want to carry out is to research the address related to specified key. This can be performed quickly, by running following command:
-
- ```bash
- fetchd keys show -a
- ```
-
-The expected output should be as shown below:
-
- ```bash
- fetch142tawq2rj397mctc3jtw9dfzf03ns0ze4swat0
- ```
-
-A less common operation, but still useful, would be to look for the public key related to a specified key.
-This can be achieved with the following command:
-
- ```bash
- fetchd keys show -p
- ```
-
-The expected output should be similar to what shown below:
-
- ```bash
- fetchpub1addwnpepqvtmze0ekffynnjx9n85g6sexzl49ze2vpgc2f52fteyyghjtvvqw682nkx
- ```
-
-## How to list keys
-
-If you wish to research for more detailed information for all keys within your system, simply use the following command:
-
- ```bash
- fetchd keys list
- ```
-
-This will show all your keys information in a `yaml` format similar to the one generated when you first created the key:
-
- ```bash
- - name: test
- type: local
- address: fetch142tawq2rj397mctc3jtw9dfzf03ns0ze4swat0
- pubkey: fetchpub1addwnpepqvtmze0ekffynnjx9n85g6sexzl49ze2vpgc2f52fteyyghjtvvqw682nkx
- mnemonic: ""
- threshold: 0
- pubkeys: []
- ```
-
-## How to recover a key
-
-You can import a key from a 24-word mnemonic by running the following:
-
- ```bash
- fetchd keys add --recover
- > Enter your bip39 mnemonic
-
- ```
-
-You will be prompted to enter the **mnemonic phrase**, and it will then print the matching address and key details as when creating a new key.
-
-## Hardware wallets
-
-### Set up your hardware wallet
-
-**We recommend hardware wallets as a solution for managing private keys!**
-
-The Fetch ledger is compatible with **Ledger Nano hardware wallets**. To use your Ledger Nano, you will need to go through the following steps:
-
- 1. Set-up your wallet by creating a PIN and passphrase, which must be stored securely to enable recovery if the device is lost or damaged.
- 2. Connect your device to your PC and update the firmware to the latest version using the Ledger Live application.
- 3. Install the Cosmos application using the software manager (Manager > Cosmos > Install).
-
-### How to add a new key
-
-To use the hardware wallet address with the CLI, the user must first add it via `fetchd`. This process only records the public information about the key. You can **import the key** by first plugging in the device and enter the device pin. Once you have unlocked the device, navigate to the Cosmos app on the device and open it.
-
-Then, you can **add the key using the following command:
-
- ```bash
- fetchd keys add --ledger --index 0
- ```
-
-
- The `--ledger` flag tells the command line tool to talk to the ledger device and the `--index` flag selects which HD index should be used.
-
-
-When running this command, the Ledger device will prompt you to verify the generated address. Once you have done this. you will get an output in the following form:
-
- ```bash
- - name: hw1
- type: ledger
- address: fetch1xqqftqp8ranv2taxsx8h594xprfw3qxl7j3ra2
- pubkey: fetchpub1addwnpepq2dulyd9mly3xqnvfgdsjkqlqzsxldpdhd6cnpm67sx90zhfw2ragk9my5h
- mnemonic: ""
- threshold: 0
- pubkeys: []
- ```
diff --git a/pages/guides/fetch-network/ledger/cli/multisig-keys.mdx b/pages/guides/fetch-network/ledger/cli/multisig-keys.mdx
deleted file mode 100644
index 15168e6f1..000000000
--- a/pages/guides/fetch-network/ledger/cli/multisig-keys.mdx
+++ /dev/null
@@ -1,96 +0,0 @@
-import { Callout } from 'nextra/components'
-
-# Multisig keys 🔐
-
-This feature of `fetchd` allows users to securely control keys in a number of configurations. This involves setting a minimum number of keys required to sign a transaction out of a maximum of N keys, known as a threshold number K.
-
-## Creating a multisig key
-
-To create a multisig key, use the following syntax:
-
- ```
- # Create a simple multisig key with a threshold of 1 as default
- fetchd keys add --multisig
-
- # Creating a multisig key with a higher threshold, K
- fetchd keys add --multisig --multisig-threshold
- ```
-
-### Example instantiation of a multisig key: shared business multisig key
-
-Consider a scenario in which three account holders need to collectively authorize transactions. At least two out of the three (K=2) must sign off on each transaction:
-
- ```
- # Create the three keys owned by the separate account holders
- fetchd keys add fred
- fetchd keys add ted
- fetchd keys add ned
-
- # Create the multisig key from keys above
- fetchd keys add business_key --multisig fred,ted,ned --multisig-threshold 2
- ```
-
-Importantly, remember to retrieve the address of `business_key` for future use:
-
- ```
- fetchd keys show -a business_key
- ```
-
-## Signing and broadcasting multisig transactions
-
-Transactions must be signed and broadcasted before they can be executed.
-
-In order to sign a multi signature transaction, the transaction itself must not be immediately broadcast. Instead, the key holders must each sign until a minimum threshold K signatures are present.
-
-
- For this example, we will be performing the transaction on the [Dorado ↗️](https://explore-dorado.fetch.ai/) network and therefore will be using `atestfet` as the denomination, and a gas price of 1000000000atestfet (this should be changed depending on the actual currency and network used).
-
-
-### Example: Multisig transaction
-
- ```
- # Create a key to represent a vendor that the business must pay
- fetchd keys add vendor
-
- # Generate a transaction as an output file to be signed by
- # the keyholders, 'ted' and 'fred' in this example
- fetchd tx bank send 1000atestfet --gas 90000 --gas-prices 1000000000atestfet --generate-only > transfer.json
-
- # you'll get "account not found" error for missing funds
- # add funds to using block explorer or by eg
- curl -X POST -H 'Content-Type: application/json' -d '{"address":""}' https://faucet-dorado.fetch.ai/api/v3/claims
-
- # This transaction file (transfer.json) is then made available for
- # the first keyholder to sign, 'fred'
- fetchd tx sign transfer.json --chain-id dorado-1 --from fred --multisig > transfer_fredsigned.json
-
- # This is repeated for 'ted'
- fetchd tx sign transfer.json --chain-id dorado-1 --from ted --multisig > transfer_tedsigned.json
-
- # These two files are then collated together and used as inputs to the
- # multisign command to create a fully signed transaction
- fetchd tx multisign transfer.json business_key transfer_fredsigned.json transfer_tedsigned.json > signed_transfer.json
-
- # Now that the transaction is fully signed, it may be broadcast
- fetchd tx broadcast signed_transfer.json
-
- # Now display the result of the transaction and confirm that the vendor has
- # received payment
- fetchd query bank balances
- ```
-
-It is important to note that this method of signing transactions can apply to all types of transaction, including staking and withdrawal transactions as shown below.
-
-### Other multisig transaction examples
-
-Other examples are provided below:
-
- ```
- # In order to create a staking transaction using a multisig key
- # the same process as above can be used with the output file of this command
- fetchd tx staking delegate 10000atestfet --from --gas 200000 --gas-prices 1000000000atestfet --generate-only > stake.json
-
- # The following command can also be used to create a withdrawal transaction for the
- # rewards from staking when using a multisig key - this too must be signed as before
- fetchd tx distribution withdraw-all-rewards --from --gas 150000 --gas-prices 1000000000atestfet --generate-only > withdrawal.json
- ```
diff --git a/pages/guides/fetch-network/ledger/cli/tokens.mdx b/pages/guides/fetch-network/ledger/cli/tokens.mdx
deleted file mode 100644
index 87b759343..000000000
--- a/pages/guides/fetch-network/ledger/cli/tokens.mdx
+++ /dev/null
@@ -1,80 +0,0 @@
-# CLI - Managing tokens
-
-## How to query your balance
-
-Once `fetchd` is configured for the desired [network ↗️](/guides/fetch-network/ledger/cli/intro). The user can query their balance using the following command:
-
- ```bash
- fetchd query bank balances fetch1akvyhle79nts4rwn075t85xrwmp5ysuqynxcn4
- ```
-
-If the address exists on the network, then the user will expect to see an output in the following form:
-
- ```text
- balances:
- - amount: "8000000000000000000"
- denom: atestfet
- pagination:
- next_key: null
- total: "0"
- ```
-
-## How to send funds
-
-Before sending funds, make sure the sender address has tokens available by querying your balance as shown above. Checkout the [token faucet](/guides/fetch-network/ledger/faucet) page for more information on how to add test tokens to your address.
-
-If you wish to send funds from one address to another, then you would use the `tx send` subcommand as shown below:
-
- ```bash
- fetchd tx bank send
- ```
-
-In a more concrete example, if the user wanted to send `100atestfet` from `main` key/address to `fetch106vm9q6ezu9va7v7e0cvq0nedc54egjm692fcp`, then the following command would be needed:
-
- ```bash
- fetchd tx bank send main fetch106vm9q6ezu9va7v7e0cvq0nedc54egjm692fcp 100atestfet
- ```
-
-When you run the command, you will get a similar output and prompt. The user can check the details of the transfer and then press `y` to confirm the transfer.
-
- ```text
- {"body":{"messages":[{"@type":"/cosmos.bank.v1beta1.MsgSend","from_address":"fetch12cjntwl32dry7fxck8qlgxq6na3fk5juwjdyy3","to_address":"fetch1hph8kd54gl6qk0hy5rl08qw9gcr4vltmk3w02v","amount":[{"denom":"atestfet","amount":"100"}]}],"memo":"","timeout_height":"0","extension_options":[],"non_critical_extension_options":[]},"auth_info":{"signer_infos":[],"fee":{"amount":[],"gas_limit":"200000","payer":"","granter":""}},"signatures":[]}
-
- confirm transaction before signing and broadcasting [y/N]: y
- ```
-
-Once the transfer has been made, a summary is presented to the user.
-An example is shown below:
-
- ```text
- code: 0
- codespace: ""
- data: ""
- gas_used: "0"
- gas_wanted: "0"
- height: "0"
- info: ""
- logs: []
- raw_log: '[]'
- timestamp: ""
- tx: null
- txhash: 77C7382A0B1B9FE39257A6C16C7E3169A875CB3A87F2CE9D947D7C1335B53E76
- ```
-
-On failure, the response will have a non-zero code, as well as some logs under the `raw_log` key:
-
- ```text
- code: 4
- codespace: sdk
- data: ""
- gas_used: "0"
- gas_wanted: "0"
- height: "0"
- info: ""
- logs: []
- raw_log: 'signature verification failed; please verify account number (5815) and chain-id
- (dorado-1): unauthorized'
- timestamp: ""
- tx: null
- txhash: 23701B052B423D63EB4AC94773B5B8227B03A576692A57999E92F2554F2372D4
- ```
diff --git a/pages/guides/fetch-network/ledger/faucet.mdx b/pages/guides/fetch-network/ledger/faucet.mdx
deleted file mode 100644
index 4f96612d1..000000000
--- a/pages/guides/fetch-network/ledger/faucet.mdx
+++ /dev/null
@@ -1,87 +0,0 @@
-import { Callout } from 'nextra/components'
-
-# How to get testnet tokens via the token faucet 💰
-
-A **token faucet** is a service that provides free tokens to users for testing or development purposes on a blockchain network. It helps developers and users access a blockchain's test network with a small amount of cryptocurrency without having to purchase it. This allows them to interact with the blockchain, test applications, and simulate real-world scenarios without using actual funds. It is a valuable resource for developers who want to experiment with blockchain applications in a risk-free environment.
-
-For our [test networks ↗️](/references/ledger/active-networks#test-nets), we have a simple token faucet implemented to allow users to get started quickly. You can send the faucet an account address, and it will transfer some test tokens back to such address. Token faucets are network specific, depending on the network type they may or may not be deployed. Please check the [networks ↗️](/references/ledger/active-networks) page for specific details.
-
-The testnet token faucet itself is available from the network block explorer available within the [active networks ↗️](/references/ledger/active-networks) page. You will be asked to enter your **Fetch Account address** (`fetch...`) and you will have to wait a few blocks for the transaction to be processed, and you should see it appearing alongside with some funds on your account.
-
-Overall, you can obtain test tokens for your account in the following way:
-
- 1. Copy your account's address and paste it into the **token faucet** available within each [network ↗️](/references/ledger/active-networks) configuration. For the **Dorado testnet**, the faucet is available within the [block explorer ↗️](https://explore-dorado.fetch.ai/) homepage.
- 2. Within the block explorer homepage, press the **Get Funds** button.
- 3. Paste the address you wish to top-up in the pop-up window and then press **Add Funds**.
- 4. Then, you can return to your address page, via the person icon, and should be able to see that you have been allocated **1 TESTFET** token.
-
-
- The tokens provided by a faucet do not have any real-world market value. These tokens are specifically created for testing and development purposes within the blockchain's ecosystem. They are not intended for trading on cryptocurrency exchanges or for any commercial transactions. Therefore, while they have utility within the test network, they do not hold any value on the broader cryptocurrency market.
-
-
-# How to add funds to your wallet using faucet APIs
-
-You can also request and get testnet tokens in your wallet using the APIs, by running the following commands:
-
-## For **Eridanus** testnet:
-### Get `atestasi` tokens
-
- ```bash
- curl -X POST -H 'Content-Type: application/json' -d '{"address":""}' https://faucet-eridanus-1.fetch.ai/api/v3/claims
- ```
-
-### Get nanomobx tokens
-
- ```bash
- curl -X POST -H 'Content-Type: application/json' -d '{"address":""}' https://faucet-mobx-eridanus-1.fetch.ai/api/v3/claims
- ```
-
-### Get ulrn tokens
-
- ```bash
- curl -X POST -H 'Content-Type: application/json' -d '{"address":""}' https://faucet-lrn-eridanus-1.fetch.ai/api/v3/claims
- ```
-
-## For **Dorado** testnet:
-### Get atestfet tokens
-
- ```bash
- curl -X POST -H 'Content-Type: application/json' -d '{"address":""}' https://faucet-dorado.fetch.ai/api/v3/claims
- ```
-
-### Get nanomobx tokens
-
- ```bash
- curl -X POST -H 'Content-Type: application/json' -d '{"address":""}' https://faucet-mobx-dorado.fetch.ai/api/v3/claims
- ```
-
-### Get ulrn tokens
-
- ```bash
- curl -X POST -H 'Content-Type: application/json' -d '{"address":""}' https://faucet-lrn-dorado.fetch.ai/api/v3/claims
- ```
-
-## Sample response for fund request to faucet API
-
- ```text
- {"status":"ok","uuid":"","target":""}
- ```
-
-## Check the wallet balance
-
-If you want to check your wallet balance, you need to run the following command:
-
- ```bash
- fetchd query bank balances
- ```
-
-The output would be:
-
- ```text
- balances:
- - amount: ""
- denom: atestfet
- pagination:
- next_key: null
- total: "0"
- ```
diff --git a/pages/guides/fetch-network/ledger/governance.mdx b/pages/guides/fetch-network/ledger/governance.mdx
deleted file mode 100644
index 7d092c27a..000000000
--- a/pages/guides/fetch-network/ledger/governance.mdx
+++ /dev/null
@@ -1,119 +0,0 @@
-import { Callout } from 'nextra/components'
-
-# Governance
-
-## Introduction
-
-**Governance** is the mechanisms through which participants collectively make decisions about the rules, parameters, and policies that govern a given network. This can include things like protocol upgrades, parameter adjustments, and even more fundamental decisions about the network's direction and purpose. Changes are requested through **governance proposals* which represent formal suggestions or requests put forth by a member or participant of a network or community to make changes to that network. These proposals are typically submitted to a decentralized governance system, where participants in the network have the opportunity to review, discuss, and ultimately vote on the proposed changes.
-
-The approval process and the required majority for a proposal to pass can vary depending on the specific governance model of the network. Once a proposal is approved, the changes outlined in the proposal are typically implemented according to the network's governance mechanisms. This could involve deploying new smart contracts, updating software, or making adjustments to on-chain parameters.
-
-## How to take part in the governance mechanism
-
-If you wish to take part in governance, you will either need to be running a **full validator node** or you need to **have delegated stake to an existing validator**.
-
-For additional information, visit the [validators ↗️](/concepts/fetch-network/ledger/validators) section of our documentation, or the [delegation ↗️](/guides/fetch-network/ledger/cli/delegator#how-to-delegate-tokens) guide.
-
-## Stake delegation
-
-If you want to delegate your stake to a validator, the following CLI command should be used:
-
- ```bash
- fetchd tx staking delegate --from
- ```
-
- where the `` begins with the prefix `fetchvaloper1...` and the `` field contains the currency denomination.
-
-For instance:
-
- ```bash
- fetchd tx staking delegate fetchvaloper1cct4fhhksplu9m9wjljuthjqhjj93z0s97p3g7 1000atestfet --from agent
- ```
-
-Check out our [delegation ↗️](/guides/fetch-network/ledger/cli/delegator#how-to-delegate-tokens) guide for further information on how to delegate your tokens to a validator using the CLI.
-
-## Proposals overview
-
-There are **three types** of governance proposal:
-
- 1. **Text proposals**: these are the most basic type of proposal. They can be used to get the opinion from participants of the network on a given topic.
-
- 2. **Parameter proposals**: these proposals are used to update the value of an existing software parameter of the network.
-
- 3. **Software upgrade proposals**: these are used to propose an upgrade of the `fetchd` software, particularly in cases where the software changes might not necessary be backwards compatible or in some way present a major update to the network.
-
-## The proposal process
-
-**Any FET holder can submit a proposal**.
-
-In order for the proposal to be open for voting, it needs to come with a deposit that is greater than a parameter called _minDeposit_. The deposit need not be provided in its entirety by the submitter. If the initial proposer's deposit is not sufficient, the proposal enters the **deposit period** status. Then, any FET holder can increase the deposit by sending a _depositTx_ transaction to the network.
-
-Once the deposit reaches _minDeposit_, the proposal enters the **voting period**, which lasts 5 days. Any bonded FET holder can then cast a vote on this proposal, by choosing one of the following options for voting:
-
- * Yes.
- * No.
- * NoWithVeto.
- * Abstain.
-
-At the end of the voting period, the proposal is accepted if there are **more than 50% Yes votes** (excluding Abstain votes) and **less than 33.33% of NoWithVeto votes** (excluding Abstain votes).
-
-## Generating proposals
-
-When creating a proposal, you will create a proposal **JSON file** with all the relevant information.
-
-An example of a **text proposal** is shown below:
-
- ```json
- {
- "title": "Switch to semantic commit messages for fetchd",
- "description": "This proposal is advocating a switch to semantic commit messages. You can find the full discussion at: https://github.com/fetchai/fetchd/issues/231",
- "type": "Text",
- "deposit": "10000000000000000000atestfet"
- }
- ```
-
-
- It is always recommended that the description of a text proposal has a link to a Github issue with the full proposal text along with the discussions about it.
-
-
-After having created the JSON file, you can **generate the text proposal on chain** by running the following command:
-
- `fetchd tx gov submit-proposal --proposal proposal.json --from `
-
-## Increasing the deposit for a proposal
-
-If you want to **increase the deposit of a proposal**, you could do this by running the following command:
-
- `fetchd tx gov deposit 100atestfet --from `
-
-For instance:
-
- `fetchd tx gov deposit 2 100atestfet --from validator`
-
-If you want to get the **proposalID**, you will need to use the **txhash** obtained when the proposal was submitted and run the following command:
-
- `fetchd query tx `
-
-For additional information on how to create a governance proposal using CLI, have a look at our [dedicated guide ↗️](/guides/fetch-network/ledger/cli/governance-proposals).
-
-## Listing current proposals
-
-Current proposals can be retrieved by using the **CLI** or from the **block explorer**.
-
-If you wish to **get the list of current proposals** and their corresponding **proposal-ids**, then you need to run the following command:
-
- `fetchd query gov proposals`
-
-## Voting on a proposal
-
-If you want to **vote for a proposal**, run the following command:
-
- `fetchd tx gov vote