Skip to content

Commit

Permalink
edits: substitued code snippets
Browse files Browse the repository at this point in the history
  • Loading branch information
FelixNicolaeBucsa committed Oct 17, 2024
1 parent 03f98c4 commit 86e0803
Show file tree
Hide file tree
Showing 33 changed files with 2,802 additions and 3,600 deletions.
202 changes: 123 additions & 79 deletions pages/guides/agents/advanced/agents-async-loops.mdx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { CodeGroup, DocsCode } from "../../../../components/code";
import { CodeGroup, CodeSegment, DocsCode, GithubCodeSegment } from "../../../../components/code";

# Agent Asynchronous Loops

Expand Down Expand Up @@ -47,49 +47,71 @@ First of all, let's create a Python script:

Now, paste the below code into it:

```py copy filename="external_loop_attach.py"
import asyncio
import contextlib

from uagents import Agent, Bureau, Context

loop = asyncio.get_event_loop()

agent = Agent(
name="looper",
seed="<YOUR_SEED>",
)

bureau = Bureau(
agents=[agent],
)

@agent.on_event("startup")
async def startup(ctx: Context):
ctx.logger.info(">>> Looper is starting up.")

@agent.on_event("shutdown")
async def shutdown(ctx: Context):
ctx.logger.info(">>> Looper is shutting down.")

async def coro():
while True:
print("doing hard work...")
await asyncio.sleep(1)

if __name__ == "__main__":
print("Attaching the agent or bureau to the external loop...")
loop.create_task(coro())
<GithubCodeSegment digest="2f3f0744a953cd4ceff94963441a2f96">
<CodeSegment
path="https://github.com/fetchai/uAgent-Examples/blob/main/5-documentation/guides/agents/advanced/agents-async-loops/external_loop_attach.py"
lineStart={1}
lineEnd={45}
hosted={true}
/>
</GithubCodeSegment>
<CodeGroup dynamic hasCopy isLocalHostedFile digest='2f3f0744a953cd4ceff94963441a2f96'>

<DocsCode local={true}>
```py copy filename="external_loop_attach.py"

import asyncio
import contextlib

from uagents import Agent, Bureau, Context

loop = asyncio.get_event_loop()

agent = Agent(
name="looper",
seed="<YOUR_SEED>",
)

bureau = Bureau(
agents=[agent],
)


@agent.on_event("startup")
async def startup(ctx: Context):
ctx.logger.info(">>> Looper is starting up.")


@agent.on_event("shutdown")
async def shutdown(ctx: Context):
ctx.logger.info(">>> Looper is shutting down.")


async def coro():
while True:
print("doing hard work...")
await asyncio.sleep(1)


if __name__ == "__main__":
print("Attaching the agent or bureau to the external loop...")
loop.create_task(coro())

# > when attaching the agent to the external loop
loop.create_task(agent.run_async())

# > when attaching a bureau to the external loop
# loop.create_task(bureau.run_async())

with contextlib.suppress(KeyboardInterrupt):
loop.run_forever()

```
</DocsCode>

# > when attaching the agent to the external loop
loop.create_task(agent.run_async())
</CodeGroup>

# > when attaching a bureau to the external loop
# loop.create_task(bureau.run_async())

with contextlib.suppress(KeyboardInterrupt):
loop.run_forever()
```

This script is for an agent using an external event loop. We first import the required libraries for this script to be run correctly. We then proceed and instantiate an agent called `looper` using a `seed`. Remember that you need to provide a seed within the `<YOUR_SEED>` field parameter. We then need to create a `bureau` to manage the agents. We can now add the `looper` agent into the `bureau`.

Expand Down Expand Up @@ -131,47 +153,69 @@ Let's start by creating a Python script:

Then, let's paste the below code into it:

```py copy filename="external_loop_run.py"
import asyncio

from uagents import Agent, Bureau, Context

loop = asyncio.get_event_loop()

agent = Agent(
name="looper",
seed="<YOUR_SEED>",
loop=loop,
)

bureau = Bureau(
agents=[agent],
loop=loop,
)

@agent.on_event("startup")
async def startup(ctx: Context):
ctx.logger.info(">>> Looper is starting up.")

@agent.on_event("shutdown")
async def shutdown(ctx: Context):
ctx.logger.info(">>> Looper is shutting down.")

async def coro():
while True:
print("doing hard work...")
await asyncio.sleep(1)
<GithubCodeSegment digest="aa7c205c69e65b45336f9edc21defdab">
<CodeSegment
path="https://github.com/fetchai/uAgent-Examples/blob/main/5-documentation/guides/agents/advanced/agents-async-loops/external_loop_run.py"
lineStart={1}
lineEnd={43}
hosted={true}
/>
</GithubCodeSegment>
<CodeGroup dynamic hasCopy isLocalHostedFile digest='aa7c205c69e65b45336f9edc21defdab'>

<DocsCode local={true}>
```py copy filename="external_loop_run.py"

import asyncio

from uagents import Agent, Bureau, Context

loop = asyncio.get_event_loop()

agent = Agent(
name="looper",
seed="<YOUR_SEED>",
loop=loop,
)

bureau = Bureau(
agents=[agent],
loop=loop,
)


@agent.on_event("startup")
async def startup(ctx: Context):
ctx.logger.info(">>> Looper is starting up.")


@agent.on_event("shutdown")
async def shutdown(ctx: Context):
ctx.logger.info(">>> Looper is shutting down.")


async def coro():
while True:
print("doing hard work...")
await asyncio.sleep(1)


if __name__ == "__main__":
print("Starting the external loop from the agent or bureau...")
loop.create_task(coro())

# > when starting the external loop from the agent
agent.run()

# > when starting the external loop from the bureau
# bureau.run()

```
</DocsCode>

if __name__ == "__main__":
print("Starting the external loop from the agent or bureau...")
loop.create_task(coro())
</CodeGroup>

# > when starting the external loop from the agent
agent.run()

# > when starting the external loop from the bureau
# bureau.run()
```

We start by importing the required libraries to correctly run this script. We then create an asynchronous event loop using `asyncio.get_event_loop()`. This loop is used to handle all asynchronous operations, such as the agent's actions and background tasks.

Expand Down
147 changes: 85 additions & 62 deletions pages/guides/agents/advanced/localwallet.mdx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Callout } from 'nextra/components'
import { CodeGroup, CodeSegment, DocsCode, GithubCodeSegment } from "../../../../components/code";

# Local Wallet

Expand Down Expand Up @@ -91,72 +92,94 @@ You can also use an account's mnemonic phrase to get the associated private key.

A simple agent that creates, or loads in a wallet, then validates a transaction has been received.

```python copy filename="local_wallet_agent.py"
<GithubCodeSegment digest="d5cadbc2e2bbf700267f9a82c1013b79">
<CodeSegment
path="https://github.com/fetchai/uAgent-Examples/blob/main/5-documentation/guides/agents/advanced/localwallet/local_wallet_agent.py"
lineStart={1}
lineEnd={68}
hosted={true}
/>
</GithubCodeSegment>
<CodeGroup dynamic hasCopy isLocalHostedFile digest='d5cadbc2e2bbf700267f9a82c1013b79'>

<DocsCode local={true}>
```py copy filename="local_wallet_agent.py"

from cosmpy.aerial.wallet import LocalWallet
from cosmpy.aerial.client import LedgerClient, NetworkConfig
from cosmpy.crypto.keypairs import PrivateKey
from uagents import Agent, Context, Model
from uagents.network import get_faucet, wait_for_tx_to_complete

mainnet_ledger = LedgerClient(NetworkConfig.fetchai_mainnet())


class RequestWithTX(Model):
message: str
tx_hash: str


class DataResponse(Model):
message: str


class PaymentError(Model):
message: str
tx_hash: str


DataSellingAgent = Agent(
name="DataSellingAgent",
seed="dwefwegferdwdwedgko4o430490349jf340-jffjweiopfnw",
port=8001,
endpoint=["http://localhost:8001/submit"],
)

print(DataSellingAgent.address)

AMOUNT = 1
DENOM = "afet"
DATA_TO_SELL = "..."

## at first you may want to generate a wallet
my_wallet = LocalWallet.generate()
## or open one from a seed you've set
# my_wallet = LocalWallet.from_unsafe_seed("registration test wallet")
# pk = my_wallet._private_key
## or from a pk you already have
# wallet = LocalWallet(PrivateKey("T7w1yHq1QIcQiSqV27YSwk+i1i+Y4JMKhkpawCQIh6s="))

...


@DataSellingAgent.on_message(model=RequestWithTX)
async def message_handler(ctx: Context, sender: str, msg: RequestWithTX):
ctx.logger.info(f"Received message from {sender}: {msg.message}")

mainnet_ledger.query_tx(msg.tx_hash)
tx_resp = await wait_for_tx_to_complete(msg.tx_hash, mainnet_ledger)

coin_received = tx_resp.events["coin_received"]
if (
coin_received["receiver"] == str(my_wallet.address)
and coin_received["amount"] == f"{AMOUNT}{DENOM}"
):
ctx.logger.info(f"Transaction was successful: {coin_received}")
await ctx.send(sender, DataResponse(message=DATA_TO_SELL))

else:
await ctx.send(sender, PaymentError(message="Incorrect tx", tx_hash=msg.tx_hash))


if __name__ == "__main__":
DataSellingAgent.run()

from cosmpy.aerial.wallet import LocalWallet
from cosmpy.aerial.client import LedgerClient, NetworkConfig
from cosmpy.crypto.keypairs import PrivateKey
from uagents import Agent, Context, Model
from uagents.network import get_faucet, wait_for_tx_to_complete

mainnet_ledger = LedgerClient(NetworkConfig.fetchai_mainnet())

class RequestWithTX(Model):
message: str
tx_hash: str

class DataResponse(Model):
message: str

class PaymentError(Model):
message: str
tx_hash: str

DataSellingAgent = Agent(
name="DataSellingAgent",
seed="dwefwegferdwdwedgko4o430490349jf340-jffjweiopfnw",
port=8001,
endpoint=["http://localhost:8001/submit"],
)

print (DataSellingAgent.address)

AMOUNT = 1
DENOM = "afet"
DATA_TO_SELL = "..."

## at first you may want to generate a wallet
my_wallet = LocalWallet.generate()
## or open one from a seed you've set
# my_wallet = LocalWallet.from_unsafe_seed("registration test wallet")
# pk = my_wallet._private_key
## or from a pk you already have
# wallet = LocalWallet(PrivateKey("T7w1yHq1QIcQiSqV27YSwk+i1i+Y4JMKhkpawCQIh6s="))

...

@DataSellingAgent.on_message(model=RequestWithTX)
async def message_handler(ctx: Context, sender: str, msg: RequestWithTX):
ctx.logger.info(f"Received message from {sender}: {msg.message}")

mainnet_ledger.query_tx(msg.tx_hash)
tx_resp = await wait_for_tx_to_complete(msg.tx_hash, mainnet_ledger)

coin_received = tx_resp.events["coin_received"]
if (
coin_received["receiver"] == str(my_wallet.address)
and coin_received["amount"] == f"{AMOUNT}{DENOM}"
):
ctx.logger.info(f"Transaction was successful: {coin_received}")
await ctx.send(sender, DataResponse(message=DATA_TO_SELL))
```
</DocsCode>

else:
await ctx.send(sender, PaymentError(message="Incorrect tx", tx_hash=msg.tx_hash))
</CodeGroup>

if __name__ == "__main__":
DataSellingAgent.run()

```

Validating a transaction with Cosmpy and uAgents is really easy, and to test the above agent you just need to replicate the `Models` and send a `RequestWithTX` in any function in another agent:

Expand Down
Loading

0 comments on commit 86e0803

Please sign in to comment.