Skip to content

Commit

Permalink
feat: update other examples with toggle
Browse files Browse the repository at this point in the history
  • Loading branch information
gautamgambhir97 committed Oct 4, 2024
1 parent 03ecb55 commit 0b4dbb2
Show file tree
Hide file tree
Showing 22 changed files with 195 additions and 83 deletions.
27 changes: 24 additions & 3 deletions components/code.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ interface CodeBlockProps {
}

type CodeBoxProps = {
filename?: string;
filename?: string[];
dataLanguage?: string;
hasCopyCode?: boolean;
children?: React.ReactNode;
Expand Down Expand Up @@ -263,11 +263,14 @@ export const CustomPre: React.FC<CodeBoxProps> = ({
children,
isLocalHostedFile,
isOSFile,
filename,
}) => {
const [isCopied, setIsCopied] = useState(false);
const codeRef = useRef<HTMLDivElement>(null);

const [selectedType, setSelectedType] = useState(agentType[0].name);
const [selectedType, setSelectedType] = useState(
filename[0].includes("local") ? agentType[0].name : agentType[1].name,
);
const [selectedOS, setSelectedOS] = useState("windows");

const renderChild = () => {
Expand All @@ -279,6 +282,14 @@ export const CustomPre: React.FC<CodeBoxProps> = ({
});
};

const filteredAgentType =
isLocalHostedFile && filename.length == 2
? agentType
: agentType.filter(
(type) =>
type.label === (filename[0].includes("local") ? "local" : "hosted"),
);

const matchFilename = (filename: string): boolean => {
const regexMap = {
self_hosted: /local/i,
Expand Down Expand Up @@ -319,7 +330,7 @@ export const CustomPre: React.FC<CodeBoxProps> = ({
selectedOption={selectedType}
onOptionSelect={setSelectedType}
placeholder="Select Language"
options={agentType.map((item) => item.name)}
options={filteredAgentType.map((item) => item.name)}
/>
)}
{isOSFile && (
Expand Down Expand Up @@ -476,12 +487,22 @@ export const CodeGroup: React.FC<CodeGroupProps> = ({
isLocalHostedFile,
hasCopy,
}) => {
const renderFileName = () => {
return React.Children.map(children, (child) => {
if (React.isValidElement<CodeBlockProps>(child)) {
return child.props.filename;
}
return null;
});
};
const filename = renderFileName();
return (
<div className="nx-mt-3">
<CustomPre
isLocalHostedFile={isLocalHostedFile}
isOSFile={isOSFile}
hasCopyCode={hasCopy}
filename={filename}
>
{children}
</CustomPre>
Expand Down
13 changes: 10 additions & 3 deletions pages/examples/advanced/async-loops.mdx
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { CodeGroup } from "../../../components/code";

# Agent Asynchronous Loops

## Introduction
Expand All @@ -15,7 +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"
<CodeGroup hasCopy isLocalHostedFile>

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

Expand Down Expand Up @@ -63,12 +67,14 @@ In this example, we demonstrate how to use agents to communicate and exchange st
with contextlib.suppress(KeyboardInterrupt):
loop.run_forever()
```

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

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

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

from uagents import Agent, Bureau, Context
Expand Down Expand Up @@ -114,6 +120,7 @@ In this example, we demonstrate how to use agents to communicate and exchange st
# > when starting the external loop from the bureau
# bureau.run()
```
</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
58 changes: 31 additions & 27 deletions pages/examples/advanced/open-dialogue-chitchat.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -205,23 +205,25 @@ 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


<CodeGroup hasCopy isOSFile>
<CodeGroup hasCopy isOSFile>

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

</CodeGroup>
</CodeGroup>

<CodeGroup hasCopy isLocalHostedFile>

```python copy filename="agent1.py"
```python copy filename="local-agent1.py"
# Import required libraries
import json

Expand Down Expand Up @@ -335,28 +337,30 @@ The contents of this script are to be shared between the agents that want to use
print(f"Agent address: {agent.address}")
agent.run()
```
</CodeGroup>

- Create Python `agent2.py` script:

<CodeGroup hasCopy isOSFile>
<CodeGroup hasCopy isOSFile>

```py copy filename="mac"
touch agent2.py
```
```py copy filename="mac"
touch agent2.py
```

```py copy filename="windows"
echo. > agent2.py
```
```py copy filename="ubuntu"
touch agent2.py
```
```py copy filename="windows"
echo. > agent2.py
```

```py copy filename="ubuntu"
touch agent2.py
```


</CodeGroup>
</CodeGroup>

<CodeGroup hasCopy isLocalHostedFile>

```python copy filename="agent2.py"
```python copy filename="local-agent2.py"
"""Chit chat dialogue example"""

from asyncio import sleep
Expand Down Expand Up @@ -474,7 +478,7 @@ The contents of this script are to be shared between the agents that want to use
print(f"Agent address: {agent.address}")
agent.run()
```

</CodeGroup>
<Callout type="info" emoji="ℹ️">
Remember to update the agent's address to communicate to each other and seed phrase of own choice.
</Callout>
Expand Down
12 changes: 9 additions & 3 deletions pages/examples/advanced/predefined-dialogue-chitchat.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -240,8 +240,10 @@ 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`:

<CodeGroup hasCopy isLocalHostedFile>

```python copy filename="agent1.py"
```python copy filename="local-agent1.py"
# Import required libraries
import json

Expand Down Expand Up @@ -297,15 +299,17 @@ These two agents use the `hardcoded_chitchat` dialogue system to automate the in
agent.run() # Running agent

```

</CodeGroup>
### Setting up `agent2`

`agent2` is configured to automatically initiate a dialogue with `agent1` using the predefined dialogue system.

- Create a new Python script named `agent2.py` in the same directory.
- Paste the following code into `agent2.py`:

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

```python copy filename="local-agent2.py"
"""Chit chat dialogue example"""

from asyncio import sleep
Expand Down Expand Up @@ -362,6 +366,8 @@ These two agents use the `hardcoded_chitchat` dialogue system to automate the in
Remember to update the agent's address to communicate to each other and seed phrase of own choice.
</Callout>

</CodeGroup>

## Step 3: Run the Dialogue

- Start `agent1`:
Expand Down
15 changes: 12 additions & 3 deletions pages/examples/intermediate/agents-cleaning-demo.mdx
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { CodeGroup } from "../../../components/code"

# Cleaning service with Agents

## Introduction
Expand Down Expand Up @@ -27,7 +29,9 @@ The protocol ensures the provider's services are available to the user's locatio

Here is the full code:

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

```py copy filename="local-__init__.py"
from datetime import datetime, timedelta
from typing import List

Expand Down Expand Up @@ -140,6 +144,7 @@ async def handle_book_request(ctx: Context, sender: str, msg: ServiceBooking):
# send the response
await ctx.send(sender, BookingResponse(success=success))
```
</CodeGroup>

#### models.py

Expand Down Expand Up @@ -195,8 +200,9 @@ class Availability(models.Model):

### Agents
#### The Cleaner Agent
<CodeGroup hasCopy isLocalHostedFile>

```py copy filename="cleaner.py"
```py copy filename="local-cleaner.py"
from datetime import datetime

from protocols.cleaning import cleaning_proto
Expand Down Expand Up @@ -249,10 +255,12 @@ async def shutdown(_ctx: Context):
if __name__ == "__main__":
cleaner.run()
```
</CodeGroup>

#### User

```py copy filename="user.py"
<CodeGroup hasCopy isLocalHostedFile>
```py copy filename="local-user.py"
from datetime import datetime, timedelta

from protocols.cleaning import (
Expand Down Expand Up @@ -328,3 +336,4 @@ async def handle_book_response(ctx: Context, _sender: str, msg: BookingResponse)
if __name__ == "__main__":
user.run()
```
</CodeGroup>
5 changes: 4 additions & 1 deletion pages/examples/intermediate/agents-with-docker.mdx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { CodeGroup } from "../../../components/code"

# Running an Agent with Docker

Expand Down Expand Up @@ -42,8 +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.

<CodeGroup hasCopy isLocalHostedFile>

```py copy filename="agent.py"
```py copy filename="local-agent.py"

from uagents import Agent, Bureau, Context, Model

Expand Down Expand Up @@ -114,6 +116,7 @@ bureau.add(data_receiver)
if __name__ == "__main__":
bureau.run()
```
</CodeGroup>

### `Dockerfile`

Expand Down
8 changes: 6 additions & 2 deletions pages/examples/intermediate/broadcast.mdx
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { CodeGroup } from "../../../components/code"

# Agents broadcast

## Introduction
Expand All @@ -16,7 +18,9 @@ This file can be run on any platform supporting Python, with the necessary insta

### The script

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

```python copy filename="local-broadcast.py"
from uagents import Agent, Bureau, Context, Model, Protocol

# create agents
Expand Down Expand Up @@ -65,7 +69,7 @@ bureau.add(charles)
if __name__ == "__main__":
bureau.run()
```

</CodeGroup>
### Expected output

```
Expand Down
6 changes: 5 additions & 1 deletion pages/examples/intermediate/langchain-rag.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +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"

<CodeGroup hasCopy isLocalHostedFile>

```python copy filename="local-langchain_rag_agent.py"
import traceback
from uagents import Agent, Context, Protocol
import validators
Expand Down Expand Up @@ -269,6 +272,7 @@ if __name__ == "__main__":
agent.run()

```
</CodeGroup>

### Langchain user agent

Expand Down
8 changes: 6 additions & 2 deletions pages/examples/intermediate/local-agent-langchain.mdx
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { CodeGroup } from "../../../components/code"

# Locally Hosted Agent with LangChain Integration

## Introduction
Expand All @@ -22,7 +24,9 @@ This guide demonstrates how to run an agent on your own hardware or infrastructu

### The agent

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

```py copy filename="local-agent.py"
from langchain_community.tools import WikipediaQueryRun
from langchain_community.utilities import WikipediaAPIWrapper
from uagents.setup import fund_agent_if_low
Expand Down Expand Up @@ -66,7 +70,7 @@ async def load_dalle(ctx: Context, sender: str, msg: WikiReq):
WikiAgent.include(wiki_protocol, publish_manifest=True)
WikiAgent.run()
```

</CodeGroup>
### 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.
Loading

0 comments on commit 0b4dbb2

Please sign in to comment.