Skip to content

Commit

Permalink
feat(docs): replaced code blocks with GithubCodeSegment object
Browse files Browse the repository at this point in the history
  • Loading branch information
FelixNicolaeBucsa committed Oct 17, 2024
1 parent fb3c1ef commit 03f98c4
Show file tree
Hide file tree
Showing 50 changed files with 1,925 additions and 1,198 deletions.
5 changes: 1 addition & 4 deletions pages/guides/agent-courses/agents-for-ai.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ At any stage, if you encounter issues or have questions about specific terms or

Current version of the AI Engine package is <PackageVersion packageName="uagents-ai-engine" packageType="pypi" />
</Callout>

## Quick overview of Fetch.ai

Fetch.ai is developing a platform to help build an AI-enabled decentralized digital economy. Agents are
Expand Down Expand Up @@ -363,7 +363,6 @@ Let's take a look.
class SummaryRequest(Model):
url: str


SEED_PHRASE = "<your_seed_phrase>"
AGENT_MAILBOX_KEY = "<your_mailbox_key>"
OPENAI_API_KEY = "<your_open_ai_key>"
Expand All @@ -379,7 +378,6 @@ Let's take a look.
print(summaryAgent.address)
print(OPENAI_API_KEY)


@summary_protocol.on_message(model=SummaryRequest, replies={UAgentResponse})
async def summarise(ctx: Context, sender: str, msg: SummaryRequest):

Expand Down Expand Up @@ -415,7 +413,6 @@ Let's take a look.
UAgentResponse(message=(result["output_text"]), type=UAgentResponseType.FINAL),
)


summaryAgent.include(summary_protocol, publish_manifest=True)
summaryAgent.run()
```
Expand Down
5 changes: 1 addition & 4 deletions pages/guides/agent-courses/introductory-course.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -870,7 +870,7 @@ Let's then define the message handlers for the `query_proto` protocol:
We define a protocol `query_proto` using the `Protocol` class of `uagents`. It is defined with a `name` and a `version`.

The `handle_query_request()` function is the message handler function defined using the `on_message()` decorator. It handles the `QueryTableRequest` messages and replies with a `QueryTableResponse` message. The handler processes the table availability query based on the provided parameters, checks the table status stored in the agent's storage, and sends the available table numbers as a response to the querying agent.

Additionally, the handler tracks the total number of queries made and increments the count in storage. On the other hand, `handle_get_total_queries()` is the message handler function defined using the `on_query()` decorator. It handles the `GetTotalQueries` query and replies with a `TotalQueries` message containing the total number of queries made to the system. The handler retrieves the total query count from the agent's storage and responds with the count.

The overall script should look as follows:
Expand Down Expand Up @@ -1220,7 +1220,6 @@ The overall script would be:
if not completed:
await ctx.send(RESTAURANT_ADDRESS, table_query)


@user.on_message(QueryTableResponse, replies={BookTableRequest})
async def handle_query_response(ctx: Context, sender: str, msg: QueryTableResponse):
if len(msg.tables) > 0:
Expand All @@ -1236,7 +1235,6 @@ The overall script would be:
ctx.logger.info("No free tables - nothing more to do")
ctx.storage.set("completed", True)


@user.on_message(BookTableResponse, replies=set())
async def handle_book_response(ctx: Context, _sender: str, msg: BookTableResponse):
if msg.success:
Expand All @@ -1246,7 +1244,6 @@ The overall script would be:

ctx.storage.set("completed", True)


if __name__ == "__main__":
user.run()
```
Expand Down
5 changes: 0 additions & 5 deletions pages/guides/agents/advanced/agents-async-loops.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,6 @@ Now, paste the below code into it:

loop = asyncio.get_event_loop()


agent = Agent(
name="looper",
seed="<YOUR_SEED>",
Expand All @@ -65,23 +64,19 @@ Now, paste the below code into it:
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())
Expand Down
2 changes: 1 addition & 1 deletion pages/guides/agents/advanced/dialogues.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ class ChitChatDialogue(Dialogue):
nodes=[ node1, node2, node3],
edges=[ init_session, start_dialogue, cont_dialogue, end_session],
)

def on_continue_dialogue(self):
return super()._on_state_transition(
cont_dialogue.name,
Expand Down
39 changes: 16 additions & 23 deletions pages/guides/agents/advanced/localwallet.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,6 @@ from cosmpy.crypto.keypairs import PrivateKey
private_key = PrivateKey()
```


## Recover an existing private key

Let's start by extracting the private key and convert it into a base64 encoded string. You can do this on macOS or Linux for the Fetch.ai network using the FetchD CL.
Expand Down Expand Up @@ -88,81 +87,75 @@ You can also use an account's mnemonic phrase to get the associated private key.
wallet = LocalWallet.from_mnemonic(mnemonic)
```


## An Agent that checks for a transaction, and sends funds

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

```python 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()



```

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
6 changes: 3 additions & 3 deletions pages/guides/agents/advanced/message-verification.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -38,15 +38,15 @@ Make sure you have read the following resources before going on with this guide:
echo. > message_verification.py
```
</DocsCode>

<DocsCode ubuntu={true}>
```py copy filename="ubuntu"
touch message_verification.py
```
</DocsCode>

</CodeGroup>

3. We now need to import the necessary classes from `uagents` (`Agent`, `Bureau`, `Context`, and `Model`), `uagents.crypto` (`Identity`) and `hashlib`. Then we would need to define the messages format using the `Message` class as a subclass of `Model`:

```py copy
Expand Down
13 changes: 3 additions & 10 deletions pages/guides/agents/advanced/name-service.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -29,17 +29,17 @@ First of all, we need to create 2 Python scripts for our two agents using the fo
echo. > bob.py
```
</DocsCode>

<DocsCode ubuntu={true}>
```py copy filename="ubuntu"
touch bob.py
```
</DocsCode>

</CodeGroup>

Alice:

<CodeGroup hasCopy isOSFile>
<DocsCode mac={true}>
```py copy filename="mac"
Expand Down Expand Up @@ -149,19 +149,16 @@ from uagents.network import get_faucet, get_name_service_contract

# NOTE: Run agent1.py before running agent2.py


class Message(Model):
message: str


bob = Agent(
name="bob-0",
seed="agent bob-0 secret phrase",
port=8001,
endpoint=["http://localhost:8001/submit"],
)


my_wallet = LocalWallet.from_unsafe_seed("registration test wallet")
name_service_contract = get_name_service_contract(test=True)
faucet = get_faucet()
Expand All @@ -170,19 +167,16 @@ DOMAIN = "example.agent"

faucet.get_wealth(my_wallet.address())


@bob.on_event("startup")
async def register_agent_name(ctx: Context):
await name_service_contract.register(
bob.ledger, my_wallet, bob.address, bob.name, DOMAIN
)


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


if __name__ == "__main__":
bob.run()
```
Expand Down Expand Up @@ -263,7 +257,6 @@ 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."))


if __name__ == "__main__":
alice.run()
```
Expand Down
6 changes: 3 additions & 3 deletions pages/guides/agents/advanced/register-in-almanac.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -36,15 +36,15 @@ Make sure you have read the following resources before going on with this guide:
echo. > registration.py
```
</DocsCode>

<DocsCode ubuntu={true}>
```py copy filename="ubuntu"
touch registration.py
```
</DocsCode>

</CodeGroup>

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:

```py copy filename="registration.py"
Expand Down
Loading

0 comments on commit 03f98c4

Please sign in to comment.