GithubHelp home page GithubHelp logo

fetchai / uagents Goto Github PK

View Code? Open in Web Editor NEW
704.0 17.0 184.0 5.17 MB

A fast and lightweight framework for creating decentralized agents with ease.

License: Apache License 2.0

Python 95.28% CSS 1.16% JavaScript 3.47% Dockerfile 0.09%
agents ai ai-agents llm multi-agent-systems

uagents's Introduction

uAgents: AI Agent Framework

Official Website Unit Tests GitHub Repo stars Twitter Follow

uAgents is a library developed by Fetch.ai that allows for creating autonomous AI agents in Python. With simple and expressive decorators, you can have an agent that performs various tasks on a schedule or takes action on various events.

πŸš€ Features

  • πŸ€– Easy creation and management: Create any type of agent you can think of and put into code.
  • πŸ”— Connected: On startup, each agent automatically joins the fast growing network of uAgents by registering on the Almanac, a smart contract deployed on the Fetch.ai blockchain.
  • πŸ”’ Secure: uAgent messages and wallets are cryptographically secured, so their identities and assets are protected.

⚑ Quickstart

Installation

Get started with uAgents by installing it for Python 3.8 to 3.12:

pip install uagents

Running a Demo

Creating an Agent

Build your first uAgent using the following script:

from uagents import Agent, Context
alice = Agent(name="alice", seed="alice recovery phrase")

Include a seed parameter when creating an agent to set fixed addresses, or leave it out to generate random addresses each time.

Giving it a task

Give it a simple task, such as greeting:

@alice.on_interval(period=2.0)
async def say_hello(ctx: Context):
    ctx.logger.info(f'hello, my name is {ctx.name}')

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

Running the Agent

So far, your code should look like this:

from uagents import Agent, Context

alice = Agent(name="alice", seed="alice recovery phrase")

@alice.on_interval(period=2.0)
async def say_hello(ctx: Context):
    ctx.logger.info(f'hello, my name is {ctx.name}')

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

Run it using:

python agent.py

You should see the results in your terminal.

πŸ“– Documentation

Please see the official documentation for full setup instructions and advanced features.

🌱 Examples

The examples folder contains several examples of how to create and run various types of agents.

🌲 Integrations

The integrations folder contains examples that provide a more in depth use of the uAgents library.

Python Library

Go to the python folder for details on the Python uAgents library.

✨ Contributing

All contributions are welcome! Remember, contribution includes not only code, but any help with docs or issues raised by other developers. See our contribution guidelines for more details.

πŸ“„ Development Guidelines

Read our development guidelines to learn some useful tips related to development.

❓ Issues, Questions, and Discussions

We use GitHub Issues for tracking requests and bugs, and GitHub Discussions for general questions and discussion.

πŸ›‘ Disclaimer

This project, uAgents, is provided "as-is" without any warranty, express or implied. By using this software, you agree to assume all risks associated with its use, including but not limited to unexpected behavior, data loss, or any other issues that may arise. The developers and contributors of this project do not accept any responsibility or liability for any losses, damages, or other consequences that may occur as a result of using this

License

The uAgents project is licensed under Apache License 2.0.

uagents's People

Contributors

abhi141 avatar alejandro-morales avatar archento avatar bgoober avatar coderlktripathi avatar devjsc avatar dpdrabla avatar ejfitzgerald avatar felixnicolaebucsa avatar gaurav19908 avatar gautamgambhir97 avatar jrriehl avatar lrahmani avatar mariamina avatar missingno57 avatar prajnasaikia avatar pratrivedi avatar qati avatar rishankjhavar avatar sangramsam avatar vijaysharma815 avatar zmezei avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

uagents's Issues

Automate protocol manifest upload

When protocols are included, there should be an option to automatically upload their manifests to Agentverse. This could probably be on by default, but users could opt out by setting upload_manifests to False.

Feature: add support for handling json parsing errors

In agent.py:

            try:
                recovered = model_class.parse_raw(message)
            except ValidationError as ex:
                self._logger.warning(f"Unable to parse message: {ex}")
                continue

This piece of code swallows the error and ignores the message. It would be nice to be able to send back a message to the agent who sent the json with the pydantic parse error.

Upgrade storage for easier handling of model types

It would be better to add methods to allow easier storage and access of model types to avoid having to do things like this:

tables = {int(num): TableStatus(**status) for (num, status) in ctx.storage._data.items()}

Update registration interval to account for expiry block

Registration is currently done on a fixed time interval, but it would be better to query the expiry block and schedule the registration based on the estimated expiry.

Also, it should be possible to re-register even if you are already registered (to avoid gaps in registration).

Revise contract interactions to include agent address signature

We need to revise the contract to store records using the agent... address as the key rather than the native FET address. This means the register function will need to verify a signature to prove that the sender owns the agent... address.

The updated interface can be something like:

    Register {
        /// The record to be created or updated
        record: Record,
        signature: String,
        sequence: u64,
    },

where sequence is an incrementing integer that updates with each registration that the sender should sign.

uAgents: Name service updates

  • Update AlmanacResolver to support agent names
  • Move name service contract registration out from core agent code and into helper function

uAgents: docs improvements

  • Clarify endpoints / server ports / registration / bureau
  • Add explanation of remote agent usage (ngrok example)

Manifest field type issue

If the agent model has datetime field, in the manifest instead of having datetime as type, it is a string.

Cache registration contract object

Instead of creating this contract object each time it is accessed, it would be better to simply creat it once and then access it as needed.

uAgents: update and reorganize examples

  • Some of the examples can be updated (e.g. with on_event("startup"))
  • Also, we should restructure them a bit to avoid duplication and to introduce one concept at a time.

Use envelope session ID correctly

Specifically, every message that originates from a message handler should use the session ID of the incoming message if available.

There is no current event loop in thread 'ScriptRunner.scriptThread' Error

Moved from here: fetchai/cosmpy#360

i think asyncio.get_event_loop() method works within uagents module ?
and how to call asyncio.get_event_loop() function in uagents module?

class ASGIServer:
def init(
self,
port: int,
loop: asyncio.AbstractEventLoop,
queries: Dict[str, asyncio.Future],
logger: Optional[Logger] = None,
):
self._port = int(port)
self._loop = loop
self._queries = queries
self._logger = logger or get_logger("server")
self._server = None
there is no get method so sadly frowning
because of that, it conflicts to streamlit module
and i get the following error:

File "C:\Users\selcu\AppData\Local\Programs\Python\Python310\lib\asyncio\events.py", line 656, in get_event_loop
raise RuntimeError('There is no current event loop in thread %r.'
RuntimeError: There is no current event loop in thread 'ScriptRunner.scriptThread'.

I'm having a problem with agents initializing

Discussed in #171

Originally posted by Mrmichelerocha September 23, 2023
Hi, I'm using agents for my course completion work, making an extension to the BDI architecture widely used in multi-agents, and today I went to compile my agents and they gave the following problem:

Traceback (most recent call last):
   File "C:\Users\mggrl\Documents\ag-bdi_central\agent1.py", line 9, in <module>
     central = Create_agent.Central()
   File "C:\Users\mggrl\Documents\ag-bdi_central\aumanaque.py", line 39, in Central
     fund_agent_if_low(central.wallet.address())
   File "C:\Users\mggrl\Documents\ag-bdi_central\uAgents\src\uagents\setup.py", line 20, in fund_agent_if_low
     faucet.get_wealth(agent_address)
   File "C:\Users\mggrl\AppData\Local\pypoetry\Cache\virtualenvs\uagents-Hie5aemw-py3.9\lib\site-packages\cosmpy\aerial\faucet.py", line 154, in get_wealth
     raise RuntimeError(f"Failed to get wealth for {address}")
RuntimeError: Failed to get wealth for fetch1twvhcnk7tdr08vsree7z0phj244vhfzvqwm3a6

Can you give me a little help?

Exception/crash when connecting to an agent through browser

Problem:

It still sometimes happens that the endpoint of an agent (incl. /submit) is being opened in a browser which leads to the following observation and leaves the agent in a stale state (stops working)

ERROR:    Exception in ASGI application
Traceback (most recent call last):
  File "/usr/local/lib/python3.10/site-packages/uvicorn/protocols/http/h11_impl.py", line 407, in run_asgi
    result = await app(  # type: ignore[func-returns-value]
  File "/usr/local/lib/python3.10/site-packages/uvicorn/middleware/proxy_headers.py", line 78, in __call__
    return await self.app(scope, receive, send)
  File "/usr/local/lib/python3.10/site-packages/uagents/asgi.py", line 81, in __call__
    if b"application/json" not in headers[b"content-type"]:
KeyError: b'content-type'

We check in:

if scope["path"] != "/submit":
if the path is ending with /submit which is true most of the time if you know how to interact with an agent OR if you do some internal routing.
The internal routing is often the case when hosting an agent in the cloud or making it accessible through a web2 DNS service.

-> The browser by default may not add the content type property to the request, leading to a key error in:

if b"application/json" not in headers[b"content-type"]:

Proposal

This should be an easy fix to prevent the agent from crashing but I would like to start the discussion here if we would additionally give a standard feedback/response to the browser client that the agent is up and running, e.g. GET "/submit" -> 200, OK - Agent is running

uAgents: add protocol query

Add built-in support for querying which protocols an agent supports (i.e. what messages they can receive and send)

Long runing agent might run out of fund and fails to reregister

The common pattern of running the agent is to use fund_agent_if_low. If the funds are not low enough this won't do anything. If the agent runs for a long time, this might yield to running out of funds, thus registration is failing. This currently requires agents to be monitored and restarted if this is happening. Generic solution would be useful for this for many developers.

Add test cases for key functionality

We should probably have some test cases for:

ASGIServer:

  • proper handling of requests (sync vs async)
  • rejection of invalid requests

Protocol:

  • correct handling of signed vs unsigned messages

Agent:

  • protocol inclusion
  • registration
  • message queue

Failing to resolve agent address

In the agents sometime we fail to resolve agent address, it feels a bit probabilistic and not too common, but sometimes simply resolution is failing.

Feature: Add retry on failed delivery if multiple addresses of an agent are registered

Problem

We have the following scenario where an agent is either:

  • residing in an unstable network, or
  • sometimes crashes due to external factors (hardware faults, vserver restrictions)

while at the same time it needs to be available at all times.

Desired state

  • An agent A who tries to contact another agent B is given a list of endpoints.
    (which represent multiple instances of the same agent B)
  • Agent A chooses at random which endpoint to contact but instead of failing and stopping, retries all available endpoints first.
  • Each of these tries should be equipped with a timeout and a proper log message.
  • If none of the endpoints are available the agent should notify the user, log its state, and not raise exceptions.

Current state

At the moment we already have some of the required aspects implemented:

  • multiple agent instances can be spun up which have access to the same wallet (and therefore have the same address).
  • we can register multiple endpoints for one agent address within the almanac smart contract.
  • upon agent address resolution (query of the almanac) we are given a list of addresses to choose from.

For more information see the following figure and please ask questions if something needs more clarification.

redundancy_proposal

Update agentverse config and websocket usage

Replace websocket wss with https wherever we use this in the examples and docs. Also, replace mailbox= with agentverse= and make sure this still makes sense for the mailbox example.

Add simple geocoder

We should replace the address field in the cleaning demo with location which can be a string, interpretable by some geocoding tool like https://pypi.org/project/geopy/.

Then we can update the demo to include this in the availability check.

Ping protocol in uAgents

We need a ping protocol in uagents. This will allow AI Engine to filter out agents that are not active. Today AI Engine picks up any agent. This can include agents that are not reachable and active.

cc: @ejfitzgerald

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.