Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore(docs): updating examples ot have links to their repos #1052

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
80 changes: 80 additions & 0 deletions .github/spelling/known_words_corpus.txt
Original file line number Diff line number Diff line change
Expand Up @@ -728,6 +728,86 @@ xml
ylabel
yml
yscale
zyx
dataLanguage
osMenu
hasCopyCode
CustomPre
ender
tech
England
transformative
Agentic
GPT
codegroup
SenderAgent
uvicorn
intfield
floatfield
onetoonefield
charfield
pk
intenum
reverserelation
datetimefield
intenumfield
manytomanyfield
visualisations
subsidised
etc
lifecycle
screenshot
docscode
richtext
bestmatches
gnews
newsrequest
v20
servicefordungeons
darksystemdiagramaiengine
svg
systemdiagramaiengine
humantextin
darkhumantextin
darkaiwithpersonaldata
aiwithpersonaldata
darkmailroom
darkscalinghosting
scalinghosting
anagentforeveryone
darkhostingnameservice1
darkanagentforeveryone
hostingnameservice1
darkagentsinteracting
imagebytheme
agentsinteracting
decentralisednetwork
darkdecentralisednetwork
decentralised
publicandprivateagents
darkpublicandprivateagents
highleveldiagram
darkhighleveldiagram
walkthrough
asyncio
asgi
abstracteventloop
ethan
olivia
hackathon
onboarded
CI
jupyter
streamlit
bot
screenshots
aws
guidesmdx
agentsicon
ledgericon
asiicon
githubcodesegment
codesegment
GlobalResolver
ReceiverAgent
TESTFET
Expand Down
200 changes: 112 additions & 88 deletions pages/examples/advanced/async-loops.mdx
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import { CodeGroup, DocsCode } from "../../../components/code";
import { CodeGroup, DocsCode, CodeSegment, GithubCodeSegment } from "../../../components/code";

# Agent Asynchronous Loops

## Introduction

In this example, we demonstrate how to use agents to communicate and exchange status updates in a decentralized system. Agents will send status messages to each other and handle acknowledgments in response. This example is useful for understanding how agents can interact, process messages, and maintain state.

Please check out the example code in our [examples repo ↗️](https://github.com/fetchai/uAgent-Examples/tree/main/1-uagents/examples/advanced/async-loops) to run this locally.

### Supporting documentation

- [Creating an agent ↗️](/guides/agents/create-a-uagent)
Expand All @@ -17,102 +19,124 @@ In this example, we demonstrate how to use agents to communicate and exchange st

#### Script 1

<CodeGroup hasCopy isLocalHostedFile>
<GithubCodeSegment digest="6f7e6def9faac6be82d2605dc7ceb7d2">
<CodeSegment
path="https://github.com/fetchai/uAgent-Examples/blob/main/1-uagents/examples/advanced/async-loops/external_loop_attach.py"
lineStart={1}
lineEnd={41}
hosted={true}
/>
</GithubCodeSegment>
<CodeGroup dynamic hasCopy isLocalHostedFile digest='6f7e6def9faac6be82d2605dc7ceb7d2'>

<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>
```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>
</CodeGroup>
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

<CodeGroup hasCopy isLocalHostedFile>
<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,
)
<GithubCodeSegment digest="f83ea329204e5a24fa261dd7d399259d">
<CodeSegment
path="https://github.com/fetchai/uAgent-Examples/blob/main/1-uagents/examples/advanced/async-loops/external_loop_run.py"
lineStart={1}
lineEnd={39}
hosted={true}
/>
</GithubCodeSegment>
<CodeGroup dynamic hasCopy isLocalHostedFile digest='f83ea329204e5a24fa261dd7d399259d'>

@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()
<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>

# > when starting the external loop from the bureau
# bureau.run()
```
</DocsCode>
</CodeGroup>

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.
Expand Down
Loading