Skip to content

Commit

Permalink
feat(docs): update code blocks for local/hosted agent (#975)
Browse files Browse the repository at this point in the history
  • Loading branch information
gautamgambhir97 authored Oct 3, 2024
1 parent 89b0258 commit 575bb6e
Show file tree
Hide file tree
Showing 16 changed files with 1,408 additions and 53 deletions.
1 change: 1 addition & 0 deletions dictionaries/custom_dict.txt
Original file line number Diff line number Diff line change
Expand Up @@ -655,3 +655,4 @@ Agentic
GPT
codegroup
SenderAgent
uvicorn
123 changes: 95 additions & 28 deletions pages/examples/intermediate/agent-and-function-api.mdx
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { CodeGroup } from "../../../components/code"

# Agents and Functions Creation using APIs

## Introduction
Expand Down Expand Up @@ -26,48 +28,113 @@ This example provides details on how to create Agents and respective Agent Funct
- Open terminal and create a directory `agents` using `mkdir agents`.
- Create a python file `agent.py` in this directory and include the following sample script in the Python file.

```python copy filename = 'agent.py'
import requests
from ai_engine import UAgentResponse, UAgentResponseType
<CodeGroup hasCopy isLocalHostedFile>
```python copy filename="local-agent.py"
import requests
from ai_engine import UAgentResponse, UAgentResponseType


class Coordinates(Model):
location: str
class Coordinates(Model):
location: str


location_protocol = Protocol("Location Coordinates")
# First generate a secure seed phrase (e.g. https://pypi.org/project/mnemonic/)
SEED_PHRASE = "put_your_seed_phrase_here"

# Now go to https://agentverse.ai, register your agent in the Mailroom by providing the address you just copied.
# Then, copy the agent's mailbox key and insert it here below inline
AGENT_MAILBOX_KEY = "put_your_AGENT_MAILBOX_KEY_here"

async def location_coordinates(latitude, longitude):
url = "https://geocoding-by-api-ninjas.p.rapidapi.com/v1/reversegeocoding"
querystring = {"lat": latitude, "lon": longitude}
# Now your agent is ready to join the agentverse!
location_agent = Agent(
name="location_agent",
seed=SEED_PHRASE,
mailbox=f"{AGENT_MAILBOX_KEY}@https://agentverse.ai",
)

headers = {
"X-RapidAPI-Key": "YOUR_API_KEY",
"X-RapidAPI-Host": "geocoding-by-api-ninjas.p.rapidapi.com",
}
fund_agent_if_low(location_agent.wallet.address())

response = requests.get(url, headers=headers, params=querystring)
# Copy the address shown below
print(f"Your agent's address is: {location_agent.address}")

data = response.json()[0]["name"]
location_protocol = Protocol("Location Coordinates")

return data

async def location_coordinates(latitude, longitude):
url = "https://geocoding-by-api-ninjas.p.rapidapi.com/v1/reversegeocoding"
querystring = {"lat": latitude, "lon": longitude}

@location_protocol.on_message(model=Coordinates, replies=UAgentResponse)
async def location_coordinates_calculator(ctx: Context, sender: str, msg: Coordinates):
ctx.logger.info(msg.location)
latitude, longitude = map(str.strip, msg.location.split(","))
city = location_coordinates(latitude, longitude)
ctx.logger.info(city)
message = city
await ctx.send(
sender, UAgentResponse(message=message, type=UAgentResponseType.FINAL)
)
headers = {
"X-RapidAPI-Key": "YOUR_API_KEY",
"X-RapidAPI-Host": "geocoding-by-api-ninjas.p.rapidapi.com",
}

response = requests.get(url, headers=headers, params=querystring)

agent.include(location_protocol)
```
data = response.json()[0]["name"]

return data


@location_protocol.on_message(model=Coordinates, replies=UAgentResponse)
async def location_coordinates_calculator(ctx: Context, sender: str, msg: Coordinates):
ctx.logger.info(msg.location)
latitude, longitude = map(str.strip, msg.location.split(","))
city = location_coordinates(latitude, longitude)
ctx.logger.info(city)
message = city
await ctx.send(
sender, UAgentResponse(message=message, type=UAgentResponseType.FINAL)
)


location_agent.include(location_protocol)

location_agent.run()
```

```python copy filename="hosted-agent.py"
import requests
from ai_engine import UAgentResponse, UAgentResponseType


class Coordinates(Model):
location: str


location_protocol = Protocol("Location Coordinates")


async def location_coordinates(latitude, longitude):
url = "https://geocoding-by-api-ninjas.p.rapidapi.com/v1/reversegeocoding"
querystring = {"lat": latitude, "lon": longitude}

headers = {
"X-RapidAPI-Key": "YOUR_API_KEY",
"X-RapidAPI-Host": "geocoding-by-api-ninjas.p.rapidapi.com",
}

response = requests.get(url, headers=headers, params=querystring)

data = response.json()[0]["name"]

return data


@location_protocol.on_message(model=Coordinates, replies=UAgentResponse)
async def location_coordinates_calculator(ctx: Context, sender: str, msg: Coordinates):
ctx.logger.info(msg.location)
latitude, longitude = map(str.strip, msg.location.split(","))
city = location_coordinates(latitude, longitude)
ctx.logger.info(city)
message = city
await ctx.send(
sender, UAgentResponse(message=message, type=UAgentResponseType.FINAL)
)

agent.include(location_protocol)
```
</CodeGroup>

- Create a python file with name `agent_create.py`.

Expand Down
2 changes: 1 addition & 1 deletion pages/examples/intermediate/agents-interval-task.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ This example shows how to use the uAgents Framework library to set up an interva

### The agent

<CodeGroup isLocalHostedFile>
<CodeGroup hasCopy isLocalHostedFile>
```py copy filename="local-interval-task.py"
from uagents import Agent, Context

Expand Down
60 changes: 59 additions & 1 deletion pages/examples/intermediate/coin-toss.mdx
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { CodeGroup } from "../../../components/code"

# Register a coin toss agent as a Function

## Introduction
Expand Down Expand Up @@ -25,7 +27,62 @@ To enable this on [DeltaV ↗️](/concepts/ai-engine/deltav) you will need to c

### The agent

```python copy filename="agent.py"
<CodeGroup hasCopy isLocalHostedFile>

```python copy filename="local-agent.py"
import random
from uagents import Agent, Context, Model, Field, Protocol
from uagents.setup import fund_agent_if_low
from ai_engine import UAgentResponse, UAgentResponseType


class CoinToss(Model):
choice: str = Field(description="The choice. Must be heads or tails.")

# First generate a secure seed phrase (e.g. https://pypi.org/project/mnemonic/)
SEED_PHRASE = "put_your_seed_phrase_here"

# Now go to https://agentverse.ai, register your agent in the Mailroom by providing the address you just copied.
# Then, copy the agent's mailbox key and insert it here below inline
AGENT_MAILBOX_KEY = "put_your_AGENT_MAILBOX_KEY_here"

# Now your agent is ready to join the agentverse!
coin_toss_agent = Agent(
name="coin_toss_agent",
seed=SEED_PHRASE,
mailbox=f"{AGENT_MAILBOX_KEY}@https://agentverse.ai",
)

fund_agent_if_low(coin_toss_agent.wallet.address())

# Copy the address shown below
print(f"Your agent's address is: {coin_toss_agent.address}")

coin_toss_protocol = Protocol("CoinToss")


@coin_toss_protocol.on_message(model=CoinToss, replies={UAgentResponse})
async def toss_coin(ctx: Context, sender: str, msg: CoinToss):
random_number = random.randint(0, 1)
if random_number == 0:
coin_tossed = "heads"
else:
coin_tossed = "tails"
if coin_tossed == msg.choice:
message = "You won!"
else:
message = "You lost!"
await ctx.send(
sender, UAgentResponse(message=message, type=UAgentResponseType.FINAL)
)

coin_toss_agent.include(coin_toss_protocol, publish_manifest=True)

if __name__ == "__main__":
coin_toss_agent.run()
```

```python copy filename="hosted-agent.py"
import random
# third party modules used in this example
from uagents import Field
Expand Down Expand Up @@ -55,3 +112,4 @@ async def toss_coin(ctx: Context, sender: str, msg: CoinToss):

agent.include(coin_toss_protocol, publish_manifest=True)
```
</CodeGroup>
52 changes: 51 additions & 1 deletion pages/examples/intermediate/dice-roll.mdx
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { CodeGroup } from "../../../components/code"

# Register a dice roll agent as a Function

## Introduction
Expand Down Expand Up @@ -25,7 +27,54 @@ To enable this on [DeltaV ↗️](/concepts/ai-engine/deltav) you will need to c

### The agent

```py copy filename="agent.py"
<CodeGroup hasCopy isLocalHostedFile>
```py copy filename="local-agent.py"
import random
from uagents import Agent, Context, Model, Field, Protocol
from uagents.setup import fund_agent_if_low
from ai_engine import UAgentResponse, UAgentResponseType


class DiceRoll(Model):
num_rolls: int = Field(description="Number of rolls.")

# First generate a secure seed phrase (e.g. https://pypi.org/project/mnemonic/)
SEED_PHRASE = "put_your_seed_phrase_here"

# Now go to https://agentverse.ai, register your agent in the Mailroom by providing the address you just copied.
# Then, copy the agent's mailbox key and insert it here below inline
AGENT_MAILBOX_KEY = "put_your_AGENT_MAILBOX_KEY_here"

# Now your agent is ready to join the agentverse!
dice_roll_agent = Agent(
name="dice_roll_agent",
seed=SEED_PHRASE,
mailbox=f"{AGENT_MAILBOX_KEY}@https://agentverse.ai",
)

fund_agent_if_low(dice_roll_agent.wallet.address())

# Copy the address shown below
print(f"Your agent's address is: {dice_roll_agent.address}")

dice_roll_protocol = Protocol("DiceRoll")


@dice_roll_protocol.on_message(model=DiceRoll, replies={UAgentResponse})
async def roll_dice(ctx: Context, sender: str, msg: DiceRoll):
result = ", ".join([str(random.randint(1, 6)) for _ in range(msg.num_rolls)])
message = f"Dice roll results: {result}"
await ctx.send(
sender, UAgentResponse(message=message, type=UAgentResponseType.FINAL)
)

dice_roll_agent.include(dice_roll_protocol, publish_manifest=True)

if __name__ == "__main__":
dice_roll_agent.run()
```

```py copy filename="hosted-agent.py"
import random
# third party modules used in this example
from uagents import Field
Expand All @@ -48,3 +97,4 @@ async def roll_dice(ctx: Context, sender: str, msg: DiceRoll):

agent.include(dice_roll_protocol, publish_manifest=True)
```
</CodeGroup>
Loading

0 comments on commit 575bb6e

Please sign in to comment.