diff --git a/.github/spelling/known_words_corpus.txt b/.github/spelling/known_words_corpus.txt index 84251b6f8..ced3a65bd 100644 --- a/.github/spelling/known_words_corpus.txt +++ b/.github/spelling/known_words_corpus.txt @@ -656,3 +656,19 @@ GPT codegroup SenderAgent uvicorn +intfield +floatfield +onetoonefield +charfield +pk +intenum +reverserelation +datetimefield +intenumfield +manytomanyfield +visualisations +subsidised +etc +lifecycle +screenshot +docscode diff --git a/components/code.tsx b/components/code.tsx index 0c0da09ff..1107e6f9d 100644 --- a/components/code.tsx +++ b/components/code.tsx @@ -7,8 +7,8 @@ import { motion } from "framer-motion"; interface CodeOptionProps { children: ReactNode; - filename : string; - local : boolean; + filename: string; + local: boolean; } interface CodeGroupProps { @@ -16,20 +16,30 @@ interface CodeGroupProps { isOSFile?: boolean; isLocalHostedFile?: boolean; hasCopy?: boolean; + osBlocks: ReactNode; + codeBlocks: ReactNode; + dynamic?: boolean; } interface CodeBlockProps { filename: string; dataLanguage?: string; + local?: boolean; + children: React.ReactNode; + windows?: boolean; + mac?: boolean; + ubuntu?: boolean; } type CodeBoxProps = { - filename?: string; + filename?: string[]; dataLanguage?: string; hasCopyCode?: boolean; children?: React.ReactNode; isOSFile?: boolean; isLocalHostedFile?: boolean; + osBlocks: ReactNode; + codeBlocks: ReactNode; }; type CodeBlock = { @@ -267,42 +277,84 @@ const agentType = [ export const CustomPre: React.FC = ({ hasCopyCode, - children, isLocalHostedFile, isOSFile, + codeBlocks, + osBlocks, }) => { const [isCopied, setIsCopied] = useState(false); const codeRef = useRef(null); - const [selectedType, setSelectedType] = useState(agentType[0].name); + const renderCodeChild = () => { + return React.Children.map(codeBlocks, (child) => { + if (React.isValidElement(child)) { + return child; + } + return null; + }); + }; + + const child = renderCodeChild(); + const localHostdType = + child?.length === 1 && !child[0]?.props?.local + ? agentType[1].name + : agentType[0].name; + const [selectedType, setSelectedType] = useState(localHostdType); const [selectedOS, setSelectedOS] = useState("windows"); - const renderChild = () => { - return React.Children.map(children, (child) => { + const filteredAgentType = + child?.length === 2 + ? agentType + : agentType.filter((agent) => + child?.length === 1 && child[0]?.props?.local + ? agent.label === "local" + : agent.label === "hosted", + ); + + const renderCodeBlock = () => { + return React.Children.map(codeBlocks, (child) => { if (React.isValidElement(child)) { - console.log(child.props) - return matchFilename(child.props.filename) ? child : null; + if (selectedType === "Self hosted" && child?.props?.local) { + return codeBlocks && child?.props?.children; + } else if (selectedType === "Agentverse" && !child?.props?.local) { + return codeBlocks && child?.props?.children; + } } return null; }); }; - const matchFilename = (filename: string): boolean => { - const regexMap = { - self_hosted: /local/i, - agentverse: /hosted/i, - windows: /windows/i, - mac: /mac/i, - ubuntu: /ubuntu/i, - }; - - return ( - regexMap[selectedType.split(" ").join("_").toLowerCase()]?.test( - filename, - ) || regexMap[selectedOS.toLowerCase()]?.test(filename) - ); + const renderOsBlock = () => { + return React.Children.map(osBlocks, (child) => { + if (React.isValidElement(child)) { + if (selectedOS === "windows" && child?.props?.windows) { + return codeBlocks && child?.props?.children; + } else if (selectedOS === "mac" && child?.props?.mac) { + return codeBlocks && child?.props?.children; + } else if (selectedOS === "ubuntu" && child?.props?.ubuntu) { + return codeBlocks && child?.props?.children; + } + } + return null; + }); }; + useEffect(() => { + if (codeRef.current) { + const preTags = codeRef.current.querySelectorAll("pre"); + + for (const preTag of preTags) { + if (isLocalHostedFile) { + preTag.style.paddingTop = "80px"; + } else if (isOSFile) { + preTag.style.paddingTop = "45px"; + } else { + preTag.style.paddingTop = "0px"; + } + } + } + }, [isLocalHostedFile, selectedType, codeBlocks, isOSFile, selectedOS]); + const handleCopy = () => { const codeElements = codeRef.current?.querySelectorAll("code"); const codeText = [...(codeElements ?? [])] @@ -319,15 +371,23 @@ export const CustomPre: React.FC = ({ return (
-
-
+
+
{isLocalHostedFile && ( item.name)} + options={filteredAgentType.map((item) => item.name)} /> )} {isOSFile && ( @@ -374,7 +434,7 @@ export const CustomPre: React.FC = ({ style={{ overflowX: "scroll", width: "100%" }} ref={codeRef} > - {renderChild()} + {isOSFile ? renderOsBlock() : renderCodeBlock()}
@@ -382,9 +442,6 @@ export const CustomPre: React.FC = ({ ); }; -const isLocalOrHosted = (name?: string) => - name?.startsWith("local-") || name?.startsWith("hosted-"); - export const ModifiedPre = ({ children, filename, @@ -394,7 +451,6 @@ export const ModifiedPre = ({ filename?: string; hasCopyCode?: boolean; }) => { - const osMenu = ["windows", "mac", "ubuntu"]; const [isCopied, setIsCopied] = useState(false); const codeRef = useRef(null); @@ -412,66 +468,42 @@ export const ModifiedPre = ({ } }; - const shouldApplyPreNormal = Boolean(filename && isLocalOrHosted(filename)); - - if (osMenu.includes(filename || "")) { - return ( -
- - {filename?.replace(/^(local-|hosted-)/, "")} - -
{children}
-
- ); - } - return ( -
-      {isLocalOrHosted(filename) ? (
-        filename && (
-          
-            {filename.replace(/^(local-|hosted-)/, "")}
-          
-        )
-      ) : (
-        
- {filename && ( - - {filename.replace(/^(local-|hosted-)/, "")} - - )} - {hasCopyCode && ( -
- {isCopied ? ( - <> - - - - Copied - - ) : ( - - )} -
- )} -
- )} +
+      
+ {filename && {filename}} + {hasCopyCode && ( +
+ {isCopied ? ( + <> + + + + Copied + + ) : ( + // + <> + )} +
+ )} +
{children}
); @@ -482,42 +514,62 @@ export const CodeGroup: React.FC = ({ isOSFile, isLocalHostedFile, hasCopy, +}: CodeGroupProps): React.ReactElement | null => { + const codeBlocks = React.Children.toArray(children).filter( + (child): child is React.ReactElement => { + return React.isValidElement(child) && "local" in child.props; + }, + ); -}) => { - return ( -
- - {children} - -
+ const osBlocks = React.Children.toArray(children).filter( + (child): child is React.ReactElement => { + if (!React.isValidElement(child)) return false; + + const { props } = child; + return "windows" in props || "mac" in props || "ubuntu" in props; + }, ); -}; + const [firstChild] = React.Children.toArray(children); + if (React.isValidElement(firstChild)) { + const modifiedFirstChild = React.cloneElement( + firstChild as React.ReactElement, + { + isLocalHostedFile, + isOSFile, + hasCopy, + codeBlocks, + osBlocks, + }, + ); -export const CodeOption: React.FC = ({ - children, - filename, - local, + return modifiedFirstChild; + } + + return <>{children} || null; +}; +export const DocsCode: React.FC = ({ + codeBlocks, + isLocalHostedFile, + isOSFile, + hasCopy, + osBlocks, }) => { return (
- {children} - + isLocalHostedFile={isLocalHostedFile} + isOSFile={isOSFile} + hasCopyCode={hasCopy} + codeBlocks={codeBlocks} + osBlocks={osBlocks} + />
); }; - interface CodeSegment { path: string; lineStart: number; diff --git a/components/grid-view.tsx b/components/grid-view.tsx new file mode 100644 index 000000000..30669dc39 --- /dev/null +++ b/components/grid-view.tsx @@ -0,0 +1,39 @@ +import React, { useState } from "react"; +import styles from "./grid.module.css"; +import { useRouter } from "next/router"; + +export const GridView = ({ + content, +}: { + content: { + title: string; + description: string; + path: string; + }; +}) => { + const router = useRouter(); + const [hover, setHover] = useState(false); + + return ( +
{ + router.push(content.path); + }} + onMouseOver={() => { + setHover(true); + }} + onMouseLeave={() => { + setHover(false); + }} + id={content.title.toLowerCase().split(" ").join("-")} + > +

+ {content.title} +

+

+ {content.description} +

+
+ ); +}; diff --git a/components/grid.module.css b/components/grid.module.css new file mode 100644 index 000000000..bf1f3b01d --- /dev/null +++ b/components/grid.module.css @@ -0,0 +1,24 @@ +.gridBox { + padding: 16px; + border-radius: 8px; + border: 1px solid #b9c5d4; + backdrop-filter: blur(35px); + flex-direction: column; + align-items: flex-start; + width: 209px; + cursor: pointer; + color: #000d3d; +} + +.hoverGridBox { + padding: 16px; + border-radius: 8px; + border: 1px solid #b9c5d4; + backdrop-filter: blur(35px); + flex-direction: column; + align-items: flex-start; + background: #efebff; + width: 209px; + cursor: pointer; + color: #5f38fb; +} diff --git a/pages/concepts/ai-engine/ai-engine-personalities.mdx b/pages/concepts/ai-engine/ai-engine-personalities.mdx index 232373754..56dbb7bd7 100644 --- a/pages/concepts/ai-engine/ai-engine-personalities.mdx +++ b/pages/concepts/ai-engine/ai-engine-personalities.mdx @@ -25,7 +25,8 @@ The following AI Engine personality types are available for users: **Talkative V - 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** introduces significant enhancements to the AI Engine; The release includes a Workflows Beta, allowing two workflow creation methods: the first via POST requests to `/v1beta1/engine/workflows/SESSION_ID/` with payloads specifying workflow names and descriptions, where `SESSION_ID` is replaced by a session ID from DeltaV; the second allows posting workflow graphs, primarily for the Agentverse editor. To execute workflows, users append `?workflowId=YOUR-WORKFLOW-ID` to the DeltaV homepage URL. Additionally, starting workflows via API now requires POST requests to `/v1beta1/engine/chat/workflow-session/` with the workflow ID in the payload. Additionally, new **Elasticsearch-based Search APIs** were introduced for querying agents and functions, integrated directly into the Agentverse UI. A global **Agent Event Consumer** was added, processing events like agent creation, startup, and interactions to build an indexed database of agents. Furthermore, the **Function Description API** was implemented, generating detailed function descriptions based on an agent’s model and name within the function creation flow. Other technical improvements include **context validation**, **GPT-4o-mini** for enhanced recommendation accuracy within the NextGeneration personality, and **Prometheus metrics** for in-depth performance monitoring and observability of the system's health. + - Version **v0.26** introduced significant enhancements to the AI Engine; The release included a Workflows Beta, allowing two workflow creation methods: the first via POST requests to `/v1beta1/engine/workflows/SESSION_ID/` with payloads specifying workflow names and descriptions, where `SESSION_ID` is replaced by a session ID from DeltaV; the second allows posting workflow graphs, primarily for the Agentverse editor. To execute workflows, users append `?workflowId=YOUR-WORKFLOW-ID` to the DeltaV homepage URL. Additionally, starting workflows via API now requires POST requests to `/v1beta1/engine/chat/workflow-session/` with the workflow ID in the payload. Additionally, new **Elasticsearch-based Search APIs** were introduced for querying agents and functions, integrated directly into the Agentverse UI. A global **Agent Event Consumer** was added, processing events like agent creation, startup, and interactions to build an indexed database of agents. Furthermore, the **Function Description API** was implemented, generating detailed function descriptions based on an agent's model and name within the function creation flow. Other technical improvements include **context validation**, **GPT-4o-mini** for enhanced recommendation accuracy within the NextGeneration personality, and **Prometheus metrics** for in-depth performance monitoring and observability of the system's health. + - Version **v0.27** introduces further improvements to the AI Engine. The Workflow Executor v2 now incorporates the latest advancements in Large Language Models (LLMs), allowing for a more refined context builder in workflows. Additionally, the consumption of events from Agentverse has been fully completed, and now enables full support for the explore page search feature. The Search API has also been extended with improved capabilities, particularly by adding relevancy ordering to refine search results. LLM-driven improvements have been implemented allowing for enhanced descriptions of functions through an API endpoint designed for Agentverse. Similarly, function parameter descriptions have been improved using LLMs, with the updated descriptions now available via another API endpoint for Agentverse. Furthermore, the release brings Workflow API enhancements, introducing functionalities to update and delete workflows. Also, several bug fixes have been introduced to improve system performance and ensuring a smoother and more efficient user experience. ## Exploring the Feature Set of AI Engine Personalities diff --git a/pages/examples/advanced/async-loops.mdx b/pages/examples/advanced/async-loops.mdx index 42d51e5d7..1253a347a 100644 --- a/pages/examples/advanced/async-loops.mdx +++ b/pages/examples/advanced/async-loops.mdx @@ -1,3 +1,5 @@ +import { CodeGroup, DocsCode } from "../../../components/code"; + # Agent Asynchronous Loops ## Introduction @@ -15,6 +17,9 @@ In this example, we demonstrate how to use agents to communicate and exchange st #### Script 1 + + + ```py copy filename="external_loop_attach.py" import asyncio import contextlib @@ -63,11 +68,14 @@ In this example, we demonstrate how to use agents to communicate and exchange st 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 @@ -114,6 +122,8 @@ In this example, we demonstrate how to use agents to communicate and exchange st # > 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. diff --git a/pages/examples/advanced/open-dialogue-chitchat.mdx b/pages/examples/advanced/open-dialogue-chitchat.mdx index 6c3d3ea1a..ef28250ba 100644 --- a/pages/examples/advanced/open-dialogue-chitchat.mdx +++ b/pages/examples/advanced/open-dialogue-chitchat.mdx @@ -1,5 +1,5 @@ import { Callout } from 'nextra/components' -import { CodeGroup } from "../../../components/code"; +import { CodeGroup, DocsCode } from "../../../components/code"; # Open Dialogue Chit-Chat @@ -26,21 +26,25 @@ This script sets up the `ChitChatDialogue` class, This system includes nodes rep - 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="mac" + touch chitchat.py + ``` + + + ```py copy filename="windows" + echo. > chitchat.py + ``` + - ```py copy filename="ubuntu" - touch chitchat.py - ``` + + ```py copy filename="ubuntu" + touch chitchat.py + ``` + - + - Import required libraries. @@ -205,21 +209,28 @@ The contents of this script are to be shared between the agents that want to use - Run `cd ..` to go out of `Dialogues` directory and create `agent1.py` Python script - - - ```py copy filename="mac" - touch agent1.py - ``` + + + ```py copy filename="mac" + touch agent1.py + ``` + + + ```py copy filename="windows" + echo. > agent1.py + ``` + - ```py copy filename="windows" - echo. > agent1.py - ``` + + ```py copy filename="ubuntu" + touch agent1.py + ``` + - ```py copy filename="ubuntu" - touch agent1.py - ``` + - + + ```python copy filename="agent1.py" # Import required libraries @@ -335,26 +346,33 @@ The contents of this script are to be shared between the agents that want to use print(f"Agent address: {agent.address}") agent.run() ``` + + - Create Python `agent2.py` script: - - - ```py copy filename="mac" - touch agent2.py - ``` + + + ```py copy filename="mac" + touch agent2.py + ``` + + + ```py copy filename="windows" + echo. > agent2.py + ``` + - ```py copy filename="windows" - echo. > agent2.py - ``` - - ```py copy filename="ubuntu" - touch agent2.py - ``` - + + ```py copy filename="ubuntu" + touch agent2.py + ``` + - + + + ```python copy filename="agent2.py" """Chit chat dialogue example""" @@ -474,7 +492,8 @@ The contents of this script are to be shared between the agents that want to use 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. diff --git a/pages/examples/advanced/predefined-dialogue-chitchat.mdx b/pages/examples/advanced/predefined-dialogue-chitchat.mdx index 064ab4a0d..38208c604 100644 --- a/pages/examples/advanced/predefined-dialogue-chitchat.mdx +++ b/pages/examples/advanced/predefined-dialogue-chitchat.mdx @@ -1,5 +1,5 @@ import { Callout } from 'nextra/components' -import { CodeGroup } from "../../../components/code"; +import { CodeGroup, DocsCode } from "../../../components/code"; # Predefined Dialogue Chit-Chat @@ -25,21 +25,25 @@ This example illustrates an automated dialogue scenario using a hardcoded dialog - 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="mac" + touch chitchat.py + ``` + + + ```py copy filename="windows" + echo. > chitchat.py + ``` + - ```py copy filename="ubuntu" - touch chitchat.py - ``` + + ```py copy filename="ubuntu" + touch chitchat.py + ``` + - + - Import required libraries. @@ -240,6 +244,9 @@ These two agents use the `hardcoded_chitchat` dialogue system to automate the in - Navigate to your working directory and create a Python script named `agent1.py`. - Copy the following script into `agent1.py`: + + + ```python copy filename="agent1.py" # Import required libraries @@ -297,7 +304,8 @@ These two agents use the `hardcoded_chitchat` dialogue system to automate the in agent.run() # Running agent ``` - + + ### Setting up `agent2` `agent2` is configured to automatically initiate a dialogue with `agent1` using the predefined dialogue system. @@ -305,6 +313,8 @@ These two agents use the `hardcoded_chitchat` dialogue system to automate the in - Create a new Python script named `agent2.py` in the same directory. - Paste the following code into `agent2.py`: + + ```python copy filename="agent2.py" """Chit chat dialogue example""" @@ -357,11 +367,14 @@ These two agents use the `hardcoded_chitchat` dialogue system to automate the in 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`: diff --git a/pages/examples/getting-started/first-agent.mdx b/pages/examples/getting-started/first-agent.mdx index f60e46a25..d0fb50168 100644 --- a/pages/examples/getting-started/first-agent.mdx +++ b/pages/examples/getting-started/first-agent.mdx @@ -1,4 +1,4 @@ -import { CodeGroup } from "../../../components/code" +import { CodeGroup, DocsCode } from "../../../components/code" # Create your first Agent @@ -22,8 +22,8 @@ Let's get started and explore the basic concepts you need to develop your first ## The agent - - ```py copy filename="local-agent.py" + + ```py copy filename="agent.py" # Import necessary classes from the uAgents library from uagents import Agent, Context @@ -40,8 +40,10 @@ Let's get started and explore the basic concepts you need to develop your first if __name__ == "__main__": agent.run() ``` + - ```py copy filename="hosted-agent.py" + + ```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 @@ -50,10 +52,11 @@ Let's get started and explore the basic concepts you need to develop your first # Print a greeting message with the agent's name and its address print(f"Hello, I'm agent {ctx.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/intermediate/agent-and-function-api.mdx b/pages/examples/intermediate/agent-and-function-api.mdx index 83f6fb787..42a4cd77d 100644 --- a/pages/examples/intermediate/agent-and-function-api.mdx +++ b/pages/examples/intermediate/agent-and-function-api.mdx @@ -1,4 +1,4 @@ -import { CodeGroup } from "../../../components/code" +import { CodeGroup, DocsCode } from "../../../components/code" # Agents and Functions Creation using APIs @@ -29,7 +29,10 @@ This example provides details on how to create Agents and respective Agent Funct - Create a python file `agent.py` in this directory and include the following sample script in the Python file. - ```python copy filename="local-agent.py" + + ```python 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 @@ -92,8 +95,10 @@ This example provides details on how to create Agents and respective Agent Funct location_agent.run() ``` + - ```python copy filename="hosted-agent.py" + + ```python copy filename="agent.py" import requests from ai_engine import UAgentResponse, UAgentResponseType @@ -134,6 +139,7 @@ This example provides details on how to create Agents and respective Agent Funct agent.include(location_protocol) ``` + - Create a python file with name `agent_create.py`. diff --git a/pages/examples/intermediate/agents-cleaning-demo.mdx b/pages/examples/intermediate/agents-cleaning-demo.mdx index 854d7f410..1133f990b 100644 --- a/pages/examples/intermediate/agents-cleaning-demo.mdx +++ b/pages/examples/intermediate/agents-cleaning-demo.mdx @@ -1,3 +1,5 @@ +import { CodeGroup, DocsCode } from "../../../components/code" + # Cleaning service with Agents ## Introduction @@ -27,6 +29,8 @@ The protocol ensures the provider's services are available to the user's locatio Here is the full code: + + ```py copy filename="__init__.py" from datetime import datetime, timedelta from typing import List @@ -140,6 +144,8 @@ async def handle_book_request(ctx: Context, sender: str, msg: ServiceBooking): # send the response await ctx.send(sender, BookingResponse(success=success)) ``` + + #### models.py @@ -152,7 +158,8 @@ We now need to define the data structure for the cleaning service application. W * `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 @@ -192,10 +199,13 @@ class Availability(models.Model): 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 @@ -249,9 +259,13 @@ async def shutdown(_ctx: Context): if __name__ == "__main__": cleaner.run() ``` + + #### User + + ```py copy filename="user.py" from datetime import datetime, timedelta @@ -328,3 +342,5 @@ async def handle_book_response(ctx: Context, _sender: str, msg: BookingResponse) if __name__ == "__main__": user.run() ``` + + diff --git a/pages/examples/intermediate/agents-interval-task.mdx b/pages/examples/intermediate/agents-interval-task.mdx index 2d5426423..18b08ea6e 100644 --- a/pages/examples/intermediate/agents-interval-task.mdx +++ b/pages/examples/intermediate/agents-interval-task.mdx @@ -1,4 +1,4 @@ -import { CodeGroup } from "../../../components/code" +import { CodeGroup, DocsCode } from "../../../components/code" # Interval task with Agents @@ -17,8 +17,9 @@ This example shows how to use the uAgents Framework library to set up an interva ### The agent - - ```py copy filename="local-interval-task.py" + + + ```py copy filename="interval-task.py" from uagents import Agent, Context alice = Agent(name="alice", seed="alice recovery phrase") @@ -30,12 +31,14 @@ This example shows how to use the uAgents Framework library to set up an interva if __name__ == "__main__": alice.run() ``` - - ```py copy filename="hosted-interval-task.py" + + + ```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 {ctx.name}') ``` + \ No newline at end of file diff --git a/pages/examples/intermediate/agents-with-docker.mdx b/pages/examples/intermediate/agents-with-docker.mdx index abbd9de38..0f02729e0 100644 --- a/pages/examples/intermediate/agents-with-docker.mdx +++ b/pages/examples/intermediate/agents-with-docker.mdx @@ -1,3 +1,4 @@ +import { CodeGroup, DocsCode } from "../../../components/code" # Running an Agent with Docker @@ -42,6 +43,9 @@ This example shows how to run an agent using the uAgents library inside a Docker 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" @@ -114,6 +118,8 @@ bureau.add(data_receiver) if __name__ == "__main__": bureau.run() ``` + + ### `Dockerfile` diff --git a/pages/examples/intermediate/broadcast.mdx b/pages/examples/intermediate/broadcast.mdx index 40cb5c78e..942d6b98d 100644 --- a/pages/examples/intermediate/broadcast.mdx +++ b/pages/examples/intermediate/broadcast.mdx @@ -1,3 +1,5 @@ +import { CodeGroup, DocsCode } from "../../../components/code" + # Agents broadcast ## Introduction @@ -16,6 +18,10 @@ This file can be run on any platform supporting Python, with the necessary insta ### The script + + + + ```python copy filename="broadcast.py" from uagents import Agent, Bureau, Context, Model, Protocol @@ -65,7 +71,8 @@ bureau.add(charles) if __name__ == "__main__": bureau.run() ``` - + + ### Expected output ``` diff --git a/pages/examples/intermediate/coin-toss.mdx b/pages/examples/intermediate/coin-toss.mdx index 70fe3a2d5..87f216c5e 100644 --- a/pages/examples/intermediate/coin-toss.mdx +++ b/pages/examples/intermediate/coin-toss.mdx @@ -1,4 +1,4 @@ -import { CodeGroup } from "../../../components/code" +import { CodeGroup, DocsCode } from "../../../components/code" # Register a coin toss agent as a Function @@ -28,8 +28,9 @@ To enable this on [DeltaV ↗️](/concepts/ai-engine/deltav) you will need to c ### The agent - -```python copy filename="local-agent.py" + + +```python copy filename="agent.py" import random from uagents import Agent, Context, Model, Field, Protocol from uagents.setup import fund_agent_if_low @@ -81,6 +82,9 @@ coin_toss_agent.include(coin_toss_protocol, publish_manifest=True) if __name__ == "__main__": coin_toss_agent.run() ``` + + + ```python copy filename="hosted-agent.py" import random @@ -112,4 +116,5 @@ async def toss_coin(ctx: Context, sender: str, msg: CoinToss): agent.include(coin_toss_protocol, publish_manifest=True) ``` + diff --git a/pages/examples/intermediate/dice-roll.mdx b/pages/examples/intermediate/dice-roll.mdx index dc94f18d7..caa1a79c8 100644 --- a/pages/examples/intermediate/dice-roll.mdx +++ b/pages/examples/intermediate/dice-roll.mdx @@ -1,4 +1,4 @@ -import { CodeGroup } from "../../../components/code" +import { CodeGroup, DocsCode } from "../../../components/code" # Register a dice roll agent as a Function @@ -28,7 +28,8 @@ To enable this on [DeltaV ↗️](/concepts/ai-engine/deltav) you will need to c ### The agent -```py copy filename="local-agent.py" + +```py copy filename="agent.py" import random from uagents import Agent, Context, Model, Field, Protocol from uagents.setup import fund_agent_if_low @@ -73,8 +74,10 @@ dice_roll_agent.include(dice_roll_protocol, publish_manifest=True) if __name__ == "__main__": dice_roll_agent.run() ``` + -```py copy filename="hosted-agent.py" + +```py copy filename="agent.py" import random # third party modules used in this example from uagents import Field @@ -97,4 +100,5 @@ async def roll_dice(ctx: Context, sender: str, msg: DiceRoll): agent.include(dice_roll_protocol, publish_manifest=True) ``` + diff --git a/pages/examples/intermediate/hugging-face-agent.mdx b/pages/examples/intermediate/hugging-face-agent.mdx index 47df01e01..8aba1ebfc 100644 --- a/pages/examples/intermediate/hugging-face-agent.mdx +++ b/pages/examples/intermediate/hugging-face-agent.mdx @@ -1,4 +1,4 @@ -import { CodeGroup } from "../../../components/code" +import { CodeGroup, DocsCode } from "../../../components/code" # Hugging face API agent as a Function @@ -24,8 +24,9 @@ This system shows how to integrate the Hugging Face API with an Agentverse Agent #### Hugging Face System Agent + - ```python copy filename="local-agent.py" + ```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. @@ -78,7 +79,11 @@ This system shows how to integrate the Hugging Face API with an Agentverse Agent hf_agent.run() ``` - ```python copy filename="hosted-agent.py" + + + + + ```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. @@ -109,13 +114,16 @@ This system shows how to integrate the Hugging Face API with an Agentverse Agent # Include the Hugging Face protocol in your agent. agent.include(hf_protocol) ``` + #### Hugging Face Request Agent - ```python copy filename="local-agent.py" + + + ```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. @@ -184,8 +192,11 @@ This system shows how to integrate the Hugging Face API with an Agentverse Agent hf_request_agent.run() ``` + - ```python copy filename="hosted-agent.py" + + + ```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. @@ -231,12 +242,15 @@ This system shows how to integrate the Hugging Face API with an Agentverse Agent # Include the Hugging Face protocol in your agent. agent.include(hfprotocol, publish_manifest = True) ``` + #### Model List Agent - ```python copy filename="local-agent.py" + + + ```python copy filename="agent.py" # Here we demonstrate how we can create a model list agent that is compatible with DeltaV. # Importing required libraries. @@ -315,8 +329,11 @@ This system shows how to integrate the Hugging Face API with an Agentverse Agent model_list_agent.run() ``` + + + - ```python copy filename="hosted-agent.py" + ```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. @@ -376,4 +393,5 @@ This system shows how to integrate the Hugging Face API with an Agentverse Agent # 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/intermediate/langchain-rag.mdx b/pages/examples/intermediate/langchain-rag.mdx index 1f5f2fe9d..d9cbffe7e 100644 --- a/pages/examples/intermediate/langchain-rag.mdx +++ b/pages/examples/intermediate/langchain-rag.mdx @@ -1,4 +1,4 @@ -import { CodeGroup } from "../../../components/code" +import { CodeGroup, DocsCode } from "../../../components/code" # Langchain RAG Agent @@ -130,6 +130,10 @@ class RagRequest(Model): ### 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-4o-mini model. + + + + ```python copy filename="langchain_rag_agent.py" import traceback from uagents import Agent, Context, Protocol @@ -269,14 +273,16 @@ 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. - -```python copy filename="local-langchain_rag_user.py" + +```python copy filename="langchain_rag_user.py" from uagents import Agent, Context, Protocol from messages.requests import RagRequest from ai_engine import UAgentResponse @@ -321,8 +327,11 @@ if __name__ == "__main__": rag_user.run() ``` + + + -```python copy filename="hosted-langchain_rag_user.py" +```python copy filename="langchain_rag_user.py" from uagents import Agent, Context, Protocol, Field from ai_engine import UAgentResponse @@ -365,6 +374,7 @@ async def handle_data(ctx: Context, sender: str, data: UAgentResponse): agent.include(rag_user) ``` + ```python copy filename="main.py" diff --git a/pages/examples/intermediate/local-agent-langchain.mdx b/pages/examples/intermediate/local-agent-langchain.mdx index 10ce3a70b..3b3edd3ac 100644 --- a/pages/examples/intermediate/local-agent-langchain.mdx +++ b/pages/examples/intermediate/local-agent-langchain.mdx @@ -1,3 +1,5 @@ +import { CodeGroup, DocsCode } from "../../../components/code" + # Locally Hosted Agent with LangChain Integration ## Introduction @@ -22,7 +24,11 @@ This guide demonstrates how to run an agent on your own hardware or infrastructu ### The agent -```py copy filename = 'agent.py' + + + + +```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 @@ -66,7 +72,8 @@ async def load_dalle(ctx: Context, sender: str, msg: WikiReq): 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/intermediate/local-agent-registration.mdx b/pages/examples/intermediate/local-agent-registration.mdx index 05a660ff6..6de3f52bd 100644 --- a/pages/examples/intermediate/local-agent-registration.mdx +++ b/pages/examples/intermediate/local-agent-registration.mdx @@ -1,4 +1,4 @@ -import { CodeGroup } from "../../../components/code" +import { CodeGroup, DocsCode } from "../../../components/code" # Register a local agent as a Function @@ -27,7 +27,8 @@ This file can be run on any platform supporting Python, with the necessary insta ### The script -```py copy filename="local-agent.py" + +```py copy filename="agent.py" from uagents.setup import fund_agent_if_low from uagents import Agent, Context, Protocol, Model import random @@ -65,8 +66,10 @@ dungeons.include(dice_roll_protocol, publish_manifest=True) dungeons.run() ``` + -```py copy filename="hosted-agent.py" + +```py copy filename="agent.py" from uagents import Agent, Context, Protocol, Model import random from uagents import Field @@ -91,6 +94,7 @@ async def roll_dice(ctx: Context, sender: str, msg: Request): agent.include(dice_roll_protocol, publish_manifest=True) ``` + ### Register Agent Function diff --git a/pages/examples/intermediate/local-communication.mdx b/pages/examples/intermediate/local-communication.mdx index e0e283d88..2fe24ebfb 100644 --- a/pages/examples/intermediate/local-communication.mdx +++ b/pages/examples/intermediate/local-communication.mdx @@ -1,4 +1,4 @@ -import { CodeGroup } from "../../../components/code" +import { CodeGroup, DocsCode } from "../../../components/code" # Local Network Interaction @@ -18,7 +18,8 @@ This file can be run on any platform supporting Python, with the necessary insta -```py copy filename="local-agent_1.py" + +```py copy filename="agent_1.py" from uagents import Agent, Context, Model # NOTE: Run agent1.py before running agent2.py @@ -43,8 +44,10 @@ async def message_handler(ctx: Context, sender: str, msg: Message): if __name__ == "__main__": bob.run() ``` + -```py copy filename="hosted-agent_1.py" + +```py copy filename="agent_1.py" from uagents import Agent, Context, Model # NOTE: Run agent1.py before running agent2.py @@ -59,13 +62,14 @@ async def message_handler(ctx: Context, sender: str, msg: Message): # send the response await ctx.send(sender, Message(message="Hello there alice.")) ``` + ### Agent 2 - -```py copy filename="local-agent_2.py" + +```py copy filename="agent_2.py" from uagents import Agent, Context, Model class Message(Model): @@ -93,8 +97,10 @@ async def message_handler(ctx: Context, sender: str, msg: Message): if __name__ == "__main__": alice.run() ``` + -```py copy filename="hosted-agent_2.py" + +```py copy filename="agent_2.py" from uagents import Agent, Context, Model class Message(Model): @@ -112,6 +118,7 @@ async def send_message(ctx: Context): async def message_handler(ctx: Context, sender: str, msg: Message): ctx.logger.info(f"Received message from {sender}: {msg.message}") ``` + ### Expected output diff --git a/pages/examples/intermediate/mailbox-agents.mdx b/pages/examples/intermediate/mailbox-agents.mdx index a84f44919..de7e384b6 100644 --- a/pages/examples/intermediate/mailbox-agents.mdx +++ b/pages/examples/intermediate/mailbox-agents.mdx @@ -1,3 +1,5 @@ +import { CodeGroup, DocsCode } from "../../../components/code" + # Agents communication using Agentverse Mailbox feature ## Introduction @@ -17,6 +19,9 @@ A **Mailbox** allows your agent to receive messages sent to its address even whe ### Agent 1: Local Agent + + + ```py copy filename="agent_1.py" from uagents import Agent, Context, Model from uagents.setup import fund_agent_if_low @@ -52,10 +57,13 @@ A **Mailbox** allows your agent to receive messages sent to its address even whe if __name__ == "__main__": agent.run() ``` - + + ### Agent 2: Agentverse Agent + + ```py copy filename="agent_2.py" from uagents import Agent, Context, Model @@ -74,7 +82,8 @@ A **Mailbox** allows your agent to receive messages sent to its address even whe 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: diff --git a/pages/examples/intermediate/multiple-agents.mdx b/pages/examples/intermediate/multiple-agents.mdx index 7d2bb5f02..12e68f805 100644 --- a/pages/examples/intermediate/multiple-agents.mdx +++ b/pages/examples/intermediate/multiple-agents.mdx @@ -1,3 +1,5 @@ +import { CodeGroup, DocsCode } from "../../../components/code" + # Multiple agents communication ## Introduction @@ -11,7 +13,8 @@ This file can be run on any platform supporting Python, with the necessary insta - [Creating an interval task ↗️](/guides/agents/interval-task) #### The agent - + + ```py copy filename="agents.py" from uagents import Agent, Bureau, Context @@ -33,3 +36,5 @@ bureau.add(bob) if __name__ == "__main__": bureau.run() ``` + + \ No newline at end of file diff --git a/pages/examples/intermediate/name-service.mdx b/pages/examples/intermediate/name-service.mdx index 6280a67f0..4f48ef450 100644 --- a/pages/examples/intermediate/name-service.mdx +++ b/pages/examples/intermediate/name-service.mdx @@ -1,4 +1,4 @@ -import { CodeGroup } from "../../../components/code" +import { CodeGroup, DocsCode } from "../../../components/code" # Agents Name Service @@ -19,7 +19,9 @@ This file can be run on any platform supporting Python, with the necessary insta ### Agent 1 -```py copy filename="agent_1.py" + + +```py copy filename="local-agent_1.py" from cosmpy.aerial.wallet import LocalWallet from uagents.network import get_name_service_contract @@ -56,12 +58,13 @@ async def message_handler(ctx: Context, sender: str, msg: Message): if __name__ == "__main__": bob.run() ``` + ### Agent 2 - -```py copy filename="local-agent_2.py" + +```py copy filename="agent_2.py" from uagents.setup import fund_agent_if_low from uagents import Agent, Context, Model @@ -99,6 +102,7 @@ async def alice_interval_handler(ctx: Context): ctx.logger.info(f"Sending message to {bob_name}...") await ctx.send(bob_name, Message(message="Hello there bob.")) ``` + ## Expected output diff --git a/pages/examples/intermediate/news-reading-system.mdx b/pages/examples/intermediate/news-reading-system.mdx index 2a55e0b4e..0c76bb51c 100644 --- a/pages/examples/intermediate/news-reading-system.mdx +++ b/pages/examples/intermediate/news-reading-system.mdx @@ -1,4 +1,4 @@ -import { CodeGroup } from "../../../components/code" +import { CodeGroup, DocsCode } from "../../../components/code" # Using News API to build network of Primary and Secondary functions @@ -20,8 +20,9 @@ This file can be run on any platform supporting Python, with the necessary insta #### News Reading Agent + - ```python copy filename="local-agent.py" + ```python copy filename="agent.py" # Here we demonstrate how we can create a news reading system agent that is compatible with DeltaV @@ -75,8 +76,11 @@ This file can be run on any platform supporting Python, with the necessary insta news_agent.run() ``` + - ```python copy filename="hosted-agent.py" + + + ```python copy filename="agent.py" # Here we demonstrate how we can create a news reading system agent that is compatible with DeltaV @@ -109,12 +113,14 @@ This file can be run on any platform supporting Python, with the necessary insta # Include the Generate News protocol in your agent agent.include(news_protocol) ``` + #### News Generating Agent - ```python copy filename="local-agent.py" + + ```python copy filename="agent.py" # Here we demonstrate how we can create a news generating agent that is compatible with DeltaV. # Import required libraries @@ -190,8 +196,9 @@ This file can be run on any platform supporting Python, with the necessary insta generate_news_agent.run() ``` - - ```python copy filename="hosted-agent.py" + + + ```python 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. @@ -245,13 +252,14 @@ This file can be run on any platform supporting Python, with the necessary insta # Include the Generate News protocol in your agent. agent.include(generate_news_protocol) ``` + #### Generate Categorical News - - ```python copy filename="local-agent.py" + + ```python copy filename="agent.py" # Here we demonstrate how we can create a categorical news generating agent that is compatible with DeltaV. # Importing libraries @@ -331,8 +339,10 @@ This file can be run on any platform supporting Python, with the necessary insta generate_cat_news_agent.run() ``` + - ```python copy filename="hosted-agent.py" + + ```python 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. @@ -390,12 +400,14 @@ This file can be run on any platform supporting Python, with the necessary insta # Include the Generate News protocol in your agent. agent.include(generate_cat_news_protocol) ``` + #### Generate Regional News - ```python copy filename="local-agent.py" + + ```python copy filename="agent.py" # Import libraries import requests import json @@ -489,6 +501,9 @@ This file can be run on any platform supporting Python, with the necessary insta generate_news_reg_agent.run() ``` + + + ```python copy filename="hosted-agent.py" # Import libraries @@ -561,13 +576,14 @@ This file can be run on any platform supporting Python, with the necessary insta # Include the Generate Regional News protocol in your agent agent.include(generate_news_protocol) ``` + #### Generate Keyword News - - ```python copy filename="local-agent.py" + + ```python copy filename="agent.py" # Import libraries import requests from uagents import Agent, Context, Model, Field, Protocol @@ -646,8 +662,10 @@ This file can be run on any platform supporting Python, with the necessary insta generate_news_keyw_agent.run() ``` + - ```python copy filename="hosted-agent.py" + + ```python copy filename="agent.py" # Import libraries import requests import json @@ -703,4 +721,5 @@ This file can be run on any platform supporting Python, with the necessary insta # Include the Generate Keyword News protocol in your agent agent.include(generate_news_keyw_protocol) ``` + \ No newline at end of file diff --git a/pages/examples/intermediate/on-query-proxy.mdx b/pages/examples/intermediate/on-query-proxy.mdx index 3e78a1176..e33f8cc7a 100644 --- a/pages/examples/intermediate/on-query-proxy.mdx +++ b/pages/examples/intermediate/on-query-proxy.mdx @@ -1,4 +1,4 @@ -import { CodeGroup } from "../../../components/code" +import { CodeGroup, DocsCode } from "../../../components/code" # Query an agent using a proxy API @@ -18,7 +18,8 @@ This example shows how to query an agent using a proxy API. #### The agent -```py copy filename="hosted-agent.py" + +```py copy filename="agent.py" from uagents import Agent, Context, Model class TestRequest(Model): @@ -27,6 +28,13 @@ class TestRequest(Model): 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}") @@ -41,9 +49,15 @@ async def query_handler(ctx: Context, sender: str, _query: TestRequest): await ctx.send(sender, Response(text="success")) except Exception: await ctx.send(sender, Response(text="fail")) + +if __name__ == "__main__": + agent.run() ``` + + + -```py copy filename="local-agent.py" +```py copy filename="agent.py" from uagents import Agent, Context, Model class TestRequest(Model): @@ -52,13 +66,6 @@ class TestRequest(Model): 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}") @@ -73,10 +80,8 @@ async def query_handler(ctx: Context, sender: str, _query: TestRequest): await ctx.send(sender, Response(text="success")) except Exception: await ctx.send(sender, Response(text="fail")) - -if __name__ == "__main__": - agent.run() ``` + The agent is created using the `Agent` class from `uagents` library. It is initialized with a `name`, `seed`, `port`, and `endpoint`. diff --git a/pages/examples/intermediate/on-query.mdx b/pages/examples/intermediate/on-query.mdx index 0842c373e..d45e069ac 100644 --- a/pages/examples/intermediate/on-query.mdx +++ b/pages/examples/intermediate/on-query.mdx @@ -1,4 +1,5 @@ import { Callout } from 'nextra/components' +import { CodeGroup, DocsCode } from "../../../components/code" # On Query decorator example @@ -22,6 +23,8 @@ This documentation outlines the steps to set up and enable communication between 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="JobSearchAgent.py" # import required libraries import json @@ -121,7 +124,8 @@ async def query_handler(ctx: Context, sender: str, msg: Request): 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 diff --git a/pages/examples/intermediate/on_query_example.mdx b/pages/examples/intermediate/on_query_example.mdx index 01cc65569..11cce62bc 100644 --- a/pages/examples/intermediate/on_query_example.mdx +++ b/pages/examples/intermediate/on_query_example.mdx @@ -1,5 +1,5 @@ import { Callout } from 'nextra/components' -import { CodeGroup } from "../../../components/code" +import { CodeGroup, DocsCode } from "../../../components/code" ## Shopping Assistance Agent using `on_query` @@ -41,7 +41,8 @@ class ShoppingAssistResponse(Model): - **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="local-agent.py" + +```py copy filename="agent.py" from uagents import Agent, Context from uagents.setup import fund_agent_if_low from models import ShoppingAssistResponse, ShoppingRequest @@ -133,8 +134,11 @@ if __name__ == "__main__": agent.run() ``` + -```py copy filename="hosted-agent.py" + + +```py copy filename="agent.py" from uagents import Agent, Context import requests import json @@ -216,6 +220,7 @@ async def handler(ctx: Context, sender: str, msg: ShoppingRequest): 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/) . diff --git a/pages/examples/intermediate/postgres-database-with-an-agent.mdx b/pages/examples/intermediate/postgres-database-with-an-agent.mdx index e1b1dffd8..a2c5b2c32 100644 --- a/pages/examples/intermediate/postgres-database-with-an-agent.mdx +++ b/pages/examples/intermediate/postgres-database-with-an-agent.mdx @@ -1,3 +1,5 @@ +import { CodeGroup, DocsCode } from "../../../components/code" + # Utilize the PostgreSQL database with the Agent ## Introduction @@ -222,6 +224,8 @@ This script sets up and runs two agents, `db_insert_agent` and `db_fetch_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 @@ -359,7 +363,8 @@ 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. diff --git a/pages/examples/intermediate/react_example.mdx b/pages/examples/intermediate/react_example.mdx index d5f1bcf5d..c9b19f0e6 100644 --- a/pages/examples/intermediate/react_example.mdx +++ b/pages/examples/intermediate/react_example.mdx @@ -1,5 +1,5 @@ import { Callout } from 'nextra/components' -import { CodeGroup } from "../../../components/code" +import { CodeGroup, DocsCode } from "../../../components/code" # React app with agents 'on_query' decorator @@ -165,8 +165,10 @@ In this section we will setup agents and as well as flask app which will respond - **News and URL agent:** Fetches news articles titles and url for them as well. + + - ```python copy filename="local-news_agent.py" + ```python copy filename="news_agent.py" # Import Required libraries import requests import os @@ -292,8 +294,10 @@ In this section we will setup agents and as well as flask app which will respond if __name__ == "__main__": NewsAgent.run() ``` + - ```python copy filename="hosted-news_agent.py" + + ```python copy filename="news_agent.py" # Import Required libraries import requests from uagents import Agent, Context, Model @@ -402,6 +406,7 @@ In this section we will setup agents and as well as flask app which will respond # 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. @@ -409,6 +414,8 @@ In this section we will setup agents and as well as flask app which will respond - **WebScraper agent:** Scraps the webpage content for the given url. + + ```python copy filename="webscraper_agent.py" # Import Required libraries import requests @@ -488,9 +495,13 @@ In this section we will setup agents and as well as flask app which will respond 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 @@ -567,10 +578,12 @@ In this section we will setup agents and as well as flask app which will respond if __name__ == "__main__": SentimentAgent.run() ``` + + - - Get your [Hugging Face Inference API ↗️](https://huggingface.co/docs/api-inference/en/index). - + + Get your [Hugging Face Inference API ↗️](https://huggingface.co/docs/api-inference/en/index). + 3. Requirement.txt: diff --git a/pages/examples/intermediate/running-an-agent-on-agentverse.mdx b/pages/examples/intermediate/running-an-agent-on-agentverse.mdx index cbbcd8fff..0c058e998 100644 --- a/pages/examples/intermediate/running-an-agent-on-agentverse.mdx +++ b/pages/examples/intermediate/running-an-agent-on-agentverse.mdx @@ -1,3 +1,5 @@ +import { CodeGroup, DocsCode } from "../../../components/code" + # Run Agents on Agentverse ## Introduction @@ -56,6 +58,9 @@ Whenever you create a local agent, you can either run a it on the Agentverse by Let's consider the following local agent code: + + + ```py copy filename="agent.py" from uagents.setup import fund_agent_if_low from uagents import Agent, Context, Protocol, Model @@ -84,6 +89,8 @@ Let's consider the following local agent code: 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. @@ -109,6 +116,10 @@ When running the above local agent, you will see something like this in your ter Let's consider the following local agent example: + + + + ```py copy filename="agent.py" from uagents import Agent, Context, Model, Protocol @@ -135,7 +146,8 @@ Let's consider the following local agent example: 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/intermediate/local-agent-langchain). diff --git a/pages/examples/intermediate/send-tokens-agents.mdx b/pages/examples/intermediate/send-tokens-agents.mdx index 31ef62593..e853ff9ee 100644 --- a/pages/examples/intermediate/send-tokens-agents.mdx +++ b/pages/examples/intermediate/send-tokens-agents.mdx @@ -1,3 +1,5 @@ +import { CodeGroup, DocsCode } from "../../../components/code" + # Send tokens with Agents ## Introduction @@ -17,7 +19,9 @@ This example shows how to use Agents to make them send tokens to each other. ### The agent - ```py copy filename="sending_tokens.py" + + + ```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 @@ -77,6 +81,8 @@ This example shows how to use Agents to make them send tokens to each other. if __name__ == "__main__": bureau.run() ``` + + ### Expected output diff --git a/pages/examples/intermediate/sending-and-verifying-token-transactions-with-agent.mdx b/pages/examples/intermediate/sending-and-verifying-token-transactions-with-agent.mdx index 6a5d98434..e176c6cbe 100644 --- a/pages/examples/intermediate/sending-and-verifying-token-transactions-with-agent.mdx +++ b/pages/examples/intermediate/sending-and-verifying-token-transactions-with-agent.mdx @@ -1,3 +1,5 @@ +import { CodeGroup, DocsCode } from "../../../components/code" + # Sending and verifying token transactions with Agent ## Introduction @@ -82,6 +84,8 @@ This example demonstrates how to build a simple agent-based system for transferr #### 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 @@ -276,6 +280,8 @@ if __name__ == "__main__": bureau.run() ``` + + ### Poetry Dependencies diff --git a/pages/examples/intermediate/simple-agent-communication.mdx b/pages/examples/intermediate/simple-agent-communication.mdx index d64eb74e4..397f91f6b 100644 --- a/pages/examples/intermediate/simple-agent-communication.mdx +++ b/pages/examples/intermediate/simple-agent-communication.mdx @@ -1,3 +1,5 @@ +import { CodeGroup, DocsCode } from "../../../components/code" + # Agents communication ## Introduction @@ -12,7 +14,8 @@ This file can be run on any platform supporting Python, with the necessary insta - [Agents address ↗️](/guides/agents/getting-started/getting-uagent-address) #### The agent - + + ```py copy filename="agents_communication.py" from uagents import Agent, Bureau, Context, Model @@ -41,3 +44,5 @@ This file can be run on any platform supporting Python, with the necessary insta if __name__ == "__main__": bureau.run() ``` + + diff --git a/pages/examples/intermediate/storage.mdx b/pages/examples/intermediate/storage.mdx index aa1f7a1d3..3e5bc27a1 100644 --- a/pages/examples/intermediate/storage.mdx +++ b/pages/examples/intermediate/storage.mdx @@ -1,4 +1,4 @@ -import { CodeGroup } from "../../../components/code" +import { CodeGroup, DocsCode } from "../../../components/code" # Agents storage @@ -14,8 +14,8 @@ This file can be run on any platform supporting Python, with the necessary insta ### The agent - - ```py copy filename="local-storage.py" + + ```py copy filename="storage.py" from uagents import Agent, Context agent = Agent(name="bob") @@ -33,8 +33,10 @@ This file can be run on any platform supporting Python, with the necessary insta if __name__ == "__main__": agent.run() ``` + - ```py copy filename="hosted-storage.py" + + ```py copy filename="storage.py" from uagents import Agent, Context @agent.on_event("startup") @@ -47,4 +49,5 @@ This file can be run on any platform supporting Python, with the necessary insta ctx.logger.info(f"My count is: {current_count}") ctx.storage.set("count", current_count + 1) ``` + \ No newline at end of file diff --git a/pages/examples/intermediate/table-booking-demo.mdx b/pages/examples/intermediate/table-booking-demo.mdx index d5a62b991..b6616e1f9 100644 --- a/pages/examples/intermediate/table-booking-demo.mdx +++ b/pages/examples/intermediate/table-booking-demo.mdx @@ -1,4 +1,4 @@ -import { CodeGroup } from "../../../components/code" +import { CodeGroup, DocsCode } from "../../../components/code" # Table booking service with Agents @@ -22,7 +22,8 @@ This example shows how to use Agents to create a table booking service at a rest #### Query table - ```py copy filename="local-query.py" + + ```py copy filename="query.py" from typing import List from uagents import Context, Model, Protocol @@ -75,8 +76,10 @@ This example shows how to use Agents to create a table booking service at a rest total_queries = int(ctx.storage.get("total_queries") or 0) await ctx.send(sender, TotalQueries(total_queries=total_queries)) ``` + - ```py copy filename="hosted-query.py" + + ```py copy filename="query.py" from typing import List from uagents import Context, Model, Protocol @@ -129,13 +132,15 @@ This example shows how to use Agents to create a table booking service at a rest total_queries = int(ctx.storage.get("total_queries") or 0) await ctx.send(sender, TotalQueries(total_queries=total_queries)) ``` + #### Book table - ```py copy filename="local-book.py" + + ```py copy filename="book.py" from uagents import Context, Model, Protocol from .query import TableStatus @@ -171,8 +176,10 @@ This example shows how to use Agents to create a table booking service at a rest # send the response await ctx.send(sender, BookTableResponse(success=success)) ``` + - ```py copy filename="hosted-book.py" + + ```py copy filename="book.py" from uagents import Context, Model, Protocol from query import TableStatus @@ -208,6 +215,7 @@ This example shows how to use Agents to create a table booking service at a rest # send the response await ctx.send(sender, BookTableResponse(success=success)) ``` + ### The Agents @@ -215,7 +223,8 @@ This example shows how to use Agents to create a table booking service at a rest #### Restaurant - ```py copy filename="local-restaurant.py" + + ```py copy filename="restaurant.py" from uagents import Agent, Context from uagents.setup import fund_agent_if_low from protocols.book import book_proto @@ -246,8 +255,10 @@ This example shows how to use Agents to create a table booking service at a rest if __name__ == "__main__": restaurant.run() ``` + - ```py copy filename="hosted-restaurant.py" + + ```py copy filename="restaurant.py" from uagents import Agent, Context from book import book_proto from query import query_proto, TableStatus @@ -266,13 +277,15 @@ This example shows how to use Agents to create a table booking service at a rest for (number, status) in TABLES.items(): agent._storage.set(number, status.dict()) ``` + #### Customer/user - ```py copy filename="local-user.py" + + ```py copy filename="user.py" from protocols.book import BookTableRequest, BookTableResponse from protocols.query import ( QueryTableRequest, @@ -339,8 +352,10 @@ This example shows how to use Agents to create a table booking service at a rest if __name__ == "__main__": user.run() ``` + - ```py copy filename="hosted-user.py" + + ```py copy filename="user.py" from book import BookTableRequest, BookTableResponse from query import ( QueryTableRequest, @@ -394,6 +409,7 @@ This example shows how to use Agents to create a table booking service at a rest ctx.storage.set("completed", True) ``` + ### Expected output diff --git a/pages/examples/intermediate/verify-messages.mdx b/pages/examples/intermediate/verify-messages.mdx index 4fa16c1ab..57cd68cab 100644 --- a/pages/examples/intermediate/verify-messages.mdx +++ b/pages/examples/intermediate/verify-messages.mdx @@ -1,3 +1,5 @@ +import { CodeGroup, DocsCode } from "../../../components/code" + # Verify messages with Agents ## Introduction @@ -16,6 +18,8 @@ This example shows how to use Agents to make them verify authenticity of message ### The agent + + ```py copy filename="message_verification.py" import hashlib from uagents import Agent, Bureau, Context, Model @@ -76,9 +80,9 @@ This example shows how to use Agents to make them verify authenticity of message if __name__ == "__main__": bureau.run() ``` - + + ### Expected output - ``` [ bob]: Alice's message verified! [ bob]: Received message from agent1qf5gfqm48k9acegez3sg82ney2aa6l5fvpwh3n3z0ajh0nam3ssgwnn5me7: hello there bob diff --git a/pages/examples/intermediate/wallet-messaging.mdx b/pages/examples/intermediate/wallet-messaging.mdx index 5571d4e7e..8d33e6a49 100644 --- a/pages/examples/intermediate/wallet-messaging.mdx +++ b/pages/examples/intermediate/wallet-messaging.mdx @@ -1,3 +1,5 @@ +import { CodeGroup, DocsCode } from "../../../components/code" + # Communicating with other agents wallet ## Introduction @@ -86,7 +88,9 @@ In this example we will create two agents locally using `uagents` library and ma This section presents the entire script in one block, allowing users to easily copy and paste it for testing or deployment. - ```py filename=wallet_messaging.py + + + ```py filename="wallet_messaging.py" from uagents import Agent, Bureau, Context from uagents.wallet_messaging import WalletMessage @@ -116,7 +120,8 @@ This section presents the entire script in one block, allowing users to easily c bureau.add(bob) bureau.run() ``` - + + ### Script Execution - Open terminal and navigate to the folder where `wallet_messaging.py` is stored. diff --git a/pages/guides/agent-courses/agents-for-ai.mdx b/pages/guides/agent-courses/agents-for-ai.mdx index e2ed4fbc4..d4b0f8671 100644 --- a/pages/guides/agent-courses/agents-for-ai.mdx +++ b/pages/guides/agent-courses/agents-for-ai.mdx @@ -1,6 +1,6 @@ import { Callout } from 'nextra/components' import PackageVersion from 'components/package-version' -import { CodeGroup } from "../../../components/code"; +import { CodeGroup, DocsCode } from "../../../components/code"; # Agents 101 for AI Engine @@ -107,21 +107,25 @@ In this guide, our first agent takes any text and returns a sentiment of content 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="mac" + touch sentiment_agent.py + ``` + + + ```py copy filename="windows" + echo. > sentiment_agent.py + ``` + - ```py copy filename="ubuntu" - touch sentiment_agent.py - ``` + + ```py copy filename="ubuntu" + touch sentiment_agent.py + ``` + - + ```py copy filename="sentiment_agent.py" from uagents import Agent, Context, Protocol, Model @@ -323,21 +327,25 @@ Okay, take a quick break then let's create the second Agent; it's time to introd 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_summary_agent.py - ``` - - ```py copy filename="windows" - echo. > web_summary_agent.py - ``` + + + ```py copy filename="mac" + touch web_summary_agent.py + ``` + + + ```py copy filename="windows" + echo. > web_summary_agent.py + ``` + - ```py copy filename="ubuntu" - touch web_summary_agent.py - ``` + + ```py copy filename="ubuntu" + touch web_summary_agent.py + ``` + - + This Agent has the same structure as the sentiment Agent we previously defined. diff --git a/pages/guides/agent-courses/introductory-course.mdx b/pages/guides/agent-courses/introductory-course.mdx index 80572be01..b7098adaf 100644 --- a/pages/guides/agent-courses/introductory-course.mdx +++ b/pages/guides/agent-courses/introductory-course.mdx @@ -1,6 +1,6 @@ import { Callout } from 'nextra/components' import PackageVersion from 'components/package-version' -import { CodeGroup } from "../../../components/code"; +import { CodeGroup, DocsCode } from "../../../components/code"; # Agents 101 @@ -204,21 +204,25 @@ The agents registered in the Almanac provide service endpoints for remote commun 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="mac" + touch alice_agent.py + ``` + + + ```py copy filename="windows" + echo. > alice_agent.py + ``` + - ```py copy filename="ubuntu" - touch 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: @@ -337,21 +341,25 @@ We can now introduce a second agent to demonstrate how two agents can interact w 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="mac" + touch duo_agent.py + ``` + + + ```py copy filename="windows" + echo. > duo_agent.py + ``` + - ```py copy filename="ubuntu" - touch duo_agent.py - ``` + + ```py copy filename="ubuntu" + touch duo_agent.py + ``` + - + The script will look as follows: @@ -396,21 +404,25 @@ We can now show how to enable effective communication between different 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="mac" + touch agent_communication.py + ``` + + + ```py copy filename="windows" + echo. > agent_communication.py + ``` + - ```py copy filename="ubuntu" - touch agent_communication.py - ``` + + ```py copy filename="ubuntu" + touch agent_communication.py + ``` + - + We can now define the `Message` data model and our two agents: @@ -489,21 +501,25 @@ We first import modules, then initialize our agents and include a function ensur 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="mac" + touch almanac_registration.py + ``` + + + ```py copy filename="windows" + echo. > almanac_registration.py + ``` + - ```py copy filename="ubuntu" - touch almanac_registration.py - ``` + + ```py copy filename="ubuntu" + touch almanac_registration.py + ``` + - + We will have what follows: @@ -543,21 +559,25 @@ In this example, we provide scripts for two agents. To establish a line of remot 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="mac" + touch remote_alice.py + ``` + + + ```py copy filename="windows" + echo. > remote_alice.py + ``` + - ```py copy filename="ubuntu" - touch 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. @@ -595,21 +615,25 @@ The script would be as follows: 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 it: - - - ```py copy filename="mac" - touch remote_bob.py - ``` - - ```py copy filename="windows" - echo. > remote_bob.py - ``` + + + ```py copy filename="mac" + touch remote_bob.py + ``` + + + ```py copy filename="windows" + echo. > remote_bob.py + ``` + - ```py copy filename="ubuntu" - touch 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: @@ -678,21 +702,25 @@ An example is provided below. In this example we have a full script for an agent 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="mac" + touch storage.py + ``` + + + ```py copy filename="windows" + echo. > storage.py + ``` + - ```py copy filename="ubuntu" - touch storage.py - ``` + + ```py copy filename="ubuntu" + touch storage.py + ``` + - + The script for this example is: diff --git a/pages/guides/agents/advanced/agents-async-loops.mdx b/pages/guides/agents/advanced/agents-async-loops.mdx index 5df485d21..1c0250d8d 100644 --- a/pages/guides/agents/advanced/agents-async-loops.mdx +++ b/pages/guides/agents/advanced/agents-async-loops.mdx @@ -1,4 +1,4 @@ -import { CodeGroup } from "../../../../components/code"; +import { CodeGroup, DocsCode } from "../../../../components/code"; # Agent Asynchronous Loops @@ -25,21 +25,25 @@ The first script depicts how to **attach an agent to an external event loop** an 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="mac" + touch external_loop_attach.py + ``` + + + ```py copy filename="windows" + echo. > external_loop_attach.py + ``` + - ```py copy filename="ubuntu" - touch external_loop_attach.py - ``` + + ```py copy filename="ubuntu" + touch external_loop_attach.py + ``` + - + Now, paste the below code into it: @@ -110,21 +114,25 @@ The goal of the second script is to create an agent that runs tasks inside an ex 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="mac" + touch external_loop_run.py + ``` + + + ```py copy filename="windows" + echo. > external_loop_run.py + ``` + - ```py copy filename="ubuntu" - touch external_loop_run.py - ``` + + ```py copy filename="ubuntu" + touch external_loop_run.py + ``` + - + Then, let's paste the below code into it: diff --git a/pages/guides/agents/advanced/message-verification.mdx b/pages/guides/agents/advanced/message-verification.mdx index 4c0230de9..1380bd165 100644 --- a/pages/guides/agents/advanced/message-verification.mdx +++ b/pages/guides/agents/advanced/message-verification.mdx @@ -1,4 +1,4 @@ -import { CodeGroup } from "../../../../components/code"; +import { CodeGroup, DocsCode } from "../../../../components/code"; # How to use agents to verify messages @@ -27,21 +27,25 @@ Make sure you have read the following resources before going on with this guide: 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="mac" + touch message_verification.py + ``` + + + ```py copy filename="windows" + echo. > message_verification.py + ``` + - ```py copy filename="ubuntu" - touch 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`: diff --git a/pages/guides/agents/advanced/name-service.mdx b/pages/guides/agents/advanced/name-service.mdx index a5a89aa67..494a12f69 100644 --- a/pages/guides/agents/advanced/name-service.mdx +++ b/pages/guides/agents/advanced/name-service.mdx @@ -1,4 +1,4 @@ -import { CodeGroup } from "../../../../components/code"; +import { CodeGroup, DocsCode } from "../../../../components/code"; # Agents Name Service @@ -18,39 +18,47 @@ First of all, we need to create 2 Python scripts for our two agents using the fo Bob: - - - ```py copy filename="mac" - touch agent_1.py - ``` - - ```py copy filename="windows" - echo. > agent_1.py - ``` + + + ```py copy filename="mac" + touch agent_1.py + ``` + + + ```py copy filename="windows" + echo. > agent_1.py + ``` + - ```py copy filename="ubuntu" - touch agent_1.py - ``` + + ```py copy filename="ubuntu" + touch agent_1.py + ``` + - + Alice: + + + + ```py copy filename="mac" + touch agent_2.py + ``` + + + ```py copy filename="windows" + echo. > agent_2.py + ``` + - - - ```py copy filename="mac" - touch agent_2.py - ``` - - ```py copy filename="windows" - echo. > agent_2.py - ``` - - ```py copy filename="ubuntu" - touch agent_2.py - ``` + + ```py copy filename="ubuntu" + touch agent_2.py + ``` + - + ### Bob diff --git a/pages/guides/agents/advanced/register-in-almanac.mdx b/pages/guides/agents/advanced/register-in-almanac.mdx index 515e351f5..712c2edfa 100644 --- a/pages/guides/agents/advanced/register-in-almanac.mdx +++ b/pages/guides/agents/advanced/register-in-almanac.mdx @@ -1,5 +1,5 @@ import {Callout} from 'nextra/components' -import { CodeGroup } from "../../../../components/code"; +import { CodeGroup, DocsCode } from "../../../../components/code"; # Registering in Almanac Contract @@ -25,21 +25,25 @@ Make sure you have read the following resources before going on with this guide: 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="mac" + touch registration.py + ``` + + + ```py copy filename="windows" + echo. > registration.py + ``` + - ```py copy filename="ubuntu" - touch registration.py - ``` + + ```py copy filename="ubuntu" + touch registration.py + ``` + - + 2. Then, import the `Agent` class from the `uagents` library to create our agent, and the `fund_agent_if_low` class from the `uagents.setup` module. This function will check if you have enough tokens to register in the Almanac contract, if not it will add testnet tokens to your `Fetch 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: diff --git a/pages/guides/agents/getting-started/create-a-uagent.mdx b/pages/guides/agents/getting-started/create-a-uagent.mdx index eeb7ae7da..20d213616 100644 --- a/pages/guides/agents/getting-started/create-a-uagent.mdx +++ b/pages/guides/agents/getting-started/create-a-uagent.mdx @@ -1,4 +1,5 @@ import { CodeGroup } from "../../../../components/code"; +import { DocsCode } from "../../../../components/code"; # Creating your first agent @@ -25,28 +26,32 @@ Make sure you have read the following resources before going on with this guide: 1. Let's create a Python script for this task, and name it by running: - - + + ```py copy filename="mac" touch agent.py ``` + + ```py copy filename="windows" echo. > agent.py ``` + + ```py copy filename="ubuntu" touch 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 - from uagents import Agent, Context - agent = Agent(name="alice", seed="secret_seed_phrase") - ``` +```py copy +from uagents import Agent, Context +agent = Agent(name="alice", seed="secret_seed_phrase") +``` 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. diff --git a/pages/guides/agents/getting-started/getting-uagent-address.mdx b/pages/guides/agents/getting-started/getting-uagent-address.mdx index bb0066e4d..6df3a27a6 100644 --- a/pages/guides/agents/getting-started/getting-uagent-address.mdx +++ b/pages/guides/agents/getting-started/getting-uagent-address.mdx @@ -1,4 +1,4 @@ -import { CodeGroup } from "../../../../components/code"; +import { CodeGroup, DocsCode } from "../../../../components/code"; # Agents address @@ -33,21 +33,26 @@ 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="mac" + touch uagent-address.py + ``` + - ```py copy filename="ubuntu" - 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: @@ -77,21 +82,25 @@ You can print the `Fetch network address` related to your agent in the following 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="mac" +touch fetch-address.py +``` + - ```py copy filename="ubuntu" - 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 `Fetch Network address`: @@ -129,21 +138,25 @@ In this guide, we aim at showing how to create an agent being able to say hello 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="mac" +touch my_agent.py +``` + - ```py copy filename="ubuntu" - 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: diff --git a/pages/guides/agents/intermediate/_meta.json b/pages/guides/agents/intermediate/_meta.json index b021959f1..b1beeed9d 100644 --- a/pages/guides/agents/intermediate/_meta.json +++ b/pages/guides/agents/intermediate/_meta.json @@ -24,6 +24,11 @@ "tags": ["Intermediate", "Python", "Use Cases"], "timestamp": true }, + "agent-types": { + "title": "Hosted, Local, and Mailbox Agents", + "tags": ["Intermediate", "Python", "Agents"], + "timestamp": true + }, "mailbox": { "title": "Agents Mailboxes", "tags": ["Intermediate", "Python", "Communication", "Mailbox"], diff --git a/pages/guides/agents/intermediate/agent-functions.mdx b/pages/guides/agents/intermediate/agent-functions.mdx index e4e045ab9..d8669912f 100644 --- a/pages/guides/agents/intermediate/agent-functions.mdx +++ b/pages/guides/agents/intermediate/agent-functions.mdx @@ -133,13 +133,13 @@ The **Description** is super important to the success of your Agent Function. Th 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 +## Objective Service and Sub-Service -**Primary** and **Secondary** functions are different but have strong similarities. +**Objective Service** and **Sub-Service** functions are different but have strong similarities. -A **Primary Function** 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_. +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 services 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. +Similarly, a **Sub-Service** function is an Agent Sub-function 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_. 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). diff --git a/pages/guides/agents/intermediate/agent-types.mdx b/pages/guides/agents/intermediate/agent-types.mdx new file mode 100644 index 000000000..45762de5c --- /dev/null +++ b/pages/guides/agents/intermediate/agent-types.mdx @@ -0,0 +1,74 @@ +# Hosted, Local, and Mailbox Agents + +Agents can operate in multiple environments based on how they are created and deployed within the network. Understanding the difference between **Hosted**, **Local**, and **Mailbox Agents** is helpful for developers to correctly choose the right setup for their use cases and applications. + +## Hosted Agents + +[Hosted Agents ↗️](/guides/agentverse/creating-agentverse-agents/creating-a-hosted-agent) are cloud-based agents managed within the [Agentverse ↗️](https://agentverse.ai/). This allows developers to build, deploy, and run Agents without worrying about infrastructure management. The Agentverse ensures that your agents run as functions, executing routines and handling messages straightforwardly in response to specific triggers. This design keeps the operational costs of hosted agents low, which is passed on to the users. + +Agentverse provides a variety of tools to make agent development easy. First of all, the Agent Editor which allows you to write, edit, and manage your agents directly in the Agentverse environment. It includes essential features such as the Agent Logs, where you can view real-time outputs of your agent's execution, helping you monitor and debug your agents on the fly. The platform also offers storage and secrets management, enabling you to securely manage data and information. One important feature of hosted agents is _how they manage their state_. Since hosted agents do not run continuously, any global variable you define will always revert to its initialized value after each function call. For example, if you try to increment a global counter, its value will reset to the starting value every time the function is invoked. To persist data between calls, you must use the Agent Storage; this ensures key values are maintained across function executions. This is crucial for developing agents that require stateful behavior over time. . + +When creating hosted agents, you can either start from a blank script or use one of the many predefined templates available. These templates cover a range of use cases, such as smart services or AI/ML integrations, allowing developers to quickly get started with agents designed to toss a coin, retrieve stock prices, or find nearby restaurants. The template system simplifies agent creation by providing a foundation, while also allowing for customization to meet specific requirements following the idea users have in mind. + +A key advantage of hosted agents is that they do not require local dependencies, making development more accessible. The system provides an integrated `agent.py` file, and although hosted agents can be created based on a restricted set of imports, they still offer significant flexibility for developers to create complex solutions. + +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 instead run directly on your machine or infrastructure; this gives you full control over environment, configuration, and execution. Unlike Agentverse hosted agents, local agents can continuously run processes that handle events, messages, and tasks in real-time without relying on an orchestrator. This setup allows for enhanced flexibility and dynamic behavior, as agents can manage their state across function calls without needing to store data externally. This feature makes them ideal for use cases where real-time processing and direct access to local resources are critical. + +When developing local agents, you can leverage the entire uAgents Framework, which offers a wide range of tools to support agent-based development. Also, since local agents do not face the same constraints as hosted agents, you are free to use any Python package or custom module that fits your project; this increases flexibility in design, and enables the use of powerful libraries for machine learning, data processing, and external integrations that may not be supported on Agentverse. + +A key benefit of local agents is their ability to maintain persistent state without external storage. Since they run continuously, global variables and internal states are maintained across multiple function executions. For instance, if you have a counter that increments every time a message is received, it will correctly retain its value throughout the agent's lifecycle. This contrasts with hosted agents, where global variables are re-initialized with each call and require storage to persist data. + +Running a local agent involves setting up a Python environment on your machine, installing the necessary dependencies, and executing the agent script. Agents can run indefinitely, waiting for incoming messages or scheduled tasks, which makes them well-suited for applications that require constant monitoring, immediate response handling, or interactions with other agents in real-time. + +A local agent can also be run within a Docker container, making it easier to deploy agents in a production environment or across distributed systems. This is particularly useful when building functions that need to scale across multiple systems or require isolation from other processes. + +Local agents allow for deeper customization and optimization features; you can manage resource allocation, tune performance settings, and integrate directly with other services running on the same machine. This makes local agents the preferred choice for high-performance applications or scenarios where you need to closely manage system resources and agent behavior. + +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 Agents. 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. It may also be that you need to create an Agent application using imports and tools that are currently not available in the Agentverse, and thus you need to design agents locally to guarantee fully operative and runnable application. 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 a local agent. The agent's address is used to register it on the Agentverse, and then to generate a **Mailbox API key** for your agent. For instance, consider the following basic agent: + + ```py copy filename="agent_1.py" + from uagents import Agent, Context, Model + + class Message(Model): + message: str + + AGENT_MAILBOX_KEY = "put_your_AGENT_MAILBOX_KEY_here" + SEED_PHRASE = "put_your_seed_phrase_here" + + agent = Agent( + name="alice", + seed=SEED_PHRASE, + mailbox=f"{AGENT_MAILBOX_KEY}@https://agentverse.ai", + ) + + # Copy the address shown below and paste it in Agentverse + print(f"Your agent's address is: {agent.address}") + + if __name__ == "__main__": + agent.run() + ``` + +Then, head over to the [Agentverse ↗️](https://agentverse.ai/) and navigate to the **My Agents** tab. Here, select **Local Agents** and click on **Connect Local Agent**. Paste your agent's address retrieved from running your local agent and follow the steps until you get a **Mailbox API Key**, which you will use to update your agent's configuration above. 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). diff --git a/pages/guides/agents/intermediate/communicating-with-other-agents.mdx b/pages/guides/agents/intermediate/communicating-with-other-agents.mdx index 4f0adf3c8..3aca8ce03 100644 --- a/pages/guides/agents/intermediate/communicating-with-other-agents.mdx +++ b/pages/guides/agents/intermediate/communicating-with-other-agents.mdx @@ -1,5 +1,5 @@ import {Callout} from 'nextra/components' -import { CodeGroup } from "../../../../components/code"; +import { CodeGroup, DocsCode } from "../../../../components/code"; # Communicating with other agents @@ -40,21 +40,25 @@ The first step to better understand how agents communicate is to introduce how 2 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="mac" +touch agents_communication.py +``` + - ```py copy filename="ubuntu" - 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`: @@ -185,39 +189,47 @@ The first step would be to create two different Python scripts for this task, ea Slaanesh: - - - ```py copy filename="mac" - touch remote_agents_slaanesh.py - ``` - - ```py copy filename="windows" - echo. > remote_agents_slaanesh.py - ``` + + +```py copy filename="mac" +touch remote_agents_slaanesh.py +``` + - ```py copy filename="ubuntu" - 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="mac" +touch remote_agents_sigmar.py +``` + - ```py copy filename="ubuntu" - 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 diff --git a/pages/guides/agents/intermediate/handlers.mdx b/pages/guides/agents/intermediate/handlers.mdx index 50e853175..e249c2d3c 100644 --- a/pages/guides/agents/intermediate/handlers.mdx +++ b/pages/guides/agents/intermediate/handlers.mdx @@ -1,5 +1,5 @@ import { Callout } from 'nextra/components' -import { CodeGroup } from "../../../../components/code"; +import { CodeGroup, DocsCode } from "../../../../components/code"; # Agent Handlers @@ -38,21 +38,25 @@ Make sure you have read the following resources before going on with this guide: 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="mac" +touch interval-task.py +``` + - ```py copy filename="ubuntu" - 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: @@ -128,21 +132,25 @@ We now showcase a scenario where three agents, named `alice`, `bob`, and `charle 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="mac" +touch broadcast.py +``` + - ```py copy filename="ubuntu" - 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, and the `fund_agent_if_low` from `uagents.setup`. 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. Additionally, if an agent's wallet balance is low, the `fund_agent_if_low()` function is called to add funds to their wallet: @@ -356,21 +364,25 @@ 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="mac" +touch on_query.py +``` + - ```py copy filename="ubuntu" - 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`: diff --git a/pages/guides/agents/intermediate/langchain-rag-agent.mdx b/pages/guides/agents/intermediate/langchain-rag-agent.mdx index 066eef7e0..b17e4dc20 100644 --- a/pages/guides/agents/intermediate/langchain-rag-agent.mdx +++ b/pages/guides/agents/intermediate/langchain-rag-agent.mdx @@ -1,6 +1,6 @@ import {Callout} from 'nextra/components' import PackageVersion from 'components/package-version' -import { CodeGroup } from "../../../../components/code"; +import { CodeGroup, DocsCode } from "../../../../components/code"; # Build a LangChain RAG Agent @@ -121,21 +121,25 @@ You'll need several Python packages for the project. These can be managed effici 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="mac" - touch requests.py - ``` - - ```py copy filename="windows" - echo. > requests.py - ``` - - ```py copy filename="ubuntu" - touch requests.py - ``` + + ```py copy filename="windows" + echo. > requests.py + ``` + - + + ```py copy filename="ubuntu" + touch requests.py + ``` + + Here, the `RagRequest` message data model represents the request to retrieve an answer to an user's question from a specified document URL. The script includes an optional parameter, `deep_read`, to determine if nested pages should also be read to retrieve the answer. This parameter is set to `no` as `default`. @@ -170,21 +174,25 @@ The script look like the following: This step involves setting up the **LangChain Retrieval-Augmented Generation (RAG) Agent** which is able to scrape web content, retrieve relevant documents, and generate answers to user queries based on that content. Let's create the file within the `agents` directory we created 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="mac" - touch langchain_rag_agent.py - ``` - - ```py copy filename="windows" - echo. > langchain_rag_agent.py - ``` - - ```py copy filename="ubuntu" - 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 ↗️](https://fetch.ai/docs/guides/agents/intermediate/options-for-running-local-agents#run-a-local-agent-using-a-mailbox) and it is able to answer questions by fetching and summarizing information from a given website URL. @@ -352,21 +360,25 @@ We are now ready to define the **LangChain User Agent** which interacts with the Create a file for this agent: - + + +```py copy filename="mac" +touch langchain_rag_user.py +``` + - ```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 - ``` + + ```py copy filename="windows" + echo. > langchain_rag_user.py + ``` + - + + ```py copy filename="ubuntu" + touch langchain_rag_user.py + ``` + + The script looks as follows: @@ -432,21 +444,25 @@ Finally, the LangChain RAG user protocol is then included using the `.include()` We are now ready to define the main script for our project. In the `src` folder of our project we create a Python script named `main.py` using the following command: - + + +```py copy filename="mac" +touch main.py +``` + - ```py copy filename="mac" - touch main.py - ``` - - ```py copy filename="windows" - echo. > main.py - ``` - - ```py copy filename="ubuntu" - touch main.py - ``` + + ```py copy filename="windows" + echo. > main.py + ``` + - + + ```py copy filename="ubuntu" + touch main.py + ``` + + We then define the code within this one which looks like the one provided here below: diff --git a/pages/guides/agents/intermediate/public-private-agents.mdx b/pages/guides/agents/intermediate/public-private-agents.mdx index 6f11ed7d7..34642a651 100644 --- a/pages/guides/agents/intermediate/public-private-agents.mdx +++ b/pages/guides/agents/intermediate/public-private-agents.mdx @@ -10,28 +10,35 @@ Transparency is a fundamental principle in decentralized finance (DeFi) and bloc This allows users to provide greater flexibility to Agents, creating a balance between transparency and privacy for every operation they perform on the network. -For example, let's say a logistics company develops a public AI agent specialized in freight transport. By registering this agent as public, the manifest and associated logs become available on the Agentverse platform. Consequently, other users and companies can access its endpoint and understand its communication methods, enabling direct interaction. This visibility can be beneficial for collaboration, as it allows external agents to initiate communication and collaborate on logistical tasks. +## Defining public and private agents -In contrast, a financial institution developing an AI agent for secure transactions might choose to keep it private. By classifying the agent as private during development, the details of the protocol are not exposed to the outside world, ensuring a higher level of confidentiality. This private agent can still be found via the almanac, but the details of the protocol remain hidden. Only agents who are explicitly aware of the protocol can communicate with it, ensuring a more controlled and secure communication environment. -## 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: -![](src/images/concepts/ai-agents/privacy_spectrum.png) + ```python -In this context, users may not be willing to share information but want to keep it private for some reason. This is possible thanks to the ability to distinguish between **public** and **private** actors. + agent = Agent( + name="demo agent", + seed=SEED, + endpoint=["http://127.0.0.1:8000/submit"], + ) + agent.include(new_protocol, publish_manifest=True) + agent.run() -There are two ways in which an agent can be classified as **public**: + ``` - 1. By default, _at registration_ in the agentverse, when the protocol's manifest and associated digests are published, making the agent's [endpoint ↗️](/references/contracts/uagents-almanac/endpoints) available to any other user for communication. This provides users with a way to access our registered agent's information and understand how to communicate with it. +Private agents can be private in two ways, by hiding a protocol they use from public, and or not defining an endpoint: - 2. By default, _during agent development_, the agent's specific protocol is set to accept introspection requests from any other external agent. This feature of the agent protocol can be turned on and off, but is _on_ by default so that introspection requests can be answered by it. +```python -In particular, public and private agents are demarcated by whether the specification of an agent protocol is made private or public. Indeed, **private** agents maintain a degree of privacy by not disclosing their protocol manifest to the outside world. Although they are private, these agents can still be found via the almanac. However, the details of the actual protocol remain hidden, even though the digests of the associated protocols are still visible, ensuring that only agents who know the protocol itself can communicate with it. + agent = Agent( + name="private demo agent", + seed=SEED, + ) + agent.include(new_protocol, publish_manifest=False) + agent.run() - - By default, all agents are public and contactable by everyone but you need to know how to talk to them otherwise they will not answer back to you! + ``` - Check out [The Almanac ↗️](/concepts/fetch-network/almanac) resource to understand the role of protocols and the Almanac contract in creating private and public agents. - +You would need to share the ip of the private agent you're running to other agent you're communicating with. -The distinction between public and private agents is valuable for users, developers and companies within the Fetch.ai ecosystem, as it allows for a flexible approach to data protection while enabling agents to interact efficiently. It is also consistent with the general principles of decentralization and trustless interactions that underpin blockchain and decentralized system technologies. diff --git a/pages/guides/agents/intermediate/send-tokens.mdx b/pages/guides/agents/intermediate/send-tokens.mdx index cd689ad38..a03a30b66 100644 --- a/pages/guides/agents/intermediate/send-tokens.mdx +++ b/pages/guides/agents/intermediate/send-tokens.mdx @@ -1,5 +1,5 @@ import { Callout } from 'nextra/components' -import { CodeGroup } from "../../../../components/code"; +import { CodeGroup, DocsCode } from "../../../../components/code"; # How to use agents to send tokens @@ -28,21 +28,25 @@ Make sure you have read the following resources before going on with this guide: 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="mac" +touch sending_tokens.py +``` + - ```py copy filename="ubuntu" - 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: diff --git a/pages/guides/agents/intermediate/storage-function.mdx b/pages/guides/agents/intermediate/storage-function.mdx index f7aff7018..c90ad084d 100644 --- a/pages/guides/agents/intermediate/storage-function.mdx +++ b/pages/guides/agents/intermediate/storage-function.mdx @@ -1,4 +1,4 @@ -import { CodeGroup } from "../../../../components/code"; +import { CodeGroup, DocsCode } from "../../../../components/code"; # Using agents storage function @@ -21,21 +21,25 @@ Make sure you have read the following resources before going on with this guide: 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="mac" - touch storage.py - ``` - - ```py copy filename="windows" - echo. > storage.py - ``` - - ```py copy filename="ubuntu" - 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. diff --git a/pages/guides/agents/quickstart.mdx b/pages/guides/agents/quickstart.mdx index 86a0b16c6..68fc66618 100644 --- a/pages/guides/agents/quickstart.mdx +++ b/pages/guides/agents/quickstart.mdx @@ -1,6 +1,4 @@ -import {CodeGroup, CodeSegment} from "../../../components/code"; - import { GithubCodeSegment } from "../../../components/code"; - +import {CodeGroup, CodeSegment, DocsCode, GithubCodeSegment} from "../../../components/code"; # Quick Start Guide for uAgents Framework @@ -62,22 +60,25 @@ We should create something simple to get started, below the most basic of agents Create a new Python script: - - - ```py copy filename="mac" - touch interval_task.py - ``` - - ```py copy filename="windows" - echo. > interval_task.py - ``` - - ```py copy filename="ubuntu" - touch interval_task.py - ``` + + + ```py copy filename="mac" + touch interval_task.py + ``` + + + ```py copy filename="windows" + echo. > interval_task.py + ``` + - + + ```py copy filename="ubuntu" + touch interval_task.py + ``` + + Open `interval_task.py` in your text editor and add the following code: @@ -99,68 +100,41 @@ Open `interval_task.py` in your text editor and add the following code: + ```py copy filename="main.py" - from uagents import Agent, Context - - agent = Agent(name="alice") - - - @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}.") - - -``` - - ```py copy filename="main.py" - - from uagents import Agent, Context - - agent = Agent(name="alice") - - - @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}.") - +from uagents import Agent, Context -``` - +agent = Agent(name="alice") +@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}.") - - +``` + + ```py copy filename="main.py" - from uagents import Agent, Context - agent = Agent(name="alice") +from uagents import Agent, Context +agent = Agent(name="alice") - @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}.") - ``` - - ```py copy filename="main.py" - from uagents import Agent, Context +@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 = Agent(name="alice") +``` + - @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}.") - ``` - - Be sure to update `seed` with a unique phrase, your seed will need to be wrapped in `"`. #### Run Script @@ -186,71 +160,80 @@ This guide will walk you through creating a simple interaction between two agent Create 2 new Python scripts: - - - ```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 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="mac" + touch ReceiverAgent.py + ``` + + + ```py copy filename="windows" + echo. > ReceiverAgent.py + ``` + - ```py copy filename="ubuntu" - touch ReceiverAgent.py - ``` + + ```py copy filename="ubuntu" + touch ReceiverAgent.py + ``` + - + Open `SenderAgent.py` in your text editor and add the following code: ```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() ``` @@ -259,31 +242,31 @@ Then, open `ReceiverAgent.py` in your text editor and add the following code int ```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() ``` @@ -326,7 +309,7 @@ Run the scripts to see the agents communicating: 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 Fetch Network! if you're keen to skip the more code focused guides, your best next steps would be [Communicating with agents](intermediate/communicating-with-other-agents). diff --git a/pages/guides/agentverse/agentverse-functions/field-descriptions-for-deltav.mdx b/pages/guides/agentverse/agentverse-functions/field-descriptions-for-deltav.mdx index 7dc12100e..28ccd9bea 100644 --- a/pages/guides/agentverse/agentverse-functions/field-descriptions-for-deltav.mdx +++ b/pages/guides/agentverse/agentverse-functions/field-descriptions-for-deltav.mdx @@ -12,11 +12,29 @@ For clarity, reinforcing key concepts could be done through repetition of keywor Consider the following Agent Function: -![](src/images/guides/services/the-importance-of-descriptions/description_1.png) +![](src/images/guides/agentverse/registering-agent-coin-toss/new-service-dialog.png) -Providing a detailed field description for the `num_rolls` data `Model` is important to correctly execute the Function. A well written field description enhances the LLM understanding of the type of Function the user objective requires to be executed. This would help in the accurate interpretation and execution of users' requests. +Providing a detailed field description for the `num_rolls` 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 Secondary Functions from Primary or Secondary ones by specifying this within the field description itself**. For Primary and Secondary Functions network, please refer to the below examples. +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 Objective Services and Sub-Services, 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: + +![](src/images/guides/agentverse/autodescriptions_initial.png) + +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. At the moment, this functionality is available just for the **Function Description**, but it will be available for **Fields** description at a later stage. + +Check out the following screenshot to have a better idea: + +![](src/images/guides/agentverse/autodescriptions.png) + +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 @@ -30,7 +48,7 @@ This Function helps user to read news of a specific type. This Function calls a ![](src/images/guides/services/the-importance-of-descriptions/description_2.png) -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 generate 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**. +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 @@ -38,7 +56,7 @@ This Function helps task to generate news and send it to task or another Seconda ![](src/images/guides/services/the-importance-of-descriptions/description_3.png) -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 want 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**. +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. @@ -65,7 +83,7 @@ The field description for the `response` describes the response to be provided t 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 to the model. Always ask this to user after model_id is given by model list secondary function. +**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. @@ -103,14 +121,15 @@ Ideal field descriptions for this example will be like: **location:** This describes the coordinates of the city given in str(lat,long) format. -![](src/images/guides/services/service-guide/business_finder_2.png) + ![](src/images/guides/services/service-guide/business_finder_2.png) 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. + **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. -![](src/images/guides/services/service-guide/business_finder_3.png) + ![](src/images/guides/services/service-guide/business_finder_3.png) ## Agent Function registration examples diff --git a/pages/guides/agentverse/agentverse-functions/registering-agent-services.mdx b/pages/guides/agentverse/agentverse-functions/registering-agent-services.mdx index 25dedf596..a22f639a1 100644 --- a/pages/guides/agentverse/agentverse-functions/registering-agent-services.mdx +++ b/pages/guides/agentverse/agentverse-functions/registering-agent-services.mdx @@ -101,7 +101,7 @@ 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**: Primary or Secondary Function. For a detailed definition, check [here ↗️](/guides/services/services#primary-and-secondary-functions) + - **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`. diff --git a/pages/guides/agentverse/creating-agentverse-agents/allowed-imports.mdx b/pages/guides/agentverse/creating-agentverse-agents/allowed-imports.mdx index ce2f450ad..9e57146e1 100644 --- a/pages/guides/agentverse/creating-agentverse-agents/allowed-imports.mdx +++ b/pages/guides/agentverse/creating-agentverse-agents/allowed-imports.mdx @@ -44,40 +44,6 @@ In the [Agentverse ↗️](https://agentverse.ai/) code editor, you have the fre - [`re` ↗️](/guides/agentverse/allowed-imports#re). - - [`bs64` ↗️](/guides/agentverse/allowed-imports#bs64). - - - [`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). - ## Allowed imports #### uagents @@ -512,417 +478,6 @@ This package is used for generating random numbers, managing random selections, print("Pattern not found.") ``` -#### 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 - - ``` -## 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) - ``` - Explore the [Agentverse guides ↗️](/guides#agentverse) and [Agentverse concepts ↗️](/concepts#agentverse) for additional guides and documentation resources! -For additional information on services, head over to [Agentverse Services ↗️](/guides/services/services). +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). 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 index 2941820a5..530787b27 100644 --- a/pages/guides/agentverse/creating-agentverse-agents/simple-dice-roll-agent.mdx +++ b/pages/guides/agentverse/creating-agentverse-agents/simple-dice-roll-agent.mdx @@ -1,4 +1,4 @@ -# Creating a simple dice roll agent on agentverse +# Creating a simple dice roll agent on Agentverse ## Introduction @@ -15,7 +15,7 @@ Make sure you have read the following resources before going on with this guide: - [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) + - [Agents running on Agentverse ↗️](/guides/agents/intermediate/hosted-agent) ## Create your dice roll agent! @@ -68,4 +68,4 @@ 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). + - [Agentverse Functions: register a coin toss agent as a Function ↗️](/guides/agentverse/agentverse-functions/registering-agent-coin-toss). diff --git a/pages/guides/apis/agent-function-creation-apis.mdx b/pages/guides/apis/agent-function-creation-apis.mdx index c9f465111..de4cd4ecd 100644 --- a/pages/guides/apis/agent-function-creation-apis.mdx +++ b/pages/guides/apis/agent-function-creation-apis.mdx @@ -1,4 +1,4 @@ -import { CodeGroup } from "../../../components/code"; +import { CodeGroup, DocsCode } from "../../../components/code"; # Agents and Functions Creation using APIs @@ -24,37 +24,46 @@ This guide shows how to create **Agents** and **Agent Functions** in Agentverse 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.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="mac" +touch agent_create.py +``` + - ```py copy filename="ubuntu" - 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: diff --git a/pages/guides/apis/secret-management-apis.mdx b/pages/guides/apis/secret-management-apis.mdx index cadfe06f2..2bf983d22 100644 --- a/pages/guides/apis/secret-management-apis.mdx +++ b/pages/guides/apis/secret-management-apis.mdx @@ -1,5 +1,5 @@ import { Callout } from 'nextra/components' -import { CodeGroup } from "../../../components/code"; +import { CodeGroup, DocsCode } from "../../../components/code"; # Adding Secret to Agents using Agentverse APIs @@ -26,21 +26,25 @@ This guide provides details on how to use the [Agentverse hosting APIs ↗️](/ 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="mac" +touch agent-secret.py +``` + - ```py copy filename="ubuntu" - 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: diff --git a/pages/guides/fetch-network/cosmpy/use-cases/liquidity-pool.mdx b/pages/guides/fetch-network/cosmpy/use-cases/liquidity-pool.mdx index 57f367639..51dca923d 100644 --- a/pages/guides/fetch-network/cosmpy/use-cases/liquidity-pool.mdx +++ b/pages/guides/fetch-network/cosmpy/use-cases/liquidity-pool.mdx @@ -1,4 +1,4 @@ -import { CodeGroup } from "../../../../../components/code"; +import { CodeGroup, DocsCode } from "../../../../../components/code"; # Liquidity pool @@ -10,21 +10,25 @@ This Liquidity pool interaction guide provides a practical demonstration of inte 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="mac" +touch aerial_liquidity_pool.py +``` + - ```py copy filename="ubuntu" - 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: diff --git a/pages/guides/fetch-network/cosmpy/use-cases/oracles.mdx b/pages/guides/fetch-network/cosmpy/use-cases/oracles.mdx index 8ead24eed..f142b5834 100644 --- a/pages/guides/fetch-network/cosmpy/use-cases/oracles.mdx +++ b/pages/guides/fetch-network/cosmpy/use-cases/oracles.mdx @@ -1,6 +1,6 @@ -import { CodeGroup } from "../../../../../components/code"; +import { CodeGroup, DocsCode } from "../../../../../components/code"; -# Oracles 🔮 +# Oracles ## Introduction @@ -21,21 +21,25 @@ We initially need to download the binaries for both contracts, which can be done 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="mac" +touch aerial_oracle.py +``` + - ```py copy filename="ubuntu" - 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: @@ -237,21 +241,25 @@ Now, we will write a script that deploys a contract that can request the oracle 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="mac" +touch aerial_oracle_client.py +``` + - ```py copy filename="ubuntu" - 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: 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 index 5a0d4700c..96572676a 100644 --- a/pages/guides/fetch-network/cosmpy/use-cases/stake-auto-compounder.mdx +++ b/pages/guides/fetch-network/cosmpy/use-cases/stake-auto-compounder.mdx @@ -1,4 +1,4 @@ -import { CodeGroup } from "../../../../../components/code"; +import { CodeGroup, DocsCode } from "../../../../../components/code"; # Stake auto-compounder @@ -79,21 +79,25 @@ Below we provide a step-by-step guide to create an auto compounder using the `co 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="mac" +touch aerial_compounder.py +``` + - ```py copy filename="ubuntu" - 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: diff --git a/pages/guides/fetch-network/cosmpy/use-cases/swap_automation.mdx b/pages/guides/fetch-network/cosmpy/use-cases/swap_automation.mdx index 7833a5cbc..a528170ab 100644 --- a/pages/guides/fetch-network/cosmpy/use-cases/swap_automation.mdx +++ b/pages/guides/fetch-network/cosmpy/use-cases/swap_automation.mdx @@ -1,4 +1,4 @@ -import { CodeGroup } from "../../../../../components/code"; +import { CodeGroup, DocsCode } from "../../../../../components/code"; # Swap automation 🔄 @@ -10,21 +10,25 @@ The following guide demonstrates an automated swapping strategy for a liquidity 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="mac" +touch aerial_swap_automation.py +``` + - ```py copy filename="ubuntu" - 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: 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 index 39b8b8f50..aa755e945 100644 --- a/pages/guides/fetch-network/cosmpy/use-cases/wallet-top-up.mdx +++ b/pages/guides/fetch-network/cosmpy/use-cases/wallet-top-up.mdx @@ -1,4 +1,4 @@ -import { CodeGroup } from "../../../../../components/code"; +import { CodeGroup, DocsCode } from "../../../../../components/code"; # Wallet top-up 💵 @@ -12,21 +12,25 @@ The following guide is about how to top-up a wallet using the CosmPy library. To 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="mac" +touch aerial_authz.py +``` + - ```py copy filename="ubuntu" - 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: @@ -246,21 +250,25 @@ We are now ready to write a Python script which automates the process of topping 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="mac" +touch aerial_topup.py +``` + - ```py copy filename="ubuntu" - 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: diff --git a/pages/references/uagents/temp.md b/pages/references/uagents/temp.md new file mode 100644 index 000000000..b8e934d47 --- /dev/null +++ b/pages/references/uagents/temp.md @@ -0,0 +1,863 @@ + + +# agent + +source: [src.uagents.agent](https://github.com/fetchai/uAgents/blob/main/python/src/uagents/agent.py) + +Agent + + + +## + +## AgentRepresentation Objects + +```python +class AgentRepresentation() +``` + +Represents an agent in the context of a message. + +#### Attributes: + +- `_address` _str_ - The address of the agent. +- `_name` _Optional[str]_ - The name of the agent. +- `_signing_callback` _Callable_ - The callback for signing messages. + + Properties: + +- `name` _str_ - The name of the agent. +- `address` _str_ - The address of the agent. +- `identifier` _str_ - The agent's address and network prefix. + +#### Methods: + +- `sign_digest(data` - bytes) -> str: Sign the provided data with the agent's identity. + + + +### `__init__` + +```python +def __init__(address: str, name: Optional[str], signing_callback: Callable) +``` + +Initialize the AgentRepresentation instance. + +#### Arguments: + +- `address` _str_ - The address of the context. +- `name` _Optional[str]_ - The optional name associated with the context. +- `signing_callback` _Callable_ - The callback for signing messages. + + + +### `name` + +```python +@property +def name() -> str +``` + +Get the name associated with the context or a truncated address if name is None. + +#### Returns: + +- `str` - The name or truncated address. + + + +### `address` + +```python +@property +def address() -> str +``` + +Get the address of the context. + +#### Returns: + +- `str` - The address of the context. + + + +### `identifier` + +```python +@property +def identifier() -> str +``` + +Get the address of the agent used for communication including the network prefix. + +#### Returns: + +- `str` - The agent's address and network prefix. + + + +### `sign_digest` + +```python +def sign_digest(data: bytes) -> str +``` + +Sign the provided data with the callback of the agent's identity. + +#### Arguments: + +- `data` _bytes_ - The data to sign. + +#### Returns: + +- `str` - The signature of the data. + + + +## + +## Agent Objects + +```python +class Agent(Sink) +``` + +An agent that interacts within a communication environment. + +#### Attributes: + +- `_name` _str_ - The name of the agent. +- `_port` _int_ - The port on which the agent's server runs. +- `_background_tasks` _Set[asyncio.Task]_ - Set of background tasks associated with the agent. +- `_resolver` _Resolver_ - The resolver for agent communication. +- `_loop` _asyncio.AbstractEventLoop_ - The asyncio event loop used by the agent. +- `_logger` - The logger instance for logging agent activities. +- `_endpoints` _List[AgentEndpoint]_ - List of endpoints at which the agent is reachable. +- `_use_mailbox` _bool_ - Indicates if the agent uses a mailbox for communication. +- `_agentverse` _dict_ - Agentverse configuration settings. +- `_mailbox_client` _MailboxClient_ - The client for interacting with the agentverse mailbox. +- `_ledger` - The client for interacting with the blockchain ledger. +- `_almanac_contract` - The almanac contract for registering agent addresses to endpoints. +- `_storage` - Key-value store for agent data storage. +- `_interval_handlers` _List[Tuple[IntervalCallback, float]]_ - List of interval + handlers and their periods. +- `_interval_messages` _Set[str]_ - Set of message digests that may be sent by interval tasks. +- `_signed_message_handlers` _Dict[str, MessageCallback]_ - Handlers for signed messages. +- `_unsigned_message_handlers` _Dict[str, MessageCallback]_ - Handlers for + unsigned messages. +- `_message_cache` _EnvelopeHistory_ - History of messages received by the agent. +- `_models` _Dict[str, Type[Model]]_ - Dictionary mapping supported message digests to messages. +- `_replies` _Dict[str, Dict[str, Type[Model]]]_ - Dictionary of allowed replies for each type + of incoming message. +- `_queries` _Dict[str, asyncio.Future]_ - Dictionary mapping query senders to their response + Futures. +- `_dispatcher` - The dispatcher for internal handling/sorting of messages. +- `_dispenser` - The dispatcher for external message handling. +- `_message_queue` - Asynchronous queue for incoming messages. +- `_on_startup` _List[Callable]_ - List of functions to run on agent startup. +- `_on_shutdown` _List[Callable]_ - List of functions to run on agent shutdown. +- `_version` _str_ - The version of the agent. +- `_protocol` _Protocol_ - The internal agent protocol consisting of all interval and message + handlers assigned with agent decorators. +- `protocols` _Dict[str, Protocol]_ - Dictionary mapping all supported protocol digests to their + corresponding protocols. +- `_ctx` _Context_ - The context for agent interactions. +- `_test` _bool_ - True if the agent will register and transact on the testnet. +- `_enable_agent_inspector` _bool_ - Enable the agent inspector REST endpoints. + + Properties: + +- `name` _str_ - The name of the agent. +- `address` _str_ - The address of the agent used for communication. +- `identifier` _str_ - The Agent Identifier, including network prefix and address. +- `wallet` _LocalWallet_ - The agent's wallet for transacting on the ledger. +- `storage` _KeyValueStore_ - The key-value store for storage operations. +- `mailbox` _Dict[str, str]_ - The mailbox configuration for the agent. +- `agentverse` _Dict[str, str]_ - The agentverse configuration for the agent. +- `mailbox_client` _MailboxClient_ - The client for interacting with the agentverse mailbox. +- `protocols` _Dict[str, Protocol]_ - Dictionary mapping all supported protocol digests to their + corresponding protocols. + + + +### `__init__` + +```python +def __init__(name: Optional[str] = None, + port: Optional[int] = None, + seed: Optional[str] = None, + endpoint: Optional[Union[str, List[str], Dict[str, dict]]] = None, + agentverse: Optional[Union[str, Dict[str, str]]] = None, + mailbox: Optional[Union[str, Dict[str, str]]] = None, + resolve: Optional[Resolver] = None, + registration_policy: Optional[AgentRegistrationPolicy] = None, + enable_wallet_messaging: Union[bool, Dict[str, str]] = False, + wallet_key_derivation_index: Optional[int] = 0, + max_resolver_endpoints: Optional[int] = None, + version: Optional[str] = None, + test: bool = True, + loop: Optional[asyncio.AbstractEventLoop] = None, + log_level: Union[int, str] = logging.INFO, + enable_agent_inspector: bool = True) +``` + +Initialize an Agent instance. + +#### Arguments: + +- `name` _Optional[str]_ - The name of the agent. +- `port` _Optional[int]_ - The port on which the agent's server will run. +- `seed` _Optional[str]_ - The seed for generating keys. +- `endpoint` _Optional[Union[str, List[str], Dict[str, dict]]]_ - The endpoint configuration. +- `agentverse` _Optional[Union[str, Dict[str, str]]]_ - The agentverse configuration. +- `mailbox` _Optional[Union[str, Dict[str, str]]]_ - The mailbox configuration. +- `resolve` _Optional[Resolver]_ - The resolver to use for agent communication. +- `enable_wallet_messaging` _Optional[Union[bool, Dict[str, str]]]_ - Whether to enable + wallet messaging. If '{"chain_id": CHAIN_ID}' is provided, this sets the chain ID for + the messaging server. +- `wallet_key_derivation_index` _Optional[int]_ - The index used for deriving the wallet key. +- `max_resolver_endpoints` _Optional[int]_ - The maximum number of endpoints to resolve. +- `version` _Optional[str]_ - The version of the agent. +- `test` _Optional[bool]_ - True if the agent will register and transact on the testnet. +- `loop` _Optional[asyncio.AbstractEventLoop]_ - The asyncio event loop to use. +- `log_level` _Union[int, str]_ - The logging level for the agent. +- `enable_agent_inspector` _bool_ - Enable the agent inspector for debugging. + + + +### `initialize_wallet_messaging` + +```python +def initialize_wallet_messaging(enable_wallet_messaging: Union[bool, + Dict[str, + str]]) +``` + +Initialize wallet messaging for the agent. + +#### Arguments: + +- `enable_wallet_messaging` _Union[bool, Dict[str, str]]_ - Wallet messaging configuration. + + + +### `name` + +```python +@property +def name() -> str +``` + +Get the name of the agent. + +#### Returns: + +- `str` - The name of the agent. + + + +### `address` + +```python +@property +def address() -> str +``` + +Get the address of the agent used for communication. + +#### Returns: + +- `str` - The agent's address. + + + +### `identifier` + +```python +@property +def identifier() -> str +``` + +Get the Agent Identifier, including network prefix and address. + +#### Returns: + +- `str` - The agent's identifier. + + + +### `wallet` + +```python +@property +def wallet() -> LocalWallet +``` + +Get the wallet of the agent. + +#### Returns: + +- `LocalWallet` - The agent's wallet. + + + +### `ledger` + +```python +@property +def ledger() -> LedgerClient +``` + +Get the ledger of the agent. + +#### Returns: + +- `LedgerClient` - The agent's ledger + + + +### `storage` + +```python +@property +def storage() -> KeyValueStore +``` + +Get the key-value store used by the agent for data storage. + +#### Returns: + +- `KeyValueStore` - The key-value store instance. + + + +### `mailbox` + +```python +@property +def mailbox() -> Dict[str, str] +``` + +Get the mailbox configuration of the agent. +Agentverse overrides it but mailbox is kept for backwards compatibility. + +#### Returns: + +Dict[str, str]: The mailbox configuration. + + + +### `agentverse` + +```python +@property +def agentverse() -> Dict[str, str] +``` + +Get the agentverse configuration of the agent. + +#### Returns: + +Dict[str, str]: The agentverse configuration. + + + +### `mailbox_client` + +```python +@property +def mailbox_client() -> Optional[MailboxClient] +``` + +Get the mailbox client used by the agent for mailbox communication. + +#### Returns: + +- `Optional[MailboxClient]` - The mailbox client instance. + + + +### `balance` + +```python +@property +def balance() -> int +``` + +Get the balance of the agent. + +#### Returns: + +- `int` - Bank balance. + + + +### `mailbox` + +```python +@mailbox.setter +def mailbox(config: Union[str, Dict[str, str]]) +``` + +Set the mailbox configuration for the agent. +Agentverse overrides it but mailbox is kept for backwards compatibility. + +#### Arguments: + +- `config` _Union[str, Dict[str, str]]_ - The new mailbox configuration. + + + +### `agentverse` + +```python +@agentverse.setter +def agentverse(config: Union[str, Dict[str, str]]) +``` + +Set the agentverse configuration for the agent. + +#### Arguments: + +- `config` _Union[str, Dict[str, str]]_ - The new agentverse configuration. + + + +### `sign` + +```python +def sign(data: bytes) -> str +``` + +Sign the provided data. + +#### Arguments: + +- `data` _bytes_ - The data to be signed. + +#### Returns: + +- `str` - The signature of the data. + + + +### `sign_digest` + +```python +def sign_digest(digest: bytes) -> str +``` + +Sign the provided digest. + +#### Arguments: + +- `digest` _bytes_ - The digest to be signed. + +#### Returns: + +- `str` - The signature of the digest. + + + +### `sign_registration` + +```python +def sign_registration() -> str +``` + +Sign the registration data for Almanac contract. + +#### Returns: + +- `str` - The signature of the registration data. + +#### Raises: + +- `AssertionError` - If the Almanac contract address is None. + + + +### `update_endpoints` + +```python +def update_endpoints(endpoints: List[AgentEndpoint]) +``` + +Update the list of endpoints. + +#### Arguments: + +- `endpoints` _List[AgentEndpoint]_ - List of endpoint dictionaries. + + + +### `update_loop` + +```python +def update_loop(loop) +``` + +Update the event loop. + +#### Arguments: + +- `loop` - The event loop. + + + +### `update_queries` + +```python +def update_queries(queries) +``` + +Update the queries attribute. + +#### Arguments: + +- `queries` - The queries attribute. + + + +### `register` + +```python +async def register() +``` + +Register with the Almanac contract. + +This method checks for registration conditions and performs registration +if necessary. + + + +### `on_interval` + +```python +def on_interval(period: float, + messages: Optional[Union[Type[Model], + Set[Type[Model]]]] = None) +``` + +Decorator to register an interval handler for the provided period. + +#### Arguments: + +- `period` _float_ - The interval period. +- `messages` _Optional[Union[Type[Model], Set[Type[Model]]]]_ - Optional message types. + +#### Returns: + +- `Callable` - The decorator function for registering interval handlers. + + + +### `on_query` + +```python +def on_query(model: Type[Model], + replies: Optional[Union[Type[Model], Set[Type[Model]]]] = None) +``` + +Set up a query event with a callback. + +#### Arguments: + +- `model` _Type[Model]_ - The query model. +- `replies` _Optional[Union[Model, Set[Model]]]_ - Optional reply models. + +#### Returns: + +- `Callable` - The decorator function for registering query handlers. + + + +### `on_message` + +```python +def on_message(model: Type[Model], + replies: Optional[Union[Type[Model], Set[Type[Model]]]] = None, + allow_unverified: Optional[bool] = False) +``` + +Decorator to register an message handler for the provided message model. + +#### Arguments: + +- `model` _Type[Model]_ - The message model. +- `replies` _Optional[Union[Type[Model], Set[Type[Model]]]]_ - Optional reply models. +- `allow_unverified` _Optional[bool]_ - Allow unverified messages. + +#### Returns: + +- `Callable` - The decorator function for registering message handlers. + + + +### `on_event` + +```python +def on_event(event_type: str) +``` + +Decorator to register an event handler for a specific event type. + +#### Arguments: + +- `event_type` _str_ - The type of event. + +#### Returns: + +- `Callable` - The decorator function for registering event handlers. + + + +### `on_wallet_message` + +```python +def on_wallet_message() +``` + +Add a handler for wallet messages. + + + +### `include` + +```python +def include(protocol: Protocol, publish_manifest: Optional[bool] = False) +``` + +Include a protocol into the agent's capabilities. + +#### Arguments: + +- `protocol` _Protocol_ - The protocol to include. +- `publish_manifest` _Optional[bool]_ - Flag to publish the protocol's manifest. + +#### Raises: + +- `RuntimeError` - If a duplicate model, signed message handler, or message handler + is encountered. + + + +### `publish_manifest` + +```python +def publish_manifest(manifest: Dict[str, Any]) +``` + +Publish a protocol manifest to the Almanac service. + +#### Arguments: + +- `manifest` _Dict[str, Any]_ - The protocol manifest. + + + +### `handle_message` + +```python +async def handle_message(sender, schema_digest: str, message: JsonStr, + session: uuid.UUID) +``` + +Handle an incoming message. + +#### Arguments: + +- `sender` - The sender of the message. +- `schema_digest` _str_ - The digest of the message schema. +- `message` _JsonStr_ - The message content in JSON format. +- `session` _uuid.UUID_ - The session UUID. + + + +### `handle_rest` + +```python +async def handle_rest( + method: RestMethod, endpoint: str, + message: Optional[Model]) -> Optional[Union[Dict[str, Any], Model]] +``` + +Handle a REST request. + +#### Arguments: + +- `method` _RestMethod_ - The REST method. +- `endpoint` _str_ - The REST endpoint. +- `message` _Model_ - The message content. + + + +### `setup` + +```python +async def setup() +``` + +Include the internal agent protocol, run startup tasks, and start background tasks. + + + +### `start_message_dispenser` + +```python +def start_message_dispenser() +``` + +Start the message dispenser. + + + +### `start_interval_tasks` + +```python +def start_interval_tasks() +``` + +Start interval tasks for the agent. + + + +### `start_message_receivers` + +```python +def start_message_receivers() +``` + +Start message receiving tasks for the agent. + + + +### `start_server` + +```python +async def start_server() +``` + +Start the agent's server. + + + +### `run_async` + +```python +async def run_async() +``` + +Create all tasks for the agent. + + + +### `run` + +```python +def run() +``` + +Run the agent. + + + +### `get_message_protocol` + +```python +def get_message_protocol( + message_schema_digest) -> Optional[Tuple[str, Protocol]] +``` + +Get the protocol for a given message schema digest. + + + +## + +## Bureau Objects + +```python +class Bureau() +``` + +A class representing a Bureau of agents. + +This class manages a collection of agents and orchestrates their execution. + +#### Arguments: + +- `agents` _Optional[List[Agent]]_ - The list of agents to be managed by the bureau. +- `port` _Optional[int]_ - The port number for the server. +- `endpoint` _Optional[Union[str, List[str], Dict[str, dict]]]_ - Configuration + for agent endpoints. + +#### Attributes: + +- `_loop` _asyncio.AbstractEventLoop_ - The event loop. +- `_agents` _List[Agent]_ - The list of agents to be managed by the bureau. +- `_registered_agents` _List[Agent]_ - The list of agents contained in the bureau. +- `_endpoints` _List[Dict[str, Any]]_ - The endpoint configuration for the bureau. +- `_port` _int_ - The port on which the bureau's server runs. +- `_queries` _Dict[str, asyncio.Future]_ - Dictionary mapping query senders to their + response Futures. +- `_logger` _Logger_ - The logger instance. +- `_server` _ASGIServer_ - The ASGI server instance for handling requests. +- `_use_mailbox` _bool_ - A flag indicating whether mailbox functionality is enabled for any + of the agents. + + + +### `__init__` + +```python +def __init__(agents: Optional[List[Agent]] = None, + port: Optional[int] = None, + endpoint: Optional[Union[str, List[str], Dict[str, dict]]] = None, + loop: Optional[asyncio.AbstractEventLoop] = None, + log_level: Union[int, str] = logging.INFO) +``` + +Initialize a Bureau instance. + +#### Arguments: + +- `port` _Optional[int]_ - The port on which the bureau's server will run. +- `endpoint` _Optional[Union[str, List[str], Dict[str, dict]]]_ - The endpoint configuration + for the bureau. + + + +### `add` + +```python +def add(agent: Agent) +``` + +Add an agent to the bureau. + +#### Arguments: + +- `agent` _Agent_ - The agent to be added. + + + +### `run_async` + +```python +async def run_async() +``` + +Run the agents managed by the bureau. + + + +### `run` + +```python +def run() +``` + +Run the bureau. diff --git a/pages/references/uagents/uagents-protocols/agent-protocols.mdx b/pages/references/uagents/uagents-protocols/agent-protocols.mdx index 9722df963..3b3f587af 100644 --- a/pages/references/uagents/uagents-protocols/agent-protocols.mdx +++ b/pages/references/uagents/uagents-protocols/agent-protocols.mdx @@ -1,5 +1,5 @@ import { Callout } from 'nextra/components' -import { CodeGroup } from "../../../../components/code"; +import { CodeGroup, DocsCode } from "../../../../components/code"; # Agents protocols @@ -21,21 +21,25 @@ Let's use a _simple restaurant table booking request_ as an example to better un and - - - ```py copy filename="mac" - touch book.py - ``` - - ```py copy filename="windows" - echo. > book.py - ``` - - ```py copy filename="ubuntu" - touch book.py - ``` - - + + +```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: diff --git a/src/icons/shared-icons.tsx b/src/icons/shared-icons.tsx index df9fb3467..793c6c3c3 100644 --- a/src/icons/shared-icons.tsx +++ b/src/icons/shared-icons.tsx @@ -353,3 +353,72 @@ export const Gear = ({ onClickHandler }: { onClickHandler?: () => void }) => {
); }; + +export const SearchIcon = () => { + return ( + + + + ); +}; + +export const LeftIcon = () => { + return ( + + + + ); +}; + +export const GridViewIcon = ({ viewType }: { viewType: string }) => { + return ( + + + + ); +}; + +export const ListViewIcon = ({ viewType }: { viewType: string }) => { + return ( + + + + ); +}; diff --git a/src/images/agentverse/create-agent/agentverse-myagent_1.png b/src/images/agentverse/create-agent/agentverse-myagent_1.png index 9961d12c2..6d61c44da 100644 Binary files a/src/images/agentverse/create-agent/agentverse-myagent_1.png and b/src/images/agentverse/create-agent/agentverse-myagent_1.png differ diff --git a/src/images/agentverse/create-agent/agentverse-myagent_3.png b/src/images/agentverse/create-agent/agentverse-myagent_3.png index d117a8825..5a80e23fe 100644 Binary files a/src/images/agentverse/create-agent/agentverse-myagent_3.png and b/src/images/agentverse/create-agent/agentverse-myagent_3.png differ diff --git a/src/images/agentverse/create-agent/agentverse-myagent_4.png b/src/images/agentverse/create-agent/agentverse-myagent_4.png index adef1b7d0..2fd4973f1 100644 Binary files a/src/images/agentverse/create-agent/agentverse-myagent_4.png and b/src/images/agentverse/create-agent/agentverse-myagent_4.png differ diff --git a/src/images/agentverse/create-agent/agentverse-myagent_5.png b/src/images/agentverse/create-agent/agentverse-myagent_5.png index 684e6efbd..5973d558b 100644 Binary files a/src/images/agentverse/create-agent/agentverse-myagent_5.png and b/src/images/agentverse/create-agent/agentverse-myagent_5.png differ diff --git a/src/images/agentverse/explorer/agentverse-explorer_1.png b/src/images/agentverse/explorer/agentverse-explorer_1.png index 60f8b24ec..6dcb78101 100644 Binary files a/src/images/agentverse/explorer/agentverse-explorer_1.png and b/src/images/agentverse/explorer/agentverse-explorer_1.png differ diff --git a/src/images/guides/101/sentimentagent_agent_overview.png b/src/images/guides/101/sentimentagent_agent_overview.png index eb9e20515..91936ddaf 100644 Binary files a/src/images/guides/101/sentimentagent_agent_overview.png and b/src/images/guides/101/sentimentagent_agent_overview.png differ diff --git a/src/images/guides/agentverse/agentverse_intro.png b/src/images/guides/agentverse/agentverse_intro.png index 7e9e39c01..c93fb085c 100644 Binary files a/src/images/guides/agentverse/agentverse_intro.png and b/src/images/guides/agentverse/agentverse_intro.png differ diff --git a/src/images/guides/agentverse/autodescriptions.png b/src/images/guides/agentverse/autodescriptions.png new file mode 100644 index 000000000..9303735a5 Binary files /dev/null and b/src/images/guides/agentverse/autodescriptions.png differ diff --git a/src/images/guides/agentverse/autodescriptions_initial.png b/src/images/guides/agentverse/autodescriptions_initial.png new file mode 100644 index 000000000..a8f6581aa Binary files /dev/null and b/src/images/guides/agentverse/autodescriptions_initial.png differ diff --git a/src/images/guides/agentverse/mailbox/agentverse:mailbox/mailbox_1.png b/src/images/guides/agentverse/mailbox/agentverse:mailbox/mailbox_1.png index 123e7265f..3debc95b4 100644 Binary files a/src/images/guides/agentverse/mailbox/agentverse:mailbox/mailbox_1.png and b/src/images/guides/agentverse/mailbox/agentverse:mailbox/mailbox_1.png differ diff --git a/src/images/guides/agentverse/mailbox/agentverse:mailbox/mailbox_2.png b/src/images/guides/agentverse/mailbox/agentverse:mailbox/mailbox_2.png index 201237a6a..f3b23578e 100644 Binary files a/src/images/guides/agentverse/mailbox/agentverse:mailbox/mailbox_2.png and b/src/images/guides/agentverse/mailbox/agentverse:mailbox/mailbox_2.png differ diff --git a/src/images/guides/agentverse/mailbox/agentverse:mailbox/mailbox_3.png b/src/images/guides/agentverse/mailbox/agentverse:mailbox/mailbox_3.png index c3f68fd16..65627ad8a 100644 Binary files a/src/images/guides/agentverse/mailbox/agentverse:mailbox/mailbox_3.png and b/src/images/guides/agentverse/mailbox/agentverse:mailbox/mailbox_3.png differ diff --git a/src/images/guides/agentverse/mailbox/mailbox_1.png b/src/images/guides/agentverse/mailbox/mailbox_1.png index ebf19c511..f5107571d 100644 Binary files a/src/images/guides/agentverse/mailbox/mailbox_1.png and b/src/images/guides/agentverse/mailbox/mailbox_1.png differ diff --git a/src/images/guides/agentverse/mailbox/mailbox_2.png b/src/images/guides/agentverse/mailbox/mailbox_2.png index ad306acd6..16defd32a 100644 Binary files a/src/images/guides/agentverse/mailbox/mailbox_2.png and b/src/images/guides/agentverse/mailbox/mailbox_2.png differ diff --git a/src/images/guides/agentverse/registering-agent-coin-toss/hosted-agent-in-list.png b/src/images/guides/agentverse/registering-agent-coin-toss/hosted-agent-in-list.png index 35c1b8886..273fb6ed2 100644 Binary files a/src/images/guides/agentverse/registering-agent-coin-toss/hosted-agent-in-list.png and b/src/images/guides/agentverse/registering-agent-coin-toss/hosted-agent-in-list.png differ diff --git a/src/images/guides/agentverse/registering-agent-coin-toss/hosted-agent-use-case-button.png b/src/images/guides/agentverse/registering-agent-coin-toss/hosted-agent-use-case-button.png index c3bd18a2c..626908506 100644 Binary files a/src/images/guides/agentverse/registering-agent-coin-toss/hosted-agent-use-case-button.png and b/src/images/guides/agentverse/registering-agent-coin-toss/hosted-agent-use-case-button.png differ diff --git a/src/images/guides/agentverse/registering-agent-coin-toss/new-service-dialog.png b/src/images/guides/agentverse/registering-agent-coin-toss/new-service-dialog.png index 8b728b0d0..86517db81 100644 Binary files a/src/images/guides/agentverse/registering-agent-coin-toss/new-service-dialog.png and b/src/images/guides/agentverse/registering-agent-coin-toss/new-service-dialog.png differ diff --git a/src/images/guides/agentverse/registering-agent-coin-toss/run-hosted-agent.png b/src/images/guides/agentverse/registering-agent-coin-toss/run-hosted-agent.png index 8485c6e6a..ced4c9c36 100644 Binary files a/src/images/guides/agentverse/registering-agent-coin-toss/run-hosted-agent.png and b/src/images/guides/agentverse/registering-agent-coin-toss/run-hosted-agent.png differ diff --git a/src/images/guides/agentverse/registering-agent-dice-roll/hosted-agent-in-list.png b/src/images/guides/agentverse/registering-agent-dice-roll/hosted-agent-in-list.png index cf56f93ea..cef0ffe05 100644 Binary files a/src/images/guides/agentverse/registering-agent-dice-roll/hosted-agent-in-list.png and b/src/images/guides/agentverse/registering-agent-dice-roll/hosted-agent-in-list.png differ diff --git a/src/images/guides/agentverse/registering-agent-dice-roll/new-service-dialog.png b/src/images/guides/agentverse/registering-agent-dice-roll/new-service-dialog.png index 8816a836b..0b577fac6 100644 Binary files a/src/images/guides/agentverse/registering-agent-dice-roll/new-service-dialog.png and b/src/images/guides/agentverse/registering-agent-dice-roll/new-service-dialog.png differ diff --git a/src/images/guides/agentverse/registering-agent-dice-roll/run-hosted-agent.png b/src/images/guides/agentverse/registering-agent-dice-roll/run-hosted-agent.png index ff3ec8e0d..5416f9f9b 100644 Binary files a/src/images/guides/agentverse/registering-agent-dice-roll/run-hosted-agent.png and b/src/images/guides/agentverse/registering-agent-dice-roll/run-hosted-agent.png differ diff --git a/src/images/guides/services/service-guide/business_finder_1.png b/src/images/guides/services/service-guide/business_finder_1.png index 2dd8fb151..7b15bac96 100644 Binary files a/src/images/guides/services/service-guide/business_finder_1.png and b/src/images/guides/services/service-guide/business_finder_1.png differ diff --git a/src/images/guides/services/service-guide/business_finder_2.png b/src/images/guides/services/service-guide/business_finder_2.png index 49c7b5509..9cdf32f83 100644 Binary files a/src/images/guides/services/service-guide/business_finder_2.png and b/src/images/guides/services/service-guide/business_finder_2.png differ diff --git a/src/images/guides/services/service-guide/business_finder_3.png b/src/images/guides/services/service-guide/business_finder_3.png index afc99ee1d..2569c61f4 100644 Binary files a/src/images/guides/services/service-guide/business_finder_3.png and b/src/images/guides/services/service-guide/business_finder_3.png differ diff --git a/src/images/guides/services/service-guide/hugging_face_1.png b/src/images/guides/services/service-guide/hugging_face_1.png index de055bf6c..e40cfbec3 100644 Binary files a/src/images/guides/services/service-guide/hugging_face_1.png and b/src/images/guides/services/service-guide/hugging_face_1.png differ diff --git a/src/images/guides/services/service-guide/hugging_face_2.png b/src/images/guides/services/service-guide/hugging_face_2.png index 6a847b2a1..c14080a65 100644 Binary files a/src/images/guides/services/service-guide/hugging_face_2.png and b/src/images/guides/services/service-guide/hugging_face_2.png differ diff --git a/src/images/guides/services/service-guide/hugging_face_3.png b/src/images/guides/services/service-guide/hugging_face_3.png index 4b7cb545b..0d7b4e388 100644 Binary files a/src/images/guides/services/service-guide/hugging_face_3.png and b/src/images/guides/services/service-guide/hugging_face_3.png differ diff --git a/src/images/guides/services/service-guide/simple_protocol_0.png b/src/images/guides/services/service-guide/simple_protocol_0.png index f4a30bb0c..eb600282a 100644 Binary files a/src/images/guides/services/service-guide/simple_protocol_0.png and b/src/images/guides/services/service-guide/simple_protocol_0.png differ diff --git a/src/images/guides/services/service-guide/simple_protocol_1.png b/src/images/guides/services/service-guide/simple_protocol_1.png index 3da01576c..dcb3ad74e 100644 Binary files a/src/images/guides/services/service-guide/simple_protocol_1.png and b/src/images/guides/services/service-guide/simple_protocol_1.png differ diff --git a/src/images/guides/services/the-importance-of-descriptions/description_2.png b/src/images/guides/services/the-importance-of-descriptions/description_2.png index 86fbe596d..aa6775d48 100644 Binary files a/src/images/guides/services/the-importance-of-descriptions/description_2.png and b/src/images/guides/services/the-importance-of-descriptions/description_2.png differ diff --git a/src/images/guides/services/the-importance-of-descriptions/description_3.png b/src/images/guides/services/the-importance-of-descriptions/description_3.png index 53790a4b5..98b836b58 100644 Binary files a/src/images/guides/services/the-importance-of-descriptions/description_3.png and b/src/images/guides/services/the-importance-of-descriptions/description_3.png differ diff --git a/src/images/guides/uagent/langchain_function.png b/src/images/guides/uagent/langchain_function.png index d14c59a7e..ea7b6aa96 100644 Binary files a/src/images/guides/uagent/langchain_function.png and b/src/images/guides/uagent/langchain_function.png differ diff --git a/src/images/guides/uagent/servicefordungeons_3.png b/src/images/guides/uagent/servicefordungeons_3.png index a9ef8dd29..0e38f21e0 100644 Binary files a/src/images/guides/uagent/servicefordungeons_3.png and b/src/images/guides/uagent/servicefordungeons_3.png differ diff --git a/styles/globals.css b/styles/globals.css index 6c6f680ab..2f473b64c 100644 --- a/styles/globals.css +++ b/styles/globals.css @@ -1672,6 +1672,10 @@ video { padding-top: 2rem; } +.nx-pt-20 { + padding-top: 5rem; +} + .nx-text-left { text-align: left; } @@ -4472,27 +4476,27 @@ div:hover > .\[div\:hover\>\&\]\:nx-opacity-100 { } .list-view { - border: 1px solid #ddd; + border: 1px solid #dce2ea; border-radius: 8px; - padding: 12px; + padding: 16px 48px 16px 16px; margin-bottom: 10px; transition: border-color 0.3s ease-in-out, transform 0.3s ease-in-out; } +.list-view-title:hover { + color: #5f38fb; +} +.list-view-title { + color: #000d3d; + font-size: 16px; + font-weight: 500; + text-transform: capitalize; +} .list-view:hover { - /* padding: 24px; */ - border-radius: 16px; - background-color: rgba(126, 190, 206, 0.2); - background: linear-gradient( - 134deg, - rgba(133, 102, 255, 0.2) 16.16%, - rgba(95, 56, 251, 0.3) 55.86%, - rgba(95, 56, 251, 0.4) 78.77% - ); - box-shadow: 10px 10px 30px 0px rgba(95, 56, 251, 0.3); - backdrop-filter: blur(10px); + background-color: #efebff; + backdrop-filter: blur(35px); cursor: pointer; } @@ -5038,3 +5042,38 @@ div:hover > .\[div\:hover\>\&\]\:nx-opacity-100 { background: #fff; box-shadow: 0px 30px 60px 0px rgba(0, 0, 0, 0.1); } + +.tags { + border: 1px solid #dce2ea; + background-color: #fff; +} + +.tags:hover { + border-color: #efebff; + background-color: #efebff; + color: #5f38fb; +} + +.toggle-view { + border-radius: 8px; + border: 1px solid #b9c5d4; + background: #fff; + padding: 3px; +} + +.toggle-list-grid-bg { + background: #efebff; + border-radius: 6px; +} + +.tags-input { + display: flex; + width: 280px; + height: 44px; + padding: 12px; + justify-content: space-between; + align-items: center; + border: 1px solid #d0d9e3; + border-radius: 8px; + margin-top: 35px; +} diff --git a/theme/fetch-ai-docs/components/matching-tag-routes.tsx b/theme/fetch-ai-docs/components/matching-tag-routes.tsx index 4dd2e1a28..f4ee0556a 100644 --- a/theme/fetch-ai-docs/components/matching-tag-routes.tsx +++ b/theme/fetch-ai-docs/components/matching-tag-routes.tsx @@ -1,10 +1,15 @@ /* eslint-disable unicorn/consistent-function-scoping */ -import { GuideBox } from "components/feature-guide-tabs"; -import { Button } from "nextra/components"; import React, { ReactElement, useEffect, useState } from "react"; -import { FaBars, FaThLarge, FaAngleUp, FaAngleDown } from "react-icons/fa"; import { useRouter } from "next/router"; import fetchJson from "src/lib/fetch-json"; +import { GridView } from "components/grid-view"; +import { Input } from "./input"; +import { + GridViewIcon, + LeftIcon, + ListViewIcon, + SearchIcon, +} from "src/icons/shared-icons"; interface RouteInfo { route: string; @@ -13,21 +18,29 @@ interface RouteInfo { interface RoutesComponentProps { routes: RouteInfo[]; + setMatchingTagRoute: React.Dispatch>; } export function MatchingRoutesComponent({ routes, + setMatchingTagRoute, }: RoutesComponentProps): ReactElement { const [viewType, setViewType] = useState<"list" | "grid">("list"); const [content, setContent] = useState([]); - const [isListViewCollapsed, setListViewCollapsed] = useState(false); + const [searchQuery, setSearchQuery] = useState(""); + const [matchedRoutes, setMatchedRoutes] = useState(routes); const router = useRouter(); const toggleView = (type) => { setViewType(type); }; - const toggleListView = () => { - setListViewCollapsed((prevCollapsed) => !prevCollapsed); + const handleSearch = (event) => { + setSearchQuery(event.target.value.toLowerCase()); + const filteredRoutes = routes.filter((routeInfo) => { + const guideInfo = findGuideByPath(content, routeInfo.route); + return guideInfo.title.toLowerCase().includes(searchQuery); + }); + setMatchedRoutes(filteredRoutes); }; const fetchGuide = async () => { @@ -90,116 +103,121 @@ export function MatchingRoutesComponent({ return { title, description }; }; + const routeTitle = () => { + const pathname = window.location.pathname; + return ( + pathname.split("/").pop().split("-").join(" ").charAt(0).toUpperCase() + + pathname.split("/").pop().split("-").join(" ").slice(1) + ); + }; + return (
+
-

Topics with matching tag:

- - +
+

+ {matchedRoutes?.length} topics matching with the tag +

+
- {isListViewCollapsed ? ( - - ) : ( - - )} +
+ + +
+
+
+ +
+ +
- {viewType === "list" - ? !isListViewCollapsed && ( -
    - {routes.map((routeInfo, index) => { - const guideInfo = findGuideByPath(content, routeInfo.route); - return ( -
  • { - router.push(routeInfo.route); - }} - > -

    - {guideInfo.title} -

    -

    - {guideInfo.description} -

    -
  • - ); - })} -
- ) - : !isListViewCollapsed && ( -
-
- {routes.map((routeInfo, index) => { - const guideInfo = findGuideByPath(content, routeInfo.route); - return ( - - ); - })} -
-
- )} + {viewType === "list" ? ( +
    + {matchedRoutes.map((routeInfo, index) => { + const guideInfo = findGuideByPath(content, routeInfo.route); + return ( +
  • { + router.push(routeInfo.route); + }} + > +

    {guideInfo.title}

    +

    + {guideInfo.description} +

    +
  • + ); + })} +
+ ) : ( +
+
+ {matchedRoutes.map((routeInfo, index) => { + const guideInfo = findGuideByPath(content, routeInfo.route); + return ( + + ); + })} +
+
+ )}
); } diff --git a/theme/fetch-ai-docs/index.tsx b/theme/fetch-ai-docs/index.tsx index 188940bd3..3901050a7 100644 --- a/theme/fetch-ai-docs/index.tsx +++ b/theme/fetch-ai-docs/index.tsx @@ -92,22 +92,13 @@ const Body = ({ setMatchingTagRoute(filteredRoutes); }; - const tagColors = [ - "bg-indigo", - "bg-orange", - "bg-light-green", - "bg-blue-150", - "bg-yellow-150", - "bg-red-150", - ]; - const tagsComponent = tags && ( + const tagsComponent = tags && !matchingTagRoute && (
{tags.map((tag, index) => ( @@ -129,7 +120,10 @@ const Body = ({ <> {tagsComponent} {matchingTagRoute ? ( - + ) : ( "" )} @@ -171,7 +165,7 @@ const Body = ({ )} >
- {breadcrumb} + {!matchingTagRoute && breadcrumb} {body}
diff --git a/update_code.py b/update_code.py index a75df625d..cf3fe8381 100644 --- a/update_code.py +++ b/update_code.py @@ -76,16 +76,24 @@ def insert_tag(match): filePath = "/".join(parts[7:]) filename = parts[len(parts) - 1] + hosted = code_group["hosted"] + lines = getGitHubData(username, repository, filePath) selection = lines.split("\n")[int(code_group["lineStart"]) - 1:int(code_group["lineEnd"])] - selection = ["\t\t" + s for s in selection] + selection = [s for s in selection] s = '\n'.join(selection) - code_block = code_block + f"""\n\n\t```py copy filename="{filename}"\n\n{s}\n\n```""" + print (hosted) + + code_block = code_block + f"""\n\n\n\t```py copy filename="{filename}"\n\n{s}\n\n```\n\n""" + + new_jsx_object = f"\n{code_block}\n" + print (new_jsx_object) + return f"\n{new_jsx_object}" for match in re.finditer(jsx_obj_regex, data): @@ -117,4 +125,8 @@ def directory_loop(directory, removal): filePath = './pages/guides/agents/quickstart.mdx'; delete_code_sample(filePath) -insert_Html_after_jsx(filePath) \ No newline at end of file +insert_Html_after_jsx(filePath) + +import subprocess + +subprocess.run(["pnpm", "run", "fmt"]) \ No newline at end of file