# packages

pkgId: df3a91d2fae41c26c0714334586fb81c16127b7d4a935ba0b6b3d307bd50339f
name: python-agent-watch
arch: src
version: 0.1.2
epoch: 0
release: 1
summary: An operational monitoring library for Crew AI applications.
url: https://github.com/AIAnytime/agent-watch
rpm_license: None
rpm_group: Unspecified
rpm_buildhost: localhost
location_href: Packages/python-agent-watch-0.1.2-1.src.rpm
checksum_type: sha256
description:
  **Agent Watch** is an operational monitoring library for Crew AI applications. It captures essential metrics such as token counts, costs, execution time, resource utilization, carbon emissions, and detailed logs. Additionally, it offers both textual and visual representations of the collected data via a Command-Line Interface (CLI) or a Streamlit dashboard.



  1. **Token Counting**
     - Total tokens
     - Input tokens
     - Output tokens

  2. **Cost Calculation**
     - Based on the token usage and model pricing

  3. **Performance Metrics**
     - Time taken for each call
     - CPU and memory consumption

  4. **Environmental Impact**
     - Estimated CO₂ emissions

  5. **Logging**
     - Comprehensive logs of all operations

  6. **Visualization**
     - CLI summaries
     - Streamlit dashboard for detailed insights



  You can install **Agent Watch** via `pip`. If not published to PyPI, install it locally:

  ```bash
  pip install .


pkgId: ba260d5e2a9c1c744b16978c47b9080038addd24001b2c197b960ba3590771ba
name: python-agent1c-metrics
arch: src
version: 0.4.4
epoch: 0
release: 1
summary: Get metrics from 1C srvinfo-content
url: https://gitlab.com/artplast-devops/agent1c-metrics
rpm_license: GPLv3+
rpm_group: Unspecified
rpm_buildhost: localhost
location_href: Packages/python-agent1c-metrics-0.4.4-1.src.rpm
checksum_type: sha256
description:
  Service for collecting metrics from 1C service files
  Version: 0.4.4





  ```
  pip install --upgrade agent1c_metrics
  ```



  ```
  python -m agent1c_metrics --reload
  ```





  ```
  pip install -e .
  ```



  ```
  bumpver update --patch
  ```



  ```
  poetry publish --build
  ```


pkgId: 01b7eaa8477861ada090407e8a7d24a8dbb86a1f1cdd5d36a5b9785eb4fbe9d1
name: python-agent360
arch: src
version: 1.3.0
epoch: 0
release: 1
summary: 360 agent
url: https://github.com/plesk/agent360
rpm_license: BSD-3-Clause
rpm_group: Unspecified
rpm_buildhost: localhost
location_href: Packages/python-agent360-1.3.0-1.src.rpm
checksum_type: sha256
description:
  360 Monitoring ([360monitoring.com](https://360monitoring.com)) is a web service that monitors and displays statistics of
  your server performance.

  Agent360 is OS agnostic software compatible with Python 3.7 and 3.8.
  It's been optimized to have low CPU consumption and comes with an
  extendable set of useful plugins.

  [![Build Status](https://github.com/plesk/agent360/workflows/Agent360-Test-And-Deploy/badge.svg?branch=master)](https://github.com/plesk/agent360/actions/workflows/test-and-deploy.yml)



  You can find the full documentation including the feature complete REST API at [docs.360monitoring.com](https://docs.360monitoring.com/docs) and [docs.360monitoring.com/docs/api](https://docs.360monitoring.com/docs/api).



  You can install the default configuration of Agent360 on all Linux distributions with just one click.

  1. Connect to your server via SSH.

  2. Find your USERTOKEN. To do so, [go to the servers page](https://monitoring.platform360.io/servers/overview) and then click the "Add server" button.

  3. Run the following command:

      ```sh
      wget -q -N https://monitoring.platform360.io/agent360.sh && bash agent360.sh USERTOKEN
      ```



  Download the [setup](https://github.com/plesk/agent360/releases) and install it on your Windows server.

  The installer will ask for your USERTOKEN which you can get [from the servers page](https://monitoring.platform360.io/servers/overview).



  To customize installation options, install Agent360 manually.

  1. Connect to your server via SSH.
  2. Run the following command, which differs depending on your server platform:

      - Debian GNU/Linux:

          ```sh
          apt-get install python3-devel python3-setuptools python3-pip
          pip3 install agent360
          wget -O /etc/agent360.ini https://monitoring.platform360.io/agent360.ini
          ```

      - Fedora/CentOS version 6 or earlier (python 2.7):

          ```sh
          yum install python-devel python-setuptools gcc
          easy_install agent360 netifaces psutil
          wget -O /etc/agent360.ini https://monitoring.platform360.io/agent360.ini
          ```

      - Fedora/CentOS version 7 and later (python 3):

          ```sh
          yum install python36-devel python36 gcc
          pip3 install agent360
          wget -O /etc/agent360.ini https://monitoring.platform360.io/agent360.ini
          ```

  3. Find your USERTOKEN. To do so, [go to the servers page](https://monitoring.platform360.io/servers/overview) and then click the "Add server" button. You need this to generate a serverid.

  4. Run the following command (USERTOKEN is the one you got during the previous step):

      ```sh
      agent360 hello USERTOKEN /etc/agent360-token.ini
      ```

  5. Create a systemd service at `/etc/systemd/system/agent360.service` by adding the following:

      ```ini
      [Unit]
      Description=Agent360

      [Service]
      ExecStart=/usr/local/bin/agent360
      User=agent360

      [Install]
      WantedBy=multi-user.target
      ```

  6. Run the following command:

      ```sh
      chmod 644 /etc/systemd/system/agent360.service
      systemctl daemon-reload
      systemctl enable agent360
      systemctl start agent360
      ```



  Prerequisite: [InnoSetup](https://jrsoftware.org/isdl.php) is used as the installer, build script assumes that it is installed in the default location.

  Run `php windows/build.php` to create setup file.


pkgId: 5a139921efcad09f4d7606bcc74d12639c1d831e8138ce870a7c23d2a0e607ca
name: python-agent360
arch: src
version: 1.3.1
epoch: 0
release: 1
summary: 360 agent
url: https://github.com/plesk/agent360
rpm_license: BSD-3-Clause
rpm_group: Unspecified
rpm_buildhost: localhost
location_href: Packages/python-agent360-1.3.1-1.src.rpm
checksum_type: sha256
description:
  360 Monitoring ([360monitoring.com](https://360monitoring.com)) is a web service that monitors and displays statistics of
  your server performance.

  Agent360 is OS agnostic software compatible with Python 3.7 and 3.8.
  It's been optimized to have low CPU consumption and comes with an
  extendable set of useful plugins.

  [![Build Status](https://github.com/plesk/agent360/workflows/Agent360-Test-And-Deploy/badge.svg?branch=master)](https://github.com/plesk/agent360/actions/workflows/test-and-deploy.yml)



  You can find the full documentation including the feature complete REST API at [docs.360monitoring.com](https://docs.360monitoring.com/docs) and [docs.360monitoring.com/docs/api](https://docs.360monitoring.com/docs/api).



  You can install the default configuration of Agent360 on all Linux distributions with just one click.

  1. Connect to your server via SSH.

  2. Find your USERTOKEN. To do so, [go to the servers page](https://monitoring.platform360.io/servers/overview) and then click the "Add server" button.

  3. Run the following command:

      ```sh
      wget -q -N https://monitoring.platform360.io/agent360.sh && bash agent360.sh USERTOKEN
      ```



  Download the [setup](https://github.com/plesk/agent360/releases) and install it on your Windows server.

  The installer will ask for your USERTOKEN which you can get [from the servers page](https://monitoring.platform360.io/servers/overview).



  To customize installation options, install Agent360 manually.

  1. Connect to your server via SSH.
  2. Run the following command, which differs depending on your server platform:

      - Debian GNU/Linux:

          ```sh
          apt-get install python3-dev python3-setuptools python3-pip
          pip3 install agent360
          wget -O /etc/agent360.ini https://monitoring.platform360.io/agent360.ini
          ```

      - Fedora/CentOS version 6 or earlier (python 2.7):

          ```sh
          yum install python-devel python-setuptools gcc
          easy_install agent360 netifaces psutil
          wget -O /etc/agent360.ini https://monitoring.platform360.io/agent360.ini
          ```

      - Fedora/CentOS version 7 and later (python 3):

          ```sh
          yum install python36-devel python36 gcc
          pip3 install agent360
          wget -O /etc/agent360.ini https://monitoring.platform360.io/agent360.ini
          ```

  3. Find your USERTOKEN. To do so, [go to the servers page](https://monitoring.platform360.io/servers/overview) and then click the "Add server" button. You need this to generate a serverid.

  4. Run the following command (USERTOKEN is the one you got during the previous step):

      ```sh
      agent360 hello USERTOKEN /etc/agent360-token.ini
      ```

  5. Create a systemd service at `/etc/systemd/system/agent360.service` by adding the following:

      ```ini
      [Unit]
      Description=Agent360

      [Service]
      ExecStart=/usr/local/bin/agent360
      User=agent360

      [Install]
      WantedBy=multi-user.target
      ```

  6. Run the following command:

      ```sh
      chmod 644 /etc/systemd/system/agent360.service
      systemctl daemon-reload
      systemctl enable agent360
      systemctl start agent360
      ```



  Prerequisite: [InnoSetup](https://jrsoftware.org/isdl.php) is used as the installer, build script assumes that it is installed in the default location.

  Run `php windows/build.php` to create setup file.


pkgId: 7343bfab66192b3b17f6c742f601d75185b1be8912a3a379d139b14b26f39cab
name: python-agentMET4FOF
arch: src
version: 0.13.3
epoch: 0
release: 1
url: https://github.com/Met4FoF/agentMET4FOF
rpm_license: None
rpm_group: Unspecified
rpm_buildhost: localhost
location_href: Packages/python-agentMET4FOF-0.13.3-1.src.rpm
checksum_type: sha256
summary:
  A software package for the integration of metrological input into an agent-based system for the consideration of measurement uncertainty in current industrial manufacturing processes.

description:
  <img src="https://www.ptb.de/empir2018/fileadmin/documents/empir/Met4FoF/images/AM4FoF_Logo.svg" alt="agentMET4FOF logo">
  <p align="center">
    <!-- CircleCI Tests -->
    <a href="https://circleci.com/gh/Met4FoF/agentMET4FOF"><img alt="CircleCI pipeline
      status badge" src="https://circleci.com/gh/Met4FoF/agentMET4FOF.svg?style=shield"></a>
    <!-- ReadTheDocs Documentation -->
    <a href="https://agentmet4fof.readthedocs.io/">
      <img src="https://readthedocs.org/projects/agentmet4fof/badge/?version=latest" alt="ReadTheDocs badge">
    </a>
    <!-- CodeCov(erage) -->
    <a href="https://codecov.io/gh/Met4FoF/agentMET4FOF">
      <img src="https://codecov.io/gh/Met4FoF/agentMET4FOF/branch/develop/graph/badge.svg?token=ofAPdSudLy" alt="CodeCov badge"/>
    </a>
    <!-- PyPI Version -->
    <a href="https://pypi.org/project/agentmet4fof">
      <img src="https://img.shields.io/pypi/v/agentmet4fof.svg?label=release&color=blue&style=flat-square" alt="pypi">
    </a>
    <!-- PyPI License -->
    <a href="https://www.gnu.org/licenses/lgpl-3.0.en.html">
      <img alt="PyPI - license badge"
      src="https://img.shields.io/pypi/l/agentMET4FOF?color=bright">
    </a>
    <!-- Zenodo DOI -->
    <a href="https://doi.org/10.5281/zenodo.4560343">
      <img src="https://zenodo.org/badge/DOI/10.5281/zenodo.4560343.svg" alt="DOI"></a>
    <!-- Contributor Covenant -->
    <a href="https://github.com/Met4FoF/agentMET4FOF/blob/develop/CODE_OF_CONDUCT.md">
      <img src="https://img.shields.io/badge/Contributor%20Covenant-2.0-4baaaa.svg" alt="Contributor Covenant"></a>
    <!-- Docker Hub -->
    <a href="https://hub.docker.com/r/met4fof/agentmet4fof">
      <img src="https://img.shields.io/docker/pulls/met4fof/agentmet4fof.svg" alt="Docker Hub badge"></a>
  </p>



  <p align="justify">
  agentMET4FOF is an implementation of a multi-agent system for agent-based
  analysis and processing of both static data sets and data streams with IIoT
  applications in mind. More on the motivation that drives the project can be found
  in the section <!--suppress HtmlUnknownAnchorTarget --><a href="#about">About</a>.
  </p>



  - [FOSS project](#contributing)
  - allows to
    - quickly set up and run a [metrologically enabled multi-agent system](#about)
    - [handle both static data sets and online data streams](#tutorials)
    - [consider measurement uncertainties as well as metadata with the provided message system](#tutorials)
  - [installable as a Python package or ready-to-deploy Docker image](#installation)
  - comes bundled with [several introductary and advanced tutorials](#tutorials)
  - accompanied by [several use cases with close-to-industry IIoT applications in
    our GitHub organisation](https://github.com/Met4FoF?q=agentMET4FOF&type=&language=&sort=)
  - comprehensive and ever-growing [documentation](#documentation-and-screencasts)



  - [💫 Quickstart](#quickstart)
  - [💬 About](#about)
  - [📈 The agentMET4FOF dashboard](#the-agentmet4fof-dashboard)
  - [🤓 Tutorials](#tutorials)
  - [📖 Documentation and screencasts](#documentation-and-screencasts)
  - [💻 Installation](#installation)
  - [🐝 Contributing](#contributing)
  - [💨 Coming soon](#coming-soon)
  - [🖋 Citation](#citation)
  - [💎 Acknowledgement](#acknowledgement)
  - [⚠ Disclaimer](#disclaimer)
  - [© License](#license)



  agentMET4FOF comes bundled with several [tutorials](#tutorials) to get you started
  as quick as possible. In your Python console execute the following to run the first
  tutorial.

  ```python
  >>> from agentMET4FOF_tutorials.tutorial_1_generator_agent import demonstrate_generator_agent_use
  >>> generator_agent_network = demonstrate_generator_agent_use()
  ```

  ```shell
  Starting NameServer...
  Broadcast server running on 0.0.0.0:9091
  NS running on 127.0.0.1:3333 (127.0.0.1)
  URI = PYRO:Pyro.NameServer@127.0.0.1:3333

  |----------------------------------------------------------|
  |                                                          |
  | Your agent network is starting up. Open your browser and |
  | visit the agentMET4FOF dashboard on http://0.0.0.0:8050/ |
  |                                                          |
  |----------------------------------------------------------|

  INFO [2021-02-05 18:12:52.277759] (SineGeneratorAgent_1): INITIALIZED
  INFO [2021-02-05 18:12:52.302862] (MonitorAgent_1): INITIALIZED
  [2021-02-05 18:12:52.324078] (SineGeneratorAgent_1): Connected output module: MonitorAgent_1
  SET STATE:   Running
  [...]
  ```
  ```python
  >>> generator_agent_network.shutdown()
  0
  NS shut down.
  ```




  <p align="justify">
  Sensor deployments in industrial applications usually form networks in all sorts of
  environments. This requires a flexible framework for the implementation of the
  corresponding data analysis. An excellent way to represent such networks is a
  multi-agent system (MAS), where independent software modules (agents) encapsulate
  properties and functionalities. agentMET4FOF is an interactive and flexible open-source
  implementation of such a MAS. The software engineering process is driven by several
  industry-oriented use cases with the aim of enabling IIoT applications. This leads
  to a framework that is specialized in representing heterogeneous sensor networks.
  </p>
  <p align="justify">
  A special emphasis is put on supporting metrological treatment of sensor streaming
  data. This includes the consideration of measurement uncertainties during data analysis
  and processing as well as propagating metadata alongside the data itself.
  </p>
  <p align="justify">
  One of the many questions that drive us in the project is:
  </p>
  <p align="justify">
    <blockquote>
    How can metrological input be incorporated into an agent-based system for addressing
    uncertainty of machine learning in future manufacturing?
    </blockquote>



  Some notable features of agentMET4FOF include :

  - Modular agent classes for metrological data streams and analytics
  - A built-in buffering mechanism to decouple transmission, processing and visualization
    of data
  - Easy connection among software agents to send and receive data
  - Choose backends between:
    - [_Osbrain_](https://osbrain.readthedocs.io/en/stable/) for simulating as well as
      handling real distributed systems running Python connected via a TCP network, and
    - [_Mesa_](https://mesa.readthedocs.io/en/stable/) for local simulations of
      distributed systems, debugging and more high-performance execution
  - Interactive and customisable dashboard from the get-go to:
    - Visualize and change agent-network topologies
    - Visualize groups of cooperative agents as _Coalitions_
    - View and change the agents' parameters
    - View the agents' outputs as plotly or matplotlib plots or generate and embed your
      own images
  - Generic streams and agents that can be used as starting points in simulations
    - A sine generator with an associated agent
    - A generator for a sine signal with jitter dynamically or with fixed length
    - A white noise agent
    - A metrologically enabled sine generator agent which also handles measurement uncertainties



  agentMET4FOF comes bundled with our so called _dashboard_. It is an optional component
  of every agent network and provides a web browser based view. You can
  observe the state of your agents, modify the connections between them and even add
  more pre-made agents to your network all during run-time. The address to your
  dashboard is printed to the console on every launch of an agent network.

  The following image is close to what you will find in your browser on execution of
  tutorial 2. For details on the tutorials visit our
  [video tutorial series](#screencast-series).

  ![](https://raw.githubusercontent.com/Met4FoF/agentMET4FOF/develop/docs/screenshot_met4fof.png)



  As mentioned above, agentMET4FOF comes bundled with several [tutorials
  ](https://agentmet4fof.readthedocs.io/en/latest/tutorials.html) to
  get you started as quick as possible. You will find tutorials on how to set up:

  - [a simple pipeline to plot a signal](https://agentmet4fof.readthedocs.io/en/latest/agentMET4FOF_tutorials/tutorial_1_generator_agent.html)
  - [a simple pipeline with signal postprocessing](https://agentmet4fof.readthedocs.io/en/latest/agentMET4FOF_tutorials/tutorial_2_math_agent.html)
  - [an advanced pipeline with multichannel signals](https://agentmet4fof.readthedocs.io/en/latest/agentMET4FOF_tutorials/tutorial_3_multi_channel.html)
  - [a simple metrological datastream](https://agentmet4fof.readthedocs.io/en/latest/agentMET4FOF_tutorials/tutorial_4_metrological_streams.html)
  - [pipelines to determine redundancy in sensor networks](https://agentmet4fof.readthedocs.io/en/latest/tutorials.html#working-with-signals-carrying-redundant-information)
  - [a pipeline to reduce noise and jitter in sensor readings](https://agentmet4fof.readthedocs.io/en/latest/tutorials.html#reducing-noise-and-jitter-in-signals)

  … and [more](https://agentmet4fof.readthedocs.io/en/latest/tutorials.html)!



  Extended
  [documentation can be found on ReadTheDocs](https://agentmet4fof.readthedocs.io).



  Additionally, we provide some
  [screencasts based on agentMET4FOF 0.4.1 on the project homepage
  ](https://www.ptb.de/empir2018/met4fof/information-communication/video-portal/)
  in the section _Tutorials for the multi-agent system agentMET4FOF_.
  You can self-register on the linked page and get started immediately. The video series
  begins with our motivation for creating agentMET4FOF, guide you through the
  installation of Python and other recommended software until you execute the tutorials
  on your machine.



  In an early development stage we held a live online tutorial based on
  [agentMET4FOF 0.1.0](https://github.com/Met4FoF/agentMET4FOF/releases/0.1.0/)
  which you can [download](https://github.com/Met4FoF/agentMET4FOF/releases/download/0.1.0/Met4FoF.MAS.webinar.mp4).

  If questions arise, or you feel something is missing, reach out to
  [us](https://github.com/Met4FoF/agentMET4FOF/graphs/contributors).



  There are different ways to run agentMET4FOF. Either:

  1. you [install Python](https://www.python.org/downloads/) and our package
     [agentMET4FOF](https://pypi.org/project/agentMET4FOF/) in a virtual Python
     environment on your computer, or
  2. you [install Docker](https://docs.docker.com/get-docker/), [start agentMET4FOF in
     a container](https://agentmet4fof.readthedocs.io/en/latest/INSTALL.html#start-a-container-from-the-image)
     and [visit the Jupyter Notebook server and the agentMET4FOF dashboard directly in
     your browser](https://agentmet4fof.readthedocs.io/en/latest/INSTALL.html#start-a-container-from-the-image-for-local-use)
     or even [deploy it over a proper webserver](https://agentmet4fof.readthedocs.io/en/latest/INSTALL.html#deploy-the-containerized-agents-via-a-webserver).

  In the [video tutorials series](#screencast-series)
  we guide you through every step of option 1. More detailed instructions on both
  options you can find in the [installation
  section of the docs](https://agentmet4fof.readthedocs.io/en/latest/INSTALL.html).



  Whenever you are involved with agentMET4FOF, please respect our [Code of Conduct
  ](https://github.com/Met4FoF/agentMET4FOF/blob/develop/CODE_OF_CONDUCT.md).
  If you want to contribute back to the project, after reading our Code of Conduct,
  take a look at our open developments in the [project board
  ](https://github.com/Met4FoF/agentMET4FOF/projects/1), [pull requests
  ](https://github.com/Met4FoF/agentMET4FOF/pulls) and search [the issues
  ](https://github.com/Met4FoF/agentMET4FOF/issues). If you find something similar to
  your ideas or troubles, let us know by leaving a comment or remark. If you have
  something new to tell us, feel free to open a feature request or bug report in the
  issues. If you want to contribute code or improve our documentation, please check our
  [contributing guide](https://agentmet4fof.readthedocs.io/en/latest/CONTRIBUTING.html).



  - Improved handling of metadata
  - More advanced signal processing

  For a comprehensive overview of current development activities and upcoming tasks,
  take a look at the [project board](https://github.com/Met4FoF/agentMET4FOF/projects/1),
  [issues](https://github.com/Met4FoF/agentMET4FOF/issues) and
  [pull requests](https://github.com/Met4FoF/agentMET4FOF/pulls).



  If you publish results obtained with the help of agentMET4FOF, please cite the linked
  [![](https://zenodo.org/badge/DOI/10.5281/zenodo.4560343.svg)
  ](https://doi.org/10.5281/zenodo.4560343).



  This work was part of the Joint Research Project [Metrology for the Factory of the
  Future (Met4FoF), project number 17IND12](https://www.ptb.de/empir2018/met4fof/home/)
  of the European Metrology Programme for Innovation and Research (EMPIR). The
  [EMPIR](http://msu.euramet.org) is jointly funded by the EMPIR participating
  countries within EURAMET and the European Union.



  This software is developed as a joint effort of several project partners namely:

  - [Institute for Manufacturing of the University of Cambridge (IfM)
    ](https://www.ifm.eng.cam.ac.uk/)
  - [Physikalisch-Technische Bundesanstalt (PTB)](https://www.ptb.de/)
  - [Van Swinden Laboratory (VSL)](https://www.vsl.nl/en/)
  - [National Physics Laboratory (NPL)](https://www.npl.co.uk/)

  under the lead of IfM. The software is made available "as is" free of cost. The
  authors and their institutions assume no responsibility whatsoever for its use by
  other parties, and makes no guarantees, expressed or implied, about its quality,
  reliability, safety, suitability or any other characteristic. In no event will the
  authors be liable for any direct, indirect or consequential damage arising in
  connection with the use of this software.



  agentMET4FOF is distributed under the
  [LGPLv3 license](https://github.com/Met4FoF/agentMET4FOF/blob/develop/license.md).


pkgId: 2ceac1ade9f4064325d53bfbe8ffddfd4c9634c12b0234920ff4518f51b5c3a5
name: python-agentUniverse
arch: src
version: 0.0.13
epoch: 0
release: 1
url: https://github.com/alipay/agentUniverse
rpm_license: None
rpm_group: Unspecified
rpm_buildhost: localhost
location_href: Packages/python-agentUniverse-0.0.13-1.src.rpm
checksum_type: sha256
summary:
  agentUniverse is a framework for developing applications powered by multi-agent base on large language model.

description:
  agentUniverse is a framework for developing applications powered by multi-agent base on large language model.  It provides all the essential components for building a single agent, and a multi-agent collaboration mechanism which  serves as a pattern factory that allowing developers to buid and customize multi-agent collaboration patterns. With this framework,  developers can easily construct multi-agent applications, and share the pattern practices from different technical  and business fields.

  The framework will come with serveral pre-install multi-agent collaboration patterns which have been proven effective in real business scenarios, and will continue to be enriched in the future. Patterns that are currently about to be released include:

  - PEER pattern：
  This pattern utilizes four distinct agent roles: Plan, Execute, Express, and Review, to achieve a multi-step breakdown and sequential execution of a complex task. It also performs autonomous iteration based on evaluative feedback which enhancing performance in reasoning and analytical tasks.


  - DOE pattern：
  This pattern consists of three agents: Data-fining agent, which is designed to solve data-intensive and high-computational-precision task; Opinion-inject agent, which combines the data results from first agent and the expert opinions which are pre-collected and structured; the third agent, Express agent generates the final result base on given document type and language style.

  More patterns are coming soon...


pkgId: 89b506ca5b8b3de6cb20753fd3a845d9c2345366c99eaaa54854410c8f3b17ff
name: python-agenta
arch: src
version: 0.25.3
epoch: 0
release: 1
summary: The SDK for agenta is an open-source LLMOps platform.
url: https://agenta.ai
rpm_license: None
rpm_group: Unspecified
rpm_buildhost: localhost
location_href: Packages/python-agenta-0.25.3-1.src.rpm
checksum_type: sha256
description:
  <h3 align="center">
    <a href="#quick-start"><b>Quick Start</b></a> &bull;
    <a href="#features"><b>Features</b></a> &bull;
    <a href="https://docs.agenta.ai"><b>Documentation</b></a> &bull;
    <a href="#enterprise-support"><b>Enterprise</b></a> &bull;
    <a href="https://github.com/orgs/Agenta-AI/projects/13"><b>Roadmap</b></a> &bull;
    <a href="https://join.slack.com/t/agenta-hq/shared_invite/zt-1zsafop5i-Y7~ZySbhRZvKVPV5DO_7IA"><b>Join Our Slack</b></a> &bull;
    <a href="#contributing"><b>Contributing</b></a>


pkgId: ea9f14c4d699646d665c72eb9cf0cf8f20cc2a36af237a647d4a30c5e3a5c105
name: python-agentarchives
arch: src
version: 0.9.0
epoch: 0
release: 1
summary: Clients to retrieve, add, and modify records from archival management systems.
url: https://pypi.org/project/agentarchives/
rpm_group: Unspecified
rpm_buildhost: localhost
location_href: Packages/python-agentarchives-0.9.0-1.src.rpm
checksum_type: sha256
description:
  [![PyPI version](https://img.shields.io/pypi/v/agentarchives.svg)](https://pypi.python.org/pypi/agentarchives)
  [![GitHub CI](https://github.com/artefactual-labs/agentarchives/actions/workflows/test.yml/badge.svg)](https://github.com/artefactual-labs/agentarchives/actions/workflows/test.yml)
  [![codecov](https://codecov.io/gh/artefactual-labs/agentarchives/branch/master/graph/badge.svg?token=rNmMA59AqJ)](https://codecov.io/gh/artefactual-labs/agentarchives)



  Clients to retrieve, add, and modify records from archival management systems.



  Agentarchives is on [PyPI](https://pypi.python.org/pypi/agentarchives)!

  `pip install agentarchives`

  Or you can install it directly from git

  `pip install git+https://github.com/artefactual-labs/agentarchives.git`


  Agentarchvies depends on the [mysqlclient](https://pypi.org/project/mysqlclient/) package which has a [bug](https://bugs.mysql.com/bug.php?id=86971) which can possibly fail an install when using homebrew on MacOs computers. A solution suggested on the mysqlclient site is to change `mysql_config` on or about line 112:

  ```

  libs="-L$pkglibdir"
  libs="$libs -l "
  ```

  to

  ```

  libs="-L$pkglibdir"
  libs="$libs -lmysqlclient -lssl -lcrypto"
  ```

  See also this [blog](https://medium.com/@MrWeeble/homebrew-on-mac-and-pythons-mysqlclient-ea44fa300e70).



  This library can be used to interact with [Archivists Toolkit](http://archiviststoolkit.org/),
  [ArchivesSpace](http://archivesspace.org/), and [Access To Memory (AtoM)](https://www.accesstomemory.org).



  First, you need to import the module in your Python script:

  ```python
  from agentarchives import archivesspace
  ```

  Then, initiate a new client, passing in the URL, user name, password, port and repository for your AS instance:

  ```python
  client = archivesspace.ArchivesSpaceClient('http://localhost', 'admin', 'admin', 8089, 2)
  ```

  Using your client, call one of the included functions (documented in `client.py`). For example, the following:

      $ resource = client.get_record('/repositories/2/resources/1')
      $ print resource

  will return:

  ```json
  {
      "classifications": [],
      "create_time": "2015-11-17T00:23:19Z",
      "created_by": "admin",
      "dates": [
          {
              "create_time": "2015-11-17T00:23:19Z",
              "created_by": "admin",
              "date_type": "bulk",
              "expression": "maybe 1999",
              "jsonmodel_type": "date",
              "label": "creation",
              "last_modified_by": "admin",
              "lock_version": 0,
              "system_mtime": "2015-11-17T00:23:19Z",
              "user_mtime": "2015-11-17T00:23:19Z"
          }
      ],
      "deaccessions": [],
      "extents": [
          {
              "create_time": "2015-11-17T00:23:19Z",
              "created_by": "admin",
              "extent_type": "cassettes",
              "jsonmodel_type": "extent",
              "last_modified_by": "admin",
              "lock_version": 0,
              "number": "1",
              "portion": "whole",
              "system_mtime": "2015-11-17T00:23:19Z",
              "user_mtime": "2015-11-17T00:23:19Z"
          }
      ],
      "external_documents": [],
      "external_ids": [],
      "id_0": "blah",
      "instances": [],
      "jsonmodel_type": "resource",
      "language": "aar",
      "last_modified_by": "admin",
      "level": "collection",
      "linked_agents": [],
      "linked_events": [],
      "lock_version": 0,
      "notes": [],
      "publish": false,
      "related_accessions": [],
      "repository": {
          "ref": "/repositories/2"
      },
      "restrictions": false,
      "revision_statements": [],
      "rights_statements": [],
      "subjects": [],
      "suppressed": false,
      "system_mtime": "2015-11-17T00:23:19   Z",
      "title": "blah",
      "tree": {
          "ref": "/repositories/2/resources/1/tree"
      },
      "uri": "/repositories/2/resources/1",
      "user_mtime": "2015-11-17T00:23:19   Z"
  }
  ```



  First, you need to import the module in your Python script:

  ```python
  from agentarchives import atom
  ```

  Then, initiate a new client, passing in the URL, REST API access token, password, and port for your AtoM instance:

  ```python
  client = atom.AtomClient('http://localhost', '68405800c6612599', 80)
  ```

  Using your client, call one of the included functions (documented in `client.py`). For example, the following:

      $ resource = client.get_record('test-fonds')
      $ print resource

  Will return:

  ```json
  {
      "dates": [
          {
              "begin": "2014-01-01",
              "end": "2015-01-01",
              "type": "Creation"
          }
      ],
      "level_of_description": "Fonds",
      "notes": [
          {
              "content": "Note content",
              "type": "general"
          }
      ],
      "publication_status": "Draft",
      "reference_code": "F2",
      "title": "Test fonds"
  }
  ```

  Current AtoM client limitations (versus the ArchivesSpace client):
  * Identifier wildcard search not supported
  * Creation of multiple notes not supported
  * Nested digital objects not supported
  * The ability to add/list notes with no content isn't supported

rpm_license:
  GNU AFFERO GENERAL PUBLIC LICENSE Version 3, 19 November 2007  Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.  Preamble  The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software.  The licenses for most software and other practical works are designed to take away your freedom to share and change the works.  By contrast, our General Public Licenses are intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users.  When we speak of free software, we are referring to freedom, not price.  Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.  Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software.  A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate.  Many developers of free software are heartened and encouraged by the resulting cooperation.  However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public.  The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community.  It requires the operator of a network server to provide the source code of the modified version running there to the users of that server.  Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version.  An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals.  This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license.  The precise terms and conditions for copying, distribution and modification follow.  TERMS AND CONDITIONS  0. Definitions.  "This License" refers to version 3 of the GNU Affero General Public License.  "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.  "The Program" refers to any copyrightable work licensed under this License.  Each licensee is addressed as "you".  "Licensees" and "recipients" may be individuals or organizations.  To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy.  The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work.  A "covered work" means either the unmodified Program or a work based on the Program.  To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy.  Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.  To "convey" a work means any kind of propagation that enables other parties to make or receive copies.  Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.  An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License.  If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.  1. Source Code.  The "source code" for a work means the preferred form of the work for making modifications to it.  "Object code" means any non-source form of a work.  A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.  The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form.  A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.  The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities.  However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work.  For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work.  The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.  The Corresponding Source for a work in source code form is that same work.  2. Basic Permissions.  All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met.  This License explicitly affirms your unlimited permission to run the unmodified Program.  The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work.  This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.  You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force.  You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright.  Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.  Conveying under any other circumstances is permitted solely under the conditions stated below.  Sublicensing is not allowed; section 10 makes it unnecessary.  3. Protecting Users' Legal Rights From Anti-Circumvention Law.  No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.  When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.  4. Conveying Verbatim Copies.  You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.  You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.  5. Conveying Modified Source Versions.  You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:  a) The work must carry prominent notices stating that you modified it, and giving a relevant date.  b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7.  This requirement modifies the requirement in section 4 to "keep intact all notices".  c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy.  This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged.  This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.  d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.  A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit.  Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.  6. Conveying Non-Source Forms.  You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:  a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.  b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.  c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source.  This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.  d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge.  You need not require recipients to copy the Corresponding Source along with the object code.  If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source.  Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.  e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.  A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.  A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling.  In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage.  For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product.  A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.  "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source.  The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.  If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information.  But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).  The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed.  Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.  Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.  7. Additional Terms.  "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law.  If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.  When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it.  (Additional permissions may be written to require their own removal in certain cases when you modify the work.)  You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.  Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:  a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or  b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or  c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or  d) Limiting the use for publicity purposes of names of licensors or authors of the material; or  e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or  f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.  All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10.  If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term.  If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.  If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.  Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.  8. Termination.  You may not propagate or modify a covered work except as expressly provided under this License.  Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).  However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.  Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.  Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License.  If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.  9. Acceptance Not Required for Having Copies.  You are not required to accept this License in order to receive or run a copy of the Program.  Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance.  However, nothing other than this License grants you permission to propagate or modify any covered work.  These actions infringe copyright if you do not accept this License.  Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.  10. Automatic Licensing of Downstream Recipients.  Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License.  You are not responsible for enforcing compliance by third parties with this License.  An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations.  If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.  You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License.  For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.  11. Patents.  A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based.  The work thus licensed is called the contributor's "contributor version".  A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version.  For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.  Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.  In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement).  To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.  If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients.  "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.  If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.  A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License.  You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.  Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.  12. No Surrender of Others' Freedom.  If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License.  If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all.  For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.  13. Remote Network Interaction; Use with the GNU General Public License.  Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software.  This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph.  Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU General Public License into a single combined work, and to convey the resulting work.  The terms of this License will continue to apply to the part which is the covered work, but the work with which it is combined will remain governed by version 3 of the GNU General Public License.  14. Revised Versions of this License.  The Free Software Foundation may publish revised and/or new versions of the GNU Affero General Public License from time to time.  Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.  Each version is given a distinguishing version number.  If the Program specifies that a certain numbered version of the GNU Affero General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation.  If the Program does not specify a version number of the GNU Affero General Public License, you may choose any version ever published by the Free Software Foundation.  If the Program specifies that a proxy can decide which future versions of the GNU Affero General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.  Later license versions may give you additional or different permissions.  However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.  15. Disclaimer of Warranty.  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.  16. Limitation of Liability.  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.  17. Interpretation of Sections 15 and 16.  If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.  END OF TERMS AND CONDITIONS  How to Apply These Terms to Your New Programs  If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.  To do so, attach the following notices to the program.  It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found.  <one line to give the program's name and a brief idea of what it does.> Copyright (C) <year>  <name of author>  This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.  This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.  You should have received a copy of the GNU Affero General Public License along with this program.  If not, see <http://www.gnu.org/licenses/>.  Also add information on how to contact you by electronic and paper mail.  If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source.  For example, if your program is a web application, its interface could display a "Source" link that leads users to an archive of the code.  There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements.  You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU AGPL, see <http://www.gnu.org/licenses/>.


pkgId: 5077641344eeaff20ba64000b61681768d5693e022e394a041b857fca36edbd2
name: python-agentboard
arch: src
version: 0.0.1
epoch: 0
release: 1
url: https://pypi.org/project/agentboard/
rpm_license: None
rpm_group: Unspecified
rpm_buildhost: localhost
location_href: Packages/python-agentboard-0.0.1-1.src.rpm
checksum_type: sha256
summary:
  Visualize the process and LLM functions call logs of AI agents development, including multi-agent, autonomous agents environments, etc.

description:
  This is the official github repo of pypi package agentboard(https://pypi.org/project/agentboard/).


  AgentBoard is a package designed to visualize the process and LLM functions call logs of AI agents development, such as multi-agent and autonomous agents environment.
  The development of AI agents involve asynchronous running of multiple AI agents. Their detailed processes(decision or running), timeline, asynchronous, chat visualizer, Chain-of-Thought (CoT), function calls of developments and production running stage.  It adapts to most of the popular AI agents development environments. Which will solve the problem of agent debug, and runtime visualization.


  Contributing to agentboard package development, please visit Github https://github.com/AI-Hub-Admin/agentboard

  Follow the guidelines on forum http://www.deepnlp.org/blog?category=agentboard



  ```
  pip install agentboard
  ```



  ```

  ```



  [Introduction to Robotics Mechatronics Research and Development Trends and Projects](http://www.deepnlp.org/blog/introduction-to-robotics-mechatronics-research-and-development-trends-and-projects) <br>
  [Introduction to multimodal generative models](http://www.deepnlp.org/blog/introduction-to-multimodal-generative-models) <br>
  [Generative AI Search Engine Optimization](http://www.deepnlp.org/blog/generative-ai-search-engine-optimization-how-to-improve-your-content) <br>
  [Chat Dialogue Online Visualizer](http://www.deepnlp.org/workspace/dialogue_visualization) <br>
  [AI Agent Visualizer](http://www.deepnlp.org/workspace/agent_visualization) <br>
  [AI Image Generator User Reviews](http://www.deepnlp.org/store/image-generator) <br>
  [AI Video Generator User Reviews](http://www.deepnlp.org/store/video-generator) <br>
  [AI Glasses User Reviews](http://www.deepnlp.org/store/ai-glasses) <br>
  [AI Search Engine User Reviews](http://www.deepnlp.org/store/search-engine) <br>
  [AI Search and Recommendation User Reviews](http://www.deepnlp.org/store/search-recommendation) <br>
  [AI Chatbot & Assistant Reviews](http://www.deepnlp.org/store/chatbot-assistant) <br>
  [AI Store-Best AI Tools User Reviews](http://www.deepnlp.org/store/pub/) <br>
  [AI Store Use Cases-Best AI Tools Cases User Reviews](http://www.deepnlp.org/store) <br>
  [AI Equation Database](http://www.deepnlp.org/equation/) <br>
  [4 ways to use ChatGPT Stock Chatbot for stock analysis of Global Stock Markets NASDAQ NYSE LSE HKEX TSE NSE SHANGHAI SHENZHEN](http://www.deepnlp.org/blog/chatgpt-stock-global-market) <br>
  [How to write a Financial Chatbot First Part 3 steps to crawl Hong Kong Stock Market (HKEX) realtime stock quotes](http://www.deepnlp.org/blog/fin-chatbot-first-spider-hkex) <br>
  [3 steps to create Financial Chatbot powered by ChatGPT Part 1](http://www.deepnlp.org/blog/financial-chatbot-chatgpt-1) <br>
  [AI Community Feeds](http://www.deepnlp.org/community) <br>
  [AI Community Question Discussion](http://www.deepnlp.org/question) <br>


pkgId: f018246526da50b70d636582d155deee09cf8cac55eb320f563d07477c827379
name: python-agentdesk
arch: src
version: 0.2.105
epoch: 0
release: 1
summary: A desktop for AI agents
url: https://pypi.org/project/agentdesk/
rpm_license: MIT
rpm_group: Unspecified
rpm_buildhost: localhost
location_href: Packages/python-agentdesk-0.2.105-1.src.rpm
checksum_type: sha256
description:
  <!-- PROJECT LOGO -->
  <br />
  <p align="center">
    <!-- <a href="https://github.com/agentsea/skillpacks">
      <img src="https://project-logo.png" alt="Logo" width="80">
    </a> -->

    <h1 align="center">AgentDesk</h1>

    <p align="center">
      Desktops for AI agents &nbsp; :computer:
      <br />
      <a href="https://docs.hub.agentsea.ai/agentdesk/intro"><strong>Explore the docs »</strong></a>
      <br />
      <br />
      <a href="https://youtu.be/exoOUUwFRB8">View Demo</a>
      ·
      <a href="https://github.com/agentsea/agentdesk/issues">Report Bug</a>
      ·
      <a href="https://github.com/agentsea/agentdesk/issues">Request Feature</a>
    </p>
    <br>
  </p>

  AgentDesk provides full-featured desktop environments which can be programatically controlled by AI agents.
  Spin them up locally or in the cloud.

  ▶ Built on [agentd](https://github.com/agentsea/agentd) a runtime daemon which exposes a REST API for interacting with the desktop.

  ▶ Implements the [DeviceBay Protocol](https://github.com/agentsea/devicebay).



  ```
  pip install agentdesk
  ```



  ```python
  from agentdesk import Desktop


  desktop = Desktop.docker()


  desktop.view(background=True)


  desktop.open_url("https://google.com")


  desktop.move_mouse(500, 500)
  desktop.click()
  img = desktop.take_screenshot()
  ```





  ```python
  from agentdesk import Desktop

  desktop = Desktop.docker()
  ```

  ```bash
  $ agentdesk create --provider docker
  ```

  _\*requires [docker](https://www.docker.com/)_




  ```python
  desktop = Desktop.kube()
  ```

  ```bash
  $ agentdesk create --provider kube
  ```



  ```python
  desktop = Desktop.gce()
  ```

  ```bash
  $ agentdesk create --provider gce
  ```



  ```python
  desktop = Desktop.ec2()
  ```

  ```bash
  $ agentdesk create --provider ec2
  ```



  ```python
  desktop.view()
  ```

  ```bash
  $ agentdesk view old_mckinny
  ```

  _\*requires docker_



  ```python
  Desktop.find()
  ```

  ```bash
  $ agentdesk get
  ```



  ```python
  Desktop.delete("old_mckinny")
  ```

  ```bash
  $ agentdesk delete old_mckinny
  ```



  ```python
  desktop.open_url("https://google.com")

  coords = desktop.mouse_coordinates()

  desktop.move_mouse(500, 500)

  desktop.click()

  desktop.type_text("What kind of ducks are in Canada?")

  desktop.press_key('Enter')

  desktop.scroll()

  img = desktop.take_screenshot()
  ```



  Process images to make them more accessible to LMMs.



  Add a coordinate grid on top of the image

  ```python
  from agentdesk.processors import GridProcessor

  img = desktop.take_screenshot()

  processor = GridProcessor()
  grid_img = processor.process_b64(img)
  ```





  See how to use a web-based drawing app with AgentDesk in our [notebook](./examples/drawing/demo.ipynb).



  See how to use GPT-4V with AgentDesk in our [notebook](./examples/gpt4v/note.ipynb) or [agent](./examples/gpt4v/main.py).



  Come join us on [Discord](https://discord.gg/hhaq7XYPS6).



  Please open an issue before creating a PR.

  Changes to the VM happen in [agentd](https://github.com/agentsea/agentd).


pkgId: 8d91d7677454ae4e0126115ee741a4550af11388ca87ef9857a026aaacc0b190
name: python-agentforge
arch: src
version: 0.4.1
epoch: 0
release: 1
summary: AI-driven task automation system
url: https://github.com/DataBassGit/AgentForge
rpm_license: GNU General Public License v3 or later (GPLv3+)
rpm_group: Unspecified
rpm_buildhost: localhost
location_href: Packages/python-agentforge-0.4.1-1.src.rpm
checksum_type: sha256
description:
  1. [Features](#features)
  2. [Documentation](#documentation)
  3. [Contributing](#contributing)
  4. [Contact Us](#contact-us)


pkgId: a83d216ea5f2a6491201ebfaa1496028f3614b4ade9360a8716aad349bfadf30
name: python-agentforum
arch: src
version: 0.0.10
epoch: 0
release: 1
url: https://pypi.org/project/agentforum/
rpm_license: MIT
rpm_group: Unspecified
rpm_buildhost: localhost
location_href: Packages/python-agentforum-0.0.10-1.src.rpm
checksum_type: sha256
summary:
  An asynchronous framework for building LLM-based multi-agent systems in Python, with a focus on trees of immutable messages and token streaming.

description:
  An asynchronous framework for building LLM-based multi-agent systems in Python, with a focus on:

  - **Message trees which highly resemble commits in git to facilitate backtracking.** Messages are immutable and are
    identified by hashes based on their content and their history (a hash of the previous message). A single hash
    represents state of a conversation at a given point in time.
  - **Message promises and the possibility of token streaming.** `MessagePromise` objects are returned before the
    messages are fully generated. Token streaming is supported regardless of the number of nested levels of agents.

  *NOTE: While this framework is designed with LLMs in mind, it can be used with any kind of agents.*



  - **Message forwarding.** Messages can be forwarded to become a part of different message branches or
    trees (much like it is done in messaging apps for humans).



  - **Agents run as concurrently as possible.** When an agent is called with `.call()` or `.quick_call()` a task is
    scheduled and `AgentCall` or `AsyncMessageSequence` objects are returned immediately. The actual processing will
    happen upon a task switch.
  - **Stateless agents are encouraged.** This is not a hard requirement, but ideally the agents should produce the same
    output when they are given the same input (the same sequence of messages from a message branch).



  This framework supports **Python 3.9 or higher** and uses [asyncio](https://docs.python.org/3/library/asyncio.html)
  under the hood.



  - **Message replies.** Technically this will be very similar to message forwarding. The difference will mostly be
    semantic (in the spirit of mimicking messaging apps for humans).
  - **Exceptions as part of the message tree.** In the future, exceptions raised by agents will be represented as a
    special type of messages and will be part of the message branches those agents were on when they were raised.
  - **Optional caching of agent responses (enabled by default).** When the same sequence of messages is sent to an agent,
    the framework will respond with the same sequence of response messages without actually calling the agent.
  - **Cancellation of agent execution.** In the future, it will be possible to cancel the execution of agents before
    they finish.

  ***⚠️ NOTE: These plans are tentative and may change in the future. ⚠️***


pkgId: d6b0ca8a0544dcb2d6215cdf355af2dfa0062c156c9d35c7f0279fe35eef0325
name: python-agentgateway
arch: src
version: 1.1.4
epoch: 0
release: 1
summary: A centralized framework to use a model of your choice for your agentic usecases.
url: https://github.com/santoshameti/agentgateway
rpm_license: MIT
rpm_group: Unspecified
rpm_buildhost: localhost
location_href: Packages/python-agentgateway-1.1.4-1.src.rpm
checksum_type: sha256
description:
  Agentgateway goal is to get you started with AI agents in the simplest way possible by abstracting out all complexity. This project implements a flexible AI Agent Gateway that supports LLMs from multiple AI backends including OpenAI(GPT and O1), Anthropic (Claude), Bedrock(Claude, Llama, Mistral etc), Groq (Mistral, Llama), Together(Mistral, Llama), Fireworks(Mistral, Llama) and Vertex AI (coming soon). It provides a unified interface for creating and running AI agents with various tools.



  - Support for multiple AI backends (OpenAI, Anthropic, Bedrock, Vertex AI)
  - Extensible tool system with built-in tools for weather, calculations, and translations
  - Secure management of API keys using environment variables
  - Easy-to-use interface for creating and running AI agents



  ```
  .
  ├── agent_gateway.py
  ├── core/
  │   ├── __init__.py
  │   ├── abstract_agent.py
  │   ├── agent.py
  │   ├── prompt.py
  │   ├── response.py
  │   └── abstract_tool.py
  ├── adapters/
  │   ├── __init__.py
  │   ├── anthropic_claude_adapter.py
  │   ├── openai_gpt_adapter.py
  │   ├── bedrock_converse_adapter.py
  │   └── ... (other adapter files)
  ├── tests/
  │   ├── ... (test files)
  ├── tools/
  │   ├── __init__.py
  │   ├── ask_user_tool.py
  │   ├── weather_tool.py
  │   ├── calculator_tool.py
  │   └── translation_tool.py
  ├── examples/
  │   ├── openai_example.py
  │   ├── bedrock_example.py
  │   └── anthropic_example.py
  ├── .env
  ├── requirements.txt
  └── README.md
  ```



  1. Clone the repository:
     ```
     git clone https://github.com/yourusername/ai-agent-gateway.git
     cd ai-agent-gateway
     ```

  2. Create a virtual environment and activate it:
     ```
     python -m venv venv
     source venv/bin/activate  # On Windows, use `venv\Scripts\activate`
     ```

  3. Install the required dependencies:
     ```
     pip install -r requirements.txt
     ```

  4. Create a `.env` file in the project root and add your API keys:
     ```
     OPENAI_API_KEY=your_openai_api_key_here
     ANTHROPIC_API_KEY=your_anthropic_api_key_here
     WEATHER_API_KEY=your_weather_api_key_here
     TRANSLATION_API_KEY=your_translation_api_key_here
     AWS_ACCESS_API=your_aws_api_key
     AWS_SECRET_KEY=your_aws_secret_access_key
     AWS_REGION_ID=your_aws_region
     TOGETHER_API_KEY=your_together_api_key
     FIREWORKS_API_KEY=your_together_api_key
     ```



  Here's a basic example of how to use the AI Agent Gateway with OpenAI:

  ```python
  import os
  from dotenv import load_dotenv
  from agent_gateway import AgentGateway, AgentType
  from core.prompt import Prompt
  from tools import WeatherTool, CalculatorTool


  load_dotenv()


  weather_tool = WeatherTool()
  calculator_tool = CalculatorTool()


  weather_tool.set_auth(api_key=os.getenv('WEATHER_API_KEY'))


  gateway = AgentGateway(AgentType.OPENAI)


  gateway.adapter.set_auth(api_key=os.getenv('OPENAI_API_KEY'))


  prompt = Prompt("You are a helpful assistant that can provide weather information and perform calculations.")
  agent = gateway.create_agent(prompt, tools=[weather_tool, calculator_tool])


  result = gateway.run_agent(agent, "What's the weather like in London and what's 15 * 24?")
  print(result)
  ```

  For more examples, check the `examples/` directory.



  To add a new tool:

  1. Create a new file in the `tools/` directory (e.g., `calendar_search_tool.py`).
  2. Define a new class that inherits from `Tool` (from `core.abstract_tool`).
  3. Implement the required methods: `execute`, `get_parameters_schema`, and `is_auth_setup`.
  4. Add any necessary authentication logic.

  Example of a hypothetical CalendarSearchTool:

  ```python
  from typing import Dict, Any
  from core.abstract_tool import Tool
  from some_calendar_api import CalendarAPI  # Hypothetical calendar API

  class CalendarSearchTool(Tool):
      def __init__(self):
          super().__init__("calendar_search", "Search for events in a calendar")
          self.api = None

      def is_auth_setup(self):
          return self.api is not None

      def execute(self) -> Any:
          if not self.is_auth_setup():
              raise ValueError("Calendar API not set up. Use set_auth() to set up the API.")

          parameters = self.get_parameters()
          start_date = parameters.get('start_date')
          end_date = parameters.get('end_date')
          search_term = parameters.get('search_term')

          events = self.api.search_events(start_date, end_date, search_term)
          return [self.format_event(event) for event in events]

      def get_parameters_schema(self) -> Dict[str, Any]:
          return {
              "type": "object",
              "properties": {
                  "start_date": {
                      "type": "string",
                      "description": "Start date for the search (ISO format)"
                  },
                  "end_date": {
                      "type": "string",
                      "description": "End date for the search (ISO format)"
                  },
                  "search_term": {
                      "type": "string",
                      "description": "Optional search term to filter events"
                  }
              },
              "required": ["start_date", "end_date"]
          }

      def set_auth(self, **kwargs):
          api_key = kwargs.get('api_key')
          if not api_key:
              raise ValueError("API key is required for CalendarSearchTool")
          self.api = CalendarAPI(api_key)

      def format_event(self, event):
          return {
              "title": event.title,
              "start": event.start_time.isoformat(),
              "end": event.end_time.isoformat(),
              "location": event.location
          }
  ```

  To use the new tool:

  1. Instantiate the tool: `calendar_tool = CalendarSearchTool()`
  2. Set up authentication: `calendar_tool.set_auth(api_key=os.getenv('CALENDAR_API_KEY'))`
  3. Add the tool to your agent when creating it:
     ```python
     agent = gateway.create_agent(prompt, tools=[calendar_tool, other_tools...])
     ```

  When using the tool, ensure that you handle the tool's parameters correctly in your agent's logic and provide the necessary authentication details.

  Remember to import and initialize any required libraries or APIs (in this example, the hypothetical `CalendarAPI`) in your actual implementation.



  To run the tests for this project, follow these steps:

  1. Ensure you have pytest installed. If not, install it using:
     ```
     pip install -r requirements.txt
     ```

  2. From the root directory of the project (agentgateway), run:
     ```
     python -m pytest
     ```

  This command will discover and run all tests in the `tests/` directory, including tests for tools and the tool manager.

  To run tests with more detailed output, you can use the `-v` (verbose) flag:
  ```
  python -m pytest -v
  ```

  To see print statements and other output during test execution, use the `-s` flag:
  ```
  python -m pytest -s
  ```

  You can combine these flags for even more detailed output:
  ```
  python -m pytest -v -s
  ```

  To run tests for specific components:

  - For all tool tests:
    ```
    python -m pytest tests/tools/
    ```

  - For specific tools:
    ```
    python -m pytest tests/tools/test_<tool_name>.py
    ```

  - For the tool manager:
    ```
    python -m pytest tests/test_tool_manager.py
    ```

  - For all adapter tests:
    ```
    python -m pytest tests/adapters/
    ```

  - For specific adapter:
    ```
    python -m pytest tests/tools/test_<adapter_name>.py
    ```
  - For the agent gateway:
    ```
    python -m pytest tests/test_agent_gateway.py
     ```

  Remember to write comprehensive tests for each component to ensure proper functionality and integration.



  Make sure your project structure follows the layout described in this README. The tests expect the tools to be in a module named `agentgateway`, so your directory structure should reflect this.



  Some tests, particularly for the WeatherTool and TranslationTool, use mocking to simulate external API calls. This ensures that tests can run without actually making network requests, which makes them faster and more reliable.

  When running these tests, make sure you have the `unittest.mock` module available (it's included in Python's standard library for Python 3.3 and newer).




  Consider setting up a CI/CD pipeline that runs these tests automatically on each commit or pull request. This will help catch any regressions early in the development process.



  Contributions are welcome! Please feel free to submit a Pull Request. Check out our [contribution guidelines](docs/contributing.md).



  This project is licensed under the MIT License.


pkgId: 7f8afcf44eb0eeb41fdf9c8168073d469fe8dbcc739ce49243055966b332c52b
name: python-agenthub-core
arch: src
version: 0.0.4
epoch: 0
release: 1
summary: AgentHub core package
url: https://pypi.org/project/agenthub-core/
rpm_license: None
rpm_group: Unspecified
rpm_buildhost: localhost
location_href: Packages/python-agenthub-core-0.0.4-1.src.rpm
checksum_type: sha256
description:
  Core package for the AgentHub framework, providing base classes and utilities.



  ```bash
  pip install agenthub-tools-core
  ```



  ```python
  from agenthub_tools.core import BaseTool

  class MyTool(BaseTool):
      name = "my-tool"
      description = "My custom tool"

      def execute(self, **kwargs):
          
          pass
  ```


pkgId: d3d542d6d78ff203ae8f1ab603b1477cae3dc1fbd2f3f4a70795c2461b696fe1
name: python-agenthub-tools-duckduckgo
arch: src
version: 0.0.6
epoch: 0
release: 1
summary: AgentHub duckduckgo package
url: https://pypi.org/project/agenthub-tools-duckduckgo/
rpm_license: None
rpm_group: Unspecified
rpm_buildhost: localhost
location_href: Packages/python-agenthub-tools-duckduckgo-0.0.6-1.src.rpm
checksum_type: sha256
description:
  This package provides duckduckgo integration for the AgentHub framework.



  ```bash
  pip install agenthub-tools-duckduckgo
  ```



  ```python
  from agenthub_tools.duckduckgo import search, news

  print(search(query="What is the weather in Tokyo?"))

  print(news(query="Whats going on in Paris?"))
  ```


pkgId: df0440e306ac4320951e1d8b657062d70049d0e8fdc73892d8de987d6edb8cc4
name: python-agentic-reports
arch: src
version: 0.1.5
epoch: 0
release: 1
summary: Agent Reporting using Exa.ai API.
url: https://github.com/ruvnet/agentic-reports
rpm_license: Apache License 2.0
rpm_group: Unspecified
rpm_buildhost: localhost
location_href: Packages/python-agentic-reports-0.1.5-1.src.rpm
checksum_type: sha256
description:
  ```
      _   ___ ___ _  _ _____ ___ ___   ___ ___ ___  ___  ___ _____ ___
     /_\ / __| __| \| |_   _|_ _/ __| | _ | __| _ \/ _ \| _ |_   _/ __|
    / _ | (_ | _|| .` | | |  | | (__  |   | _||  _| (_) |   / | | \__ \
   /_/ \_\___|___|_|\_| |_| |___\___| |_|_|___|_|  \___/|_|_\ |_| |___/

      A Comprehensive Python Library for Generating Research Reports

  ```
  Welcome to Agentic Reports, a Python library designed to simplify the process of generating comprehensive research reports. This library leverages the power of FastAPI, Pydantic, Pandas, and Exa to provide users with an efficient and streamlined way to create detailed reports based on various data sources. Agentic Reports uses real data from the internet, considering parameters such as time, source, domain, and other relevant factors to ensure the information is current and accurate.



  Agentic Reports uses a multi-step process to deliver detailed research reports from a variety of sources:

  1. **User Query Submission**: Users start by submitting a topic they wish to research. This can be done through a simple API request.

  2. **Subquery Generation**: The system automatically generates a set of subqueries related to the main topic. These subqueries break down the broad topic into specific areas of focus, ensuring a comprehensive analysis.

  3. **Data Collection**: Using the generated subqueries, the system searches for relevant information across various sources, including databases, external APIs, and other repositories. Web data features include filtering by time, source, domain, and other parameters to ensure the information is current and relevant.

  4. **Data Compilation**: The collected data is compiled into a cohesive and structured report. The system organizes the information, providing detailed analysis, insights, and findings based on the initial topic and subqueries.

  5. **Report Delivery**: The final report, complete with citations and data sources, is delivered back to the user in a well-organized format. This ensures that users receive a thorough and reliable resource for their research needs.

  By following these steps, Agentic Reports provides users with a streamlined and efficient way to generate comprehensive research reports, making it an invaluable tool for in-depth analysis and information gathering.



  - **AI-Enhanced Report Generation**: Harnesses the power of advanced AI models to create detailed and precise reports, ensuring accuracy and depth in every analysis.
  - **Robust Data Analysis**: Utilizes powerful search capabilities combined with Pandas for extensive data manipulation and insightful analysis.
  - **Web Data Features**: Incorporates real-time data from the internet, allowing filtering by time, source, domain, and other parameters to ensure the most current and relevant information.
  - **Flexible Report Customization**: Provides users with the ability to tailor reports to their specific needs, offering a high degree of customization to fit various requirements.



  To install Agentic Reports, simply use pip:

  ```bash
  pip install agentic-reports
  ```

  This command will install the library and all its dependencies, making it ready for use in your projects.



  To use Agentic Reports, you need to set your OpenAI and Exa API keys. These keys can be set from the command line or will be prompted the first time you start the library.



  - **OpenAI API Key**: To get your OpenAI API key, visit the [OpenAI API page](https://platform.openai.com/account/api-keys) and follow the instructions to create and retrieve your API key.
  - **Exa API Key**: To get your Exa API key, visit the [Exa API page](https://docs.exa.ai/) and follow the instructions to sign up and obtain your API key.



  When you first start the Agentic Reports library, it will check for the necessary API keys. If they are not set, it will prompt you to enter them:

  ```bash
  agentic-reports
  ```

  You will see prompts like:

  ```plaintext
  Enter your OPENAI_API_KEY:
  Enter your EXA_API_KEY:
  ```

  This ensures that you have the required keys set up before the application starts. Once entered, these keys will be used for subsequent runs of the application.

  By following these steps, you can easily set up and use your API keys to get the most out of Agentic Reports. For more detailed information, refer to the official documentation provided with the library.



  1. **Set API Keys Manually**: You can manually set your API keys using the `export` command in your terminal:

     ```bash
     export OPENAI_API_KEY="your_openai_api_key"
     export EXA_API_KEY="your_exa_api_key"
     ```

  2. **Check if API Keys are Set**: To verify that your API keys are set, you can use the `echo` command:

     ```bash
     echo $OPENAI_API_KEY
     echo $EXA_API_KEY
     ```



  `Agentic Reports` is designed to make the process of generating detailed research reports seamless and user-friendly.



  1. **Submit a Topic**: The user starts by submitting a topic they want to research. This can be done through a simple API request, where the user provides the main topic of interest. For example, "Latest AI advancements".



  2. **Automatic Subquery Generation**: Once the main topic is submitted, the system automatically generates a set of detailed subqueries related to the main topic. These subqueries help in breaking down the broad topic into specific areas of focus, ensuring a comprehensive analysis.



  3. **Data Gathering**: The system then uses these subqueries to search for relevant information across various sources. This includes fetching data from databases, external APIs, and other repositories. The goal is to gather as much pertinent information as possible.



  4. **Report Compilation**: After collecting the data, the system compiles all the gathered information into a cohesive and structured report. This report includes detailed analysis, insights, and findings based on the provided topic and its subqueries.



  5. **Report Delivery**: The final report is delivered back to the user in a well-organized format. The user can then review the comprehensive report, which includes citations, data sources, and detailed explanations, providing a thorough understanding of the topic.



  - **Ease of Use**: Users only need to provide a single topic to get started. The rest of the process, including generating subqueries and gathering data, is handled automatically.
  - **Comprehensive Analysis**: By breaking down the main topic into subqueries, the system ensures a deep and thorough exploration of the subject matter.
  - **Time Efficiency**: Automating the research process saves users significant time and effort, providing them with detailed reports quickly.
  - **Detailed Insights**: The final report includes citations and sources, offering users a reliable and informative resource for their research needs.

  Agentic Reports, through `Agentic Reports`, streamlines the entire process of creating detailed research reports, making it an invaluable tool for anyone needing comprehensive and accurate information on a specific topic.



  Agentic Reports provides several endpoints for generating reports and processing data:

  - **/generate-report**: Generates a comprehensive report based on a given topic.
    - Parameters: `topic` (string)
    - Example Request: `{"topic": "Latest AI advancements"}`

  - **/generate-subqueries**: Generates subqueries from a given topic for detailed analysis.
    - Parameters: `topic` (string), `num_subqueries` (int)
    - Example Request: `{"topic": "Latest AI advancements", "num_subqueries": 5}`

  - **/search-subqueries**: Searches for information based on provided subqueries.
    - Parameters: `subqueries` (list of strings)
    - Example Request: `{"subqueries": ["AI in healthcare", "AI in finance"]}`

  - **/advanced-search**: Performs an advanced search with customizable parameters.
    - Parameters: `query` (string), `start_published_date` (string), `end_published_date` (string), etc.
    - Example Request: `{"query": "AI", "start_published_date": "2021-01-01", "end_published_date": "2021-12-31"}`

  - **/find-similar-links**: Finds similar links to a provided URL.
    - Parameters: `url` (string), `num_results` (int)
    - Example Request: `{"url": "https://cnn.com", "num_results": 10}`

  - **/generate-report-advanced**: Generates an advanced, comprehensive report based on detailed subqueries and provided prompts.
    - Parameters:
      - `query` (string): The main topic for the report.
      - `primary_prompt` (string): The primary prompt for the report generation.
      - `subqueries_prompt` (string): The prompt for generating subqueries.
      - `report_prompt` (string): The detailed prompt for generating the final report.
      - `start_published_date` (string, optional): The start date for filtering published articles.
      - `end_published_date` (string, optional): The end date for filtering published articles.
      - `include_domains` (list of strings, optional): Domains to include in the search.
      - `exclude_domains` (list of strings, optional): Domains to exclude from the search.
      - `highlights` (dict, optional): Parameters for highlighting text.
      - `text` (dict, optional): Parameters for including HTML tags in the text.
      - `num_subqueries` (int): The number of subqueries to generate.
      - `batch_size` (int, optional): The size of each batch for processing subqueries.



  ```
  {
    "query": "string",  // The main topic for the report
    "primary_prompt": "string",  // The primary prompt for the report generation
    "subqueries_prompt": "string",  // The prompt for generating subqueries
    "report_prompt": "string",  // The detailed prompt for generating the final report
    "start_published_date": "string (YYYY-MM-DD)",  // Optional: The start date for filtering published articles
    "end_published_date": "string (YYYY-MM-DD)",  // Optional: The end date for filtering published articles
    "include_domains": ["string"],  // Optional: Domains to include in the search
    "exclude_domains": ["string"],  // Optional: Domains to exclude from the search
    "highlights": {
      "num_sentences": "int"  // Optional: Parameters for highlighting text
    },
    "text": {
      "include_html_tags": "boolean"  // Optional: Parameters for including HTML tags in the text
    },
    "num_subqueries": "int",  // The number of subqueries to generate
    "batch_size": "int"  // Optional: The size of each batch for processing subqueries
  }

  ```
  - remove "// descriptions"



  Agentic Reports can be used in a variety of advanced scenarios, such as:

  - **Automated Generation of Research Papers and Articles**: Automatically generate in-depth research papers and articles by leveraging AI models that create comprehensive and well-structured content based on user-defined topics.

  - **Data Analysis and Visualization for Business Intelligence**: Utilize the library to perform sophisticated data analysis and create visualizations that aid in business decision-making and strategy formulation.

  - **Custom Report Generation for Specific Industries or Topics**: Tailor reports to meet the unique needs of different industries or specific research topics, providing highly relevant and targeted information.



  The `@router.post("/generate-report-advanced")` endpoint is designed for generating comprehensive and detailed reports based on advanced queries and parameters. This endpoint allows for a high degree of customization, enabling users to specify detailed prompts, subqueries, and other parameters to tailor the report generation process to their specific needs.



  The endpoint aims to provide users with the ability to generate reports that require a deeper level of analysis and customization than standard reports. It supports a wide range of parameters that can be used to define the scope, focus, and structure of the generated report.



  - `query` (string): The main query or topic for the report.
  - `primary_prompt` (string): The primary prompt guiding the report's focus.
  - `subqueries_prompt` (string): Prompts for generating subqueries related to the main topic.
  - `report_prompt` (string): The prompt for structuring the final report.
  - `start_published_date` (string, optional): The start date for filtering published data.
  - `end_published_date` (string, optional): The end date for filtering published data.
  - `include_domains` (list of strings, optional): Domains to include in the search.
  - `exclude_domains` (list of strings, optional): Domains to exclude from the search.
  - `highlights` (dict, optional): Parameters for highlighting key sentences.
  - `text` (dict, optional): Parameters for text content retrieval.
  - `num_subqueries` (int): The number of subqueries to generate.



  ```json
  {
    "query": "AI Stocks",
    "primary_prompt": "Generate a detailed report on the current advancements, performance, and market trends of AI stocks. The report should include an analysis of recent developments, major players, market performance, challenges faced by AI stocks, and future prospects. Ensure that the report is well-structured and professional.",
    "subqueries_prompt": "Generate 2 interesting, diverse search queries that would be useful for generating a detailed report on AI stocks. These subqueries should cover various aspects of the topic, including recent advancements, market performance, major players, challenges, and future prospects.",
    "report_prompt": "Write a comprehensive and professional in English, five-paragraph, 200-word research report about AI stocks based on the provided information. Include citations in the text using footnote notation ([citation #]), for example [2]. First provide the report, followed by a single `References` section that only lists the URLs (and their published date) used, in the format [#] <url>. For the published date, only include the month and year. Reset the citations index and ignore the order of citations in the provided information.",
    "start_published_date": "2024-01-01",
    "end_published_date": "2024-06-03",
    "highlights": {
      "num_sentences": 5
    },
    "text": {
      "include_html_tags": false
    },
    "num_subqueries": 5
  }
  ```



  The response will include a structured report based on the provided parameters. The report will be comprehensive, including analysis, insights, and findings as specified in the prompts and subqueries. The response structure will also include any highlights or specific text content retrieval parameters as requested.

  By utilizing this advanced report generation feature, developers and researchers can create detailed and customized reports tailored to their specific research needs and interests.



  Agentic Reports incorporates advanced prompt engineering techniques to enhance the quality and depth of generated reports. These approaches include multi-hop prompting, recursive strategies, graph structures, and advanced logic and reasoning.



  Multi-hop prompting involves breaking down complex queries into a series of intermediate steps or subqueries. Each subquery aims to gather specific pieces of information that, when combined, provide a comprehensive answer to the original query. This approach ensures that the final report is detailed and well-supported by relevant data.

  **Example**: To generate a report on "The impact of AI in healthcare," the system might break it down into subqueries such as:
  1. Historical development of AI in healthcare.
  2. Current applications of AI in diagnostics and treatment.
  3. Case studies on AI-driven healthcare improvements.
  4. Future trends and potential of AI in healthcare.



  Recursive prompting involves iterative querying, where the system refines its queries based on previous responses. This technique ensures that the gathered information is accurate and relevant, progressively narrowing down the search to provide precise and comprehensive results.

  **Example**: For a topic like "AI's role in climate change mitigation," the initial query might focus on general applications of AI. Based on the gathered data, subsequent queries will delve deeper into specific areas such as AI in renewable energy optimization, AI in carbon footprint reduction, and AI-driven climate modeling.



  Graph-based prompting leverages graph structures to map relationships between different pieces of information. By creating a network of interconnected data points, the system can identify and explore intricate connections, providing a more holistic and nuanced report.

  **Example**: When researching "AI in financial markets," a graph structure can help map out the relationships between AI technologies, market trends, regulatory impacts, and economic outcomes. This interconnected approach allows for a comprehensive analysis of how AI influences various aspects of financial markets.



  Advanced logic and reasoning techniques are used to enhance the depth and accuracy of the reports. These techniques involve critical thinking, hypothesis testing, and evidence-based analysis to ensure that the generated content is logical, coherent, and well-supported by data.

  **Example**: For a report on "Ethical implications of AI," the system uses advanced reasoning to weigh different ethical considerations, analyze case studies, and provide balanced arguments. It critically examines various perspectives, ensuring a thorough and unbiased analysis.



  Agentic Reports often combines these prompt engineering techniques to maximize the quality and comprehensiveness of the generated reports. By integrating multi-hop prompting, recursive strategies, graph structures, and advanced logic and reasoning, the system can tackle complex topics with precision and depth.

  **Example**: Generating a report on "The future of AI in smart cities" might involve:
  - **Multi-hop prompting** to break down the topic into subqueries like AI in traffic management, AI in energy efficiency, and AI in public safety.
  - **Recursive prompting** to iteratively refine these subqueries based on initial findings.
  - **Graph structures** to map out the relationships between different AI applications and their impacts on smart city development.
  - **Advanced logic and reasoning** to critically analyze the data and provide well-rounded insights and projections.

  By leveraging these advanced prompt engineering techniques, Agentic Reports ensures that users receive highly detailed, accurate, and insightful reports tailored to their specific research needs.

  Here's the updated README with the link pointing to `./sample-reports/`:



  This README provides an overview of advanced reporting techniques utilized in Agentic Reports, showcasing examples and JSON configurations for each method. These techniques enhance the depth, accuracy, and comprehensiveness of generated reports, tailored to specific research needs.



  Recursive prompting involves iterative querying to refine searches based on previous responses, ensuring accurate and relevant information.

  [Learn more about Recursive Prompting](./sample-reports/recursive-prompting.md)



  Graph-based prompting uses graph structures to map relationships between information, identifying intricate connections for a holistic report.

  [Learn more about Graph Structures](./sample-reports/graph-structures.md)



  This technique employs critical thinking and evidence-based analysis to ensure logical, coherent content supported by data.

  [Learn more about Advanced Logic and Reasoning](./sample-reports/advanced-logic-and-reasoning.md)



  Agentic Reports often combine these techniques to maximize report quality, tackling complex topics with precision.

  [Learn more about Combining Approaches](./sample-reports/combining-approaches.md)



  ```json
  {
    "query": "The future of AI in smart cities",
    "primary_prompt": "Generate a detailed report on the future of AI in smart cities, focusing on applications such as traffic management, energy efficiency, and public safety.",
    "subqueries_prompt": "Generate 2 interesting, diverse search queries that would be useful for generating a detailed report on the future of AI in smart cities.",
    "report_prompt": "Write a comprehensive and professional in English, five-paragraph, 200-word research report about the future of AI in smart cities based on the provided information.",
    "start_published_date": "2024-01-01",
    "end_published_date": "2024-06-03",
    "highlights": {
      "num_sentences": 5
    },
    "text": {
      "include_html_tags": false
    },
    "num_subqueries": 5
  }
  ```

  For more detailed examples and JSON configurations, refer to the respective `.md` files linked above.


  ```
  Starting report generation for topic: Agentic Engineering and the coming agent landscape
  🌿 Generating subqueries from topic: Agentic Engineering and the coming agent landscape

  Raw response content: Certainly! Below are ten diverse and interesting search queries that can help you generate a comprehensive report on "Agentic

  Engineering and the coming agent landscape":

  1. **"Agentic Engineering: Definitions and Key Concepts"**
     - Understand the foundational ideas and terminologies related to agentic engineering.

  2. **"Historical Evolution and Milestones in Agentic Engineering"**
     - Explore the development and significant breakthroughs in the field.

  3. **"Agentic Engineering in Artificial Intelligence and Robotics"**
     - Investigate the application of agentic engineering within AI and robotics.

  4. **"Ethical Considerations and Challenges in Agentic Engineering"**
     - Delve into the ethical implications and potential societal impacts.

  5. **"Future Landscape of Autonomous Agents in Industry and Everyday Life"**
     - Analyze future projections and the expected integration of autonomous agents in various sectors.

  6. **"Case Studies of Successful Implementation of Agentic Engineering"**
     - Look at real-world examples and their outcomes to understand practical applications.

  7. **"Agentic Engineering: Innovations and Upcoming Technologies"**
     - Identify the latest innovations and technologies that are shaping the field.

  8. **"Comparative Analysis of Agentic Engineering vs Traditional Engineering"**
     - Compare and contrast agentic engineering with other engineering disciplines.

  9. **"Regulatory Frameworks and Policies Around Agentic Engineering"**
     - Investigate the current and proposed regulations governing the development and deployment of autonomous agents.

  10. **"Impact of Agentic Engineering on Employment and Workforce Dynamics"**
      - Examine how agentic engineering and autonomous agents are transforming job markets and skills requirements.

  These queries should provide a well-rounded basis for your research and reporting on the subject.
  Parsed subqueries:

  ['**"Agentic Engineering: Definitions and Key Concepts"**', '**"Historical Evolution and Milestones in Agentic Engineering"**', '**"Agentic Engineering in Artificial Intelligence and Robotics"**', '**"Ethical Considerations and Challenges in Agentic Engineering"**', '**"Future Landscape of Autonomous Agents in Industry and Everyday Life"**', '**"Case Studies of Successful Implementation of Agentic Engineering"**', '**"Agentic Engineering: Innovations and Upcoming Technologies"**', '**"Comparative Analysis of Agentic Engineering vs Traditional Engineering"**', '**"Regulatory Frameworks and Policies Around Agentic Engineering"**', '**"Impact of Agentic Engineering on Employment and Workforce Dynamics"**']

  ⌛ Searching each subquery
  🔍 Searching for subquery: **"Agentic Engineering: Definitions and Key Concepts"**
  🔍 Searching for subquery: **"Historical Evolution and Milestones in Agentic Engineering"**
  🔍 Searching for subquery: **"Agentic Engineering in Artificial Intelligence and Robotics"**
  🔍 Searching for subquery: **"Ethical Considerations and Challenges in Agentic Engineering"**
  🔍 Searching for subquery: **"Future Landscape of Autonomous Agents in Industry and Everyday Life"**
  🔍 Searching for subquery: **"Case Studies of Successful Implementation of Agentic Engineering"**
  🔍 Searching for subquery: **"Agentic Engineering: Innovations and Upcoming Technologies"**
  🔍 Searching for subquery: **"Comparative Analysis of Agentic Engineering vs Traditional Engineering"**
  🔍 Searching for subquery: **"Regulatory Frameworks and Policies Around Agentic Engineering"**
  🔍 Searching for subquery: **"Impact of Agentic Engineering on Employment and Workforce Dynamics"**
  ✅ Search successful for subquery: **"Agentic Engineering: Definitions and Key Concepts"**
  ✅ Search successful for subquery: **"Historical Evolution and Milestones in Agentic Engineering"**
  ✅ Search successful for subquery: **"Agentic Engineering in Artificial Intelligence and Robotics"**
  ✅ Search successful for subquery: **"Ethical Considerations and Challenges in Agentic Engineering"**
  ✅ Search successful for subquery: **"Future Landscape of Autonomous Agents in Industry and Everyday Life"**
  ✅ Search successful for subquery: **"Case Studies of Successful Implementation of Agentic Engineering"**
  ✅ Search successful for subquery: **"Agentic Engineering: Innovations and Upcoming Technologies"**
  ✅ Search successful for subquery: **"Comparative Analysis of Agentic Engineering vs Traditional Engineering"**
  ✅ Search successful for subquery: **"Regulatory Frameworks and Policies Around Agentic Engineering"**
  ✅ Search successful for subquery: **"Impact of Agentic Engineering on Employment and Workforce Dynamics"**
  🏁 Completed search for all subqueries
  Generating report from Exa results for topic: Agentic Engineering and the coming agent landscape
  ⌨️  Formatting Exa results for LLM
  ```




  Agentic Engineering is an evolving field that seeks to integrate principles of agency into engineered systems, emphasizing attributes such as autonomy, functionality, intentionality, and meaning. Foundational concepts in naturalized accounts of agency highlight the interrelation of these attributes and their evolution over time, showcasing the complex properties that constitute autonomous agents[1]. This approach recognizes the importance of scientific inquiry and continuous formulation of questions to advance the understanding and capabilities of agentic systems. Autonomy and interaction are particularly emphasized as key drivers in developing robust and adaptable agents capable of significantly enhancing human-machine collaboration[1].

  Recent advancements in AI and machine learning have catalyzed the development of agentic systems capable of implementing complex workflows and multi-agent collaborations. A course by Andrew Ng and collaborators showcases AutoGen, a framework that enables the creation of specialized agents designed for tasks such as multi-agent collaboration, tool use, and planning[2]. By leveraging such tools, developers can build conversational agents with capabilities ranging from playing chess to generating detailed financial reports with minimal manual intervention. These innovations are not merely confined to digital realms; they are poised to revolutionize physical tasks through integrations with robotics, as seen with AI systems that can autonomously manage real-world tasks such as self-driving cars[3].

  One of the most significant impacts of Agentic Engineering is on the workforce and employment dynamics. While there is concern about the potential for AI to displace human jobs, there is also a significant opportunity for enhancing productivity and innovation. AI employees, like the Ema multi-agent system, are designed to augment human roles by automating repetitive and complex tasks[4]. These AI personas integrate with various enterprise applications, enabling users to deploy AI-driven workflows with minimal setup. This shift not only promises to optimize operational efficiency but also necessitates new regulatory frameworks and training programs to ensure that human workers can effectively collaborate with AI counterparts while maintaining data security and ethical standards[4][5].



  [1] https://www.sciencedirect.com/science/article/pii/S0732118X09000464 (Published: November 2140)

  [2] https://x.com/AndrewYNg/status/1795845101979406490 (Published: May 2024)

  [3] https://gizmodo.com/ai-agents-openai-chatgpt-google-gemini-reality-sci-fi-1851500474 (Published: May 2024)

  [4] https://medium.com/emaunlimited/the-guide-to-ai-employees-how-ema-is-revolutionizing-enterprise-automation-with-agentic-systems-16df43d8e8d8 (Published: May 2024)

  [5] https://superagi.com/autonomous-software-development/ (Published: May 2024)


pkgId: 3ae349f5b07d8c789ad0600678433041704058dbfd8ea5fdf07c40c286875784
name: python-agentic-search
arch: src
version: 4.1.3
epoch: 0
release: 1
summary: code for an agentic search tool using Langchain
url: https://github.com/markets-agent/agentic-search
rpm_license: MIT
rpm_group: Unspecified
rpm_buildhost: localhost
location_href: Packages/python-agentic-search-4.1.3-1.src.rpm
checksum_type: sha256
description:
  This repo holds the code for [an agentic search tool package](https://pypi.org/project/agentic-search/), building up on this excellent [LangChain web search assistant YouTube tutorial](https://www.youtube.com/watch?v=DjuXACWYkkU). I want to automate my searches on various data sources, as well as their analysis.

  It can search:

  - a PostgreSQL database
  - Arxiv papers summaries
  - PDF and text documents (RAG)
  - the web

  The idea here is to modularize all that logic so that it can be reused in other projects.



  This has been tested on a Ubuntu 24 server. You'll need:

  - at least 20GB of GPU VRAM for the best experience
  - all the env vars listed in the `.env.example` file
    - be mindful that if `WITH_DEBUG_MESSAGES` is set to `true` (as in the `.env.example` file), the output to `stdout` will be more verbose
  - Ollama installed
  - the Ollama models you need to have installed are the ones specified in the [`yollama` package](https://pypi.org/project/yollama/)
  - PostgreSQL installed and running (preferably with the `pgvector` extension installed, as the PostgreSQL generation code assumes you're using vectors in the prompts)
  - Python 3 with `venv` and `pip` installed



  `pip install agentic-search`

  Let's say you want to test the `generate_sql_query` chain with `pytest` in your project.

  ```python
  from agentic_search import get_generate_sql_query_chain
  from dotenv import load_dotenv

  load_dotenv()


  def test_get_generate_sql_query_chain():
      chain = get_generate_sql_query_chain()
      result = chain.invoke({"query": "what are the latest headlines"})
      assert isinstance(result, str)
      assert result.startswith("SELECT")
  ```





  ```
  agentic_search/
      capabilities/
      chains/
      functions/
      graphs/
      nodes/
      prompts/
  ```

  We support **capabilities** for:

  - arxiv
  - PostgreSQL
  - web

  We support **chains** for:

  - arxiv
  - PostgreSQL
  - text (RAG, works on PDFs as well)
  - web

  We support **graphs** for:

  - web



  Functions are simple Python functions that can be used by other components of the system. They are located in the `functions/` folder.




  Prompts are the LLM prompts used by the chains. They are located in the `prompts/` folder.



  Chains in this project are the basic building blocks that perform specific operations. They are located in the `chains/` folder and typically:

  - Need to be explicitly invoked using the `.invoke()` method
  - Are more granular and focused on a single responsibility
  - Can be composed together to form more complex operations
  - Return raw results that might need further processing



  The chains can be orchestrated using graphs (located in the `graphs/` folder), which provides:

  - Ability to create cyclical workflows (unlike traditional DAG-based solutions)
  - State management between chain executions
  - Built-in persistence for maintaining conversation context
  - Support for human-in-the-loop interventions

  The graphs themselves use nodes, which are steps during the graph execution that can be composed together at will, located in the `nodes/` folder.

  Nodes can be plain agent nodes, with custom logic, or tools or set of tools (kinda like a toolbelt) that can be used by the agent.



  Capabilities (located in the `capabilities/` folder), on the other hand, are higher-level features that:

  - Provide a more user-friendly interface by accepting natural language input
  - Compose multiple chains together to create complete workflows
  - Handle all the necessary orchestration between different chains
  - Return processed, ready-to-use results (either as strings or JSON objects)
  - Don't require explicit `.invoke()` calls from the end user, unlike chains and graphs



  1. **Abstraction Level**:
     - Chains: Low-level, single-purpose operations
     - Graphs: Infrastructure layer handling state and flow control
     - Capabilities: High-level, complete features that solve user problems

  2. **Usage Pattern**:
     - Chains: Sequential units of work that involve LLMs and/or Python functions
     - Graphs: Manages the execution flow and state between components
     - Capabilities: Accept simple string inputs in natural language

  3. **Composition**:
     - Chains: Are the building blocks that get composed together
     - Graphs: Provides the framework for connecting and orchestrating components
     - Capabilities: Are the composers that arrange chains and graphsinto useful features

  4. **Output**:
     - Chains: May return raw or intermediate results
     - Graphs: Handles state updates and ensures proper data flow between nodes
     - Capabilities: Always return processed, user-friendly output

  This architecture allows for better modularity and reusability, as chains and graphs can be mixed and matched to create different capabilities while keeping the core logic separate from the high-level features. The graphs layer ensures reliable execution and state management throughout the workflow. The capabilities layer, on the other hand, provide a user-friendly interface for interacting with the system.



  To run the tests, follow these steps:

  - Navigate to the project root directory.

  - Run all tests:
     ```
     pytest
     ```

  - To run tests from a specific file:
    ```
    pytest agentic_search/functions/test_text.py -vv -s
    ```

  - To run a specific test function:
    ```
    pytest -k "test_normalize_and_lemmatize_text" agentic_search/functions/test_text.py -vv -s
    ```





  I've decided to let go of OpenAI to:

  - preserve my privacy
  - save money

  As local models are getting better and better, I'm confident that I'll be able to have a greater experience in the future, even with my small 20GB VRAM GPU. 🤔 Of course, it's not fast, but hey everything comes with tradeoffs right? 💪



  The Arxiv and web search features are heavily inspired by https://github.com/assafelovic/gpt-researcher, which basically splits up one search into multiple sub searches before generating a final output.

  For instance, you would have:

  - the user searching "what are the latest advancements in AI"
  - an LLM generates a set of subqueries, like "latest advancements in NLP", "latest advancements in ML", etc.
  - each subquery is sent to a search engine
  - the results are aggregated and passed to another LLM which generates a final output



  🤝 I haven't made up my mind on contribution guidelines yet. I guess we'll update them as you contribute!


pkgId: ff613f7566f8381a39ecaea377ea1545a7e199de1dc85bcb5e783c0dc1adf46e
name: python-agentic-search
arch: src
version: 5.0.0
epoch: 0
release: 1
summary: code for an agentic search tool using Langchain
url: https://github.com/markets-agent/agentic-search
rpm_license: MIT
rpm_group: Unspecified
rpm_buildhost: localhost
location_href: Packages/python-agentic-search-5.0.0-1.src.rpm
checksum_type: sha256
description:
  Multimedia search capabilities for your projects, fully local.



  This repo holds the code for [a fully local agentic search tool package](https://pypi.org/project/agentic-search/), building up on this excellent [LangChain web search assistant YouTube tutorial](https://www.youtube.com/watch?v=DjuXACWYkkU). I want to automate my searches on various data sources, as well as their analysis.

  It can search:

  - a PostgreSQL database
  - Arxiv papers summaries
  - PDF and text documents (RAG)
  - the web

  The idea here is to modularize all that logic so that it can be reused in other projects.



  This has been tested on a Ubuntu 24 server. You'll need:

  - at least 20GB of GPU VRAM for the best experience
  - all the env vars listed in the `.env.example` file
    - be mindful that if `WITH_DEBUG_MESSAGES` is set to `true` (as in the `.env.example` file), the output to `stdout` will be more verbose
  - Ollama installed
  - the Ollama models you need to have installed are the ones specified in the [`yollama` package](https://pypi.org/project/yollama/)
  - PostgreSQL installed and running (preferably with the `pgvector` extension installed, as the PostgreSQL generation code assumes you're using vectors in the prompts)
  - Python 3 with `venv` and `pip` installed



  `pip install agentic-search`

  Let's say you want to test the `generate_sql_query` chain with `pytest` in your project.

  ```python
  from agentic_search import get_generate_sql_query_chain

  def test_get_generate_sql_query_chain():
      chain = get_generate_sql_query_chain()
      result = chain.invoke({"query": "what are the latest headlines"})
      assert isinstance(result, str)
      assert result.startswith("SELECT")
  ```





  ```
  agentic_search/
      capabilities/
      chains/
      functions/
      graphs/
      nodes/
      prompts/
  ```

  We support **capabilities** for:

  - arxiv
  - PostgreSQL
  - web

  We support **chains** for:

  - arxiv
  - PostgreSQL
  - text (RAG, works on PDFs as well)
  - web

  We support **graphs** for:

  - web



  Functions are simple Python functions that can be used by other components of the system. They are located in the `functions/` folder.




  Prompts are the LLM prompts used by the chains. They are located in the `prompts/` folder.



  Chains in this project are the basic building blocks that perform specific operations. They are located in the `chains/` folder and typically:

  - Need to be explicitly invoked using the `.invoke()` method
  - Are more granular and focused on a single responsibility
  - Can be composed together to form more complex operations
  - Return raw results that might need further processing



  The chains can be orchestrated using graphs (located in the `graphs/` folder), which provides:

  - Ability to create cyclical workflows (unlike traditional DAG-based solutions)
  - State management between chain executions
  - Built-in persistence for maintaining conversation context
  - Support for human-in-the-loop interventions

  The graphs themselves use nodes, which are steps during the graph execution that can be composed together at will, located in the `nodes/` folder.

  Nodes can be plain agent nodes, with custom logic, or tools or set of tools (kinda like a toolbelt) that can be used by the agent.



  Capabilities (located in the `capabilities/` folder), on the other hand, are higher-level features that:

  - Provide a more user-friendly interface by accepting natural language input
  - Compose multiple chains together to create complete workflows
  - Handle all the necessary orchestration between different chains
  - Return processed, ready-to-use results (either as strings or JSON objects)
  - Don't require explicit `.invoke()` calls from the end user, unlike chains and graphs



  1. **Abstraction Level**:
     - Chains: Low-level, single-purpose operations
     - Graphs: Infrastructure layer handling state and flow control
     - Capabilities: High-level, complete features that solve user problems

  2. **Usage Pattern**:
     - Chains: Sequential units of work that involve LLMs and/or Python functions
     - Graphs: Manages the execution flow and state between components
     - Capabilities: Accept simple string inputs in natural language

  3. **Composition**:
     - Chains: Are the building blocks that get composed together
     - Graphs: Provides the framework for connecting and orchestrating components
     - Capabilities: Are the composers that arrange chains and graphsinto useful features

  4. **Output**:
     - Chains: May return raw or intermediate results
     - Graphs: Handles state updates and ensures proper data flow between nodes
     - Capabilities: Always return processed, user-friendly output

  This architecture allows for better modularity and reusability, as chains and graphs can be mixed and matched to create different capabilities while keeping the core logic separate from the high-level features. The graphs layer ensures reliable execution and state management throughout the workflow. The capabilities layer, on the other hand, provide a user-friendly interface for interacting with the system.



  To run the tests, follow these steps:

  - Navigate to the project root directory.

  - Run all tests:
     ```
     pytest
     ```

  - To run tests from a specific file:
    ```
    pytest agentic_search/functions/test_text.py -vv -s
    ```

  - To run a specific test function:
    ```
    pytest -k "test_normalize_and_lemmatize_text" agentic_search/functions/test_text.py -vv -s
    ```





  I've decided to let go of OpenAI to:

  - preserve my privacy
  - save money

  As local models are getting better and better, I'm confident that I'll be able to have a greater experience in the future, even with my small 20GB VRAM GPU. 🤔 Of course, it's not fast, but hey everything comes with tradeoffs right? 💪



  The Arxiv and web search features are heavily inspired by https://github.com/assafelovic/gpt-researcher, which basically splits up one search into multiple sub searches before generating a final output.

  For instance, you would have:

  - the user searching "what are the latest advancements in AI"
  - an LLM generates a set of subqueries, like "latest advancements in NLP", "latest advancements in ML", etc.
  - each subquery is sent to a search engine
  - the results are aggregated and passed to another LLM which generates a final output



  🤝 I haven't made up my mind on contribution guidelines yet. I guess we'll update them as you contribute!


pkgId: 21e1bd670b2cc0580fe13cdeb71f97169a1bc164d52bedd8c513f2b6188c8065
name: python-agentic_security
arch: src
version: 0.2.6
epoch: 0
release: 1
summary: Agentic LLM vulnerability scanner
url: https://github.com/msoedov/agentic_security
rpm_license: MIT
rpm_group: Unspecified
rpm_buildhost: localhost
location_href: Packages/python-agentic_security-0.2.6-1.src.rpm
checksum_type: sha256
description:
  <p align="center">

  <h1 align="center">Agentic Security</h1>

  <p align="center">
      The open-source Agentic LLM Vulnerability Scanner
      <br />
      <br />

  <p>
  <img alt="GitHub Contributors" src="https://img.shields.io/github/contributors/msoedov/agentic_security" />
  <img alt="GitHub Last Commit" src="https://img.shields.io/github/last-commit/msoedov/agentic_security" />
  <img alt="" src="https://img.shields.io/github/repo-size/msoedov/agentic_security" />
  <img alt="Downloads" src="https://static.pepy.tech/badge/agentic_security" />
  <img alt="GitHub Issues" src="https://img.shields.io/github/issues/msoedov/agentic_security" />
  <img alt="GitHub Pull Requests" src="https://img.shields.io/github/issues-pr/msoedov/agentic_security" />
  <img alt="Github License" src="https://img.shields.io/github/license/msoedov/agentic_security" />
  </p>
    </p>
  </p>



  - Customizable Rule Sets or Agent based attacks🛠️
  - Comprehensive fuzzing for any LLMs 🧪
  - LLM API integration and stress testing 🛠️
  - Wide range of fuzzing and attack techniques 🌀

  Note: Please be aware that Agentic Security is designed as a safety scanner tool and not a foolproof solution. It cannot guarantee complete protection against all possible threats.



  To get started with Agentic Security, simply install the package using pip:

  ```shell
  pip install agentic_security
  ```



  ```shell
  agentic_security

  2024-04-13 13:21:31.157 | INFO     | agentic_security.probe_data.data:load_local_csv:273 - Found 1 CSV files
  2024-04-13 13:21:31.157 | INFO     | agentic_security.probe_data.data:load_local_csv:274 - CSV files: ['prompts.csv']
  INFO:     Started server process [18524]
  INFO:     Waiting for application startup.
  INFO:     Application startup complete.
  INFO:     Uvicorn running on http://0.0.0.0:8718 (Press CTRL+C to quit)
  ```

  ```shell
  python -m agentic_security

  agentic_security --help


  agentic_security --port=PORT --host=HOST

  ```



  <img width="100%" alt="booking-screen" src="https://res.cloudinary.com/do9qa2bqr/image/upload/v1713002396/1-ezgif.com-video-to-gif-converter_s2hsro.gif">



  Agentic Security uses plain text HTTP spec like:

  ```http
  POST https://api.openai.com/v1/chat/completions
  Authorization: Bearer sk-xxxxxxxxx
  Content-Type: application/json

  {
       "model": "gpt-3.5-turbo",
       "messages": [{"role": "user", "content": "<<PROMPT>>"}],
       "temperature": 0.7
  }

  ```

  Where `<<PROMPT>>` will be replaced with the actual attack vector during the scan, insert the `Bearer XXXXX` header value with your app credentials.



  TBD

  ```
  ....
  ```



  To add your own dataset you can place one or multiples csv files with `prompt` column, this data will be loaded on `agentic_security` startup

  ```
  2024-04-13 13:21:31.157 | INFO     | agentic_security.probe_data.data:load_local_csv:273 - Found 1 CSV files
  2024-04-13 13:21:31.157 | INFO     | agentic_security.probe_data.data:load_local_csv:274 - CSV files: ['prompts.csv']
  ```



  ci.py

  ```python
  from agentic_security import AgenticSecurity

  spec = """
  POST http://0.0.0.0:8718/v1/self-probe
  Authorization: Bearer XXXXX
  Content-Type: application/json

  {
      "prompt": "<<PROMPT>>"
  }
  """
  result = AgenticSecurity.scan(llmSpec=spec)



  exit(max(r.values()) > 20)
  ```

  ```
  python ci.py
  2024-04-27 17:15:13.545 | INFO     | agentic_security.probe_data.data:load_local_csv:279 - Found 1 CSV files
  2024-04-27 17:15:13.545 | INFO     | agentic_security.probe_data.data:load_local_csv:280 - CSV files: ['prompts.csv']
  0it [00:00, ?it/s][INFO] 2024-04-27 17:15:13.74 | data:prepare_prompts:195 | Loading Custom CSV
  [INFO] 2024-04-27 17:15:13.74 | fuzzer:perform_scan:53 | Scanning Local CSV 15
  18it [00:00, 176.88it/s]
  +-----------+--------------+--------+
  |  Module   | Failure Rate | Status |
  +-----------+--------------+--------+
  | Local CSV |    80.0%     |   ✘    |
  +-----------+--------------+--------+
  ```



  1. Add new metadata to agentic_security.probe_data.REGISTRY

  ```python
      {
          "dataset_name": "markush1/LLM-Jailbreak-Classifier",
          "num_prompts": 1119,
          "tokens": 19758,
          "approx_cost": 0.0,
          "source": "Hugging Face Datasets",
          "selected": True,
          "dynamic": False,
          "url": "https://huggingface.co/markush1/LLM-Jailbreak-Classifier",
      },
  ```

  and implement loader into

  ```python
  @dataclass
  class ProbeDataset:
      dataset_name: str
      metadata: dict
      prompts: list[str]
      tokens: int
      approx_cost: float

      def metadata_summary(self):
          return {
              "dataset_name": self.dataset_name,
              "num_prompts": len(self.prompts),
              "tokens": self.tokens,
              "approx_cost": self.approx_cost,
          }

  ```



  One of the current examples uses sampling for the existing preloaded prompt data and applying mutations yielding a new dataset

  ```python
  class Stenography:
      fn_library = {
          "rot5": stenography_fn.rot5,
          "rot13": stenography_fn.rot13,
          "base64": stenography_fn.base64_encode,
          "mirror": stenography_fn.mirror_words,
          "random_case": stenography_fn.randomize_letter_case,
          "scramble_words": stenography_fn.scramble_words,
          "noise_characters": stenography_fn.insert_noise_characters,
          "substitute_with_ascii": stenography_fn.substitute_with_ascii,
          "remove_vowels": stenography_fn.remove_vowels,
          "zigzag_obfuscation": stenography_fn.zigzag_obfuscation,
      }

      def __init__(self, prompt_groups: [ProbeDataset]):
          self.prompt_groups = prompt_groups

      def apply(self):
          for prompt_group in self.prompt_groups:

              size = len(prompt_group.prompts)
              for name, fn in self.fn_library.items():
                  logger.info(f"Applying {name} to {prompt_group.dataset_name}")
                  selected_prompts = random.sample(prompt_group.prompts, int(size * 0.25))
                  prompts = [
                      f"Follow the instructions in {name}: {fn(p)}"
                      for p in selected_prompts
                  ]
                  yield ProbeDataset(
                      dataset_name=f"stenography.{name}({prompt_group.dataset_name})",
                      metadata={},
                      prompts=prompts,
                      tokens=count_words_in_list(prompts),
                      approx_cost=0.0,
                  )
  ```



  In the example of custom integration, we use `/v1/self-probe` for the sake of integration testing.

  ```python
  POST https://agentic_security-preview.vercel.app/v1/self-probe
  Authorization: Bearer XXXXX
  Content-Type: application/json

  {
      "prompt": "<<PROMPT>>"
  }

  ```

  This endpoint randomly mimics the refusal of a fake LLM.

  ```python
  @app.post("/v1/self-probe")
  def self_probe(probe: Probe):
      refuse = random.random() < 0.2
      message = random.choice(REFUSAL_MARKS) if refuse else "This is a test!"
      message = probe.prompt + " " + message
      return {
          "id": "chatcmpl-abc123",
          "object": "chat.completion",
          "created": 1677858242,
          "model": "gpt-3.5-turbo-0613",
          "usage": {"prompt_tokens": 13, "completion_tokens": 7, "total_tokens": 20},
          "choices": [
              {
                  "message": {"role": "assistant", "content": message},
                  "logprobs": None,
                  "finish_reason": "stop",
                  "index": 0,
              }
          ],
      }

  ```



  TBD



  For more detailed information on how to use Agentic Security, including advanced features and customization options, please refer to the official documentation.



  - \[ \] Expand dataset variety
  - \[ \] Introduce two new attack vectors
  - \[ \] Develop initial attacker LLM
  - \[ \] Complete integration of OWASP Top 10 classification

  | Tool                    | Source                                                                        | Integrated |
  |-------------------------|-------------------------------------------------------------------------------|------------|
  | Garak                   | [leondz/garak](https://github.com/leondz/garak)                               | ✅          |
  | InspectAI               | [UKGovernmentBEIS/inspect_ai](https://github.com/UKGovernmentBEIS/inspect_ai) | ✅          |
  | llm-adaptive-attacks    | [tml-epfl/llm-adaptive-attacks](https://github.com/tml-epfl/llm-adaptive-attacks) | ✅       |
  | Custom Huggingface Datasets | markush1/LLM-Jailbreak-Classifier                                                                         | ✅          |
  | Local CSV Datasets      | -                                                                             | ✅          |

  Note: All dates are tentative and subject to change based on project progress and priorities.



  Contributions to Agentic Security are welcome! If you'd like to contribute, please follow these steps:

  - Fork the repository on GitHub
  - Create a new branch for your changes
  - Commit your changes to the new branch
  - Push your changes to the forked repository
  - Open a pull request to the main Agentic Security repository

  Before contributing, please read the contributing guidelines.



  Agentic Security is released under the Apache License v2.





  <img width="100%" src="https://repobeats.axiom.co/api/embed/2b4b4e080d21ef9174ca69bcd801145a71f67aaf.svg" />


pkgId: 2b0fdb814620cefa23548e4b1eff21f197b12b05976cfb51393b402106aebd97
name: python-agentica
arch: src
version: 0.1.8
epoch: 0
release: 1
summary: LLM agents
url: https://github.com/shibing624/agentica
rpm_license: Apache License 2.0
rpm_group: Unspecified
rpm_buildhost: localhost
location_href: Packages/python-agentica-0.1.8-1.src.rpm
checksum_type: sha256
description:
  [![PyPI version](https://badge.fury.io/py/agentica.svg)](https://badge.fury.io/py/agentica)
  [![Downloads](https://static.pepy.tech/badge/agentica)](https://pepy.tech/project/agentica)
  [![Contributions welcome](https://img.shields.io/badge/contributions-welcome-brightgreen.svg)](CONTRIBUTING.md)
  [![License Apache 2.0](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](LICENSE)
  [![python_version](https://img.shields.io/badge/Python-3.5%2B-green.svg)](requirements.txt)
  [![GitHub issues](https://img.shields.io/github/issues/shibing624/agentica.svg)](https://github.com/shibing624/agentica/issues)
  [![Wechat Group](https://img.shields.io/badge/wechat-group-green.svg?logo=wechat)](#Contact)
  **Agentica**: A Human-Centric Framework for Large Language Model Agent Building. 快速打造你的专属Agent。


  <img src="https://github.com/shibing624/agentica/blob/main/docs/llm_agentv2.png" width="800" />
  - **规划（Planning）**：任务拆解、生成计划、反思
  - **记忆（Memory）**：短期记忆（prompt实现）、长期记忆（RAG实现）
  - **工具使用（Tool use）**：function call能力，调用外部API，以获取外部信息，包括当前日期、日历、代码执行能力、对专用信息源的访问等

  <img src="https://github.com/shibing624/agentica/blob/main/docs/agent_arch.png" width="800" />
  - **Planner**：负责让LLM生成一个多步计划来完成复杂任务，生成相互依赖的“链式计划”，定义每一步所依赖的上一步的输出
  - **Worker**：接受“链式计划”，循环遍历计划中的每个子任务，并调用工具完成任务，可以自动反思纠错以完成任务
  - **Solver**：求解器将所有这些输出整合为最终答案

  `Agentica`是一个Agent构建工具，功能：
  - 简单代码快速编排Agent，支持 Reflection(反思）、Plan and Solve(计划并执行)、RAG、Agent、Multi-Agent、Multi-Role、Workflow等功能
  - Agent支持prompt自定义，支持多种工具调用（tool_calls）
  - 支持OpenAI/Azure/Deepseek/Moonshot/Claude/Ollama/Together API调用

  ```bash
  pip install -U agentica
  ```
  or
  ```bash
  git clone https://github.com/shibing624/agentica.git
  cd agentica
  pip install .
  ```


  ```shell
  git clone https://github.com/shibing624/agentica.git
  cd agentica
  pip install -r requirements.txt
  ```

  ```shell

  cp .env.example ~/.agentica/.env
  cd examples
  python web_search_deepseek_demo.py
  ```
  1. 复制[.env.example](https://github.com/shibing624/agentica/blob/main/.env.example)文件为`~/.agentica/.env`，并填写LLM api key(选填DEEPSEEK_API_KEY、MOONSHOT_API_KEY、OPENAI_API_KEY等任一个即可)。
  2. 使用`agentica`构建Agent并执行：
  自动调用google搜索工具，示例[examples/web_search_deepseek_demo.py](https://github.com/shibing624/agentica/blob/main/examples/web_search_deepseek_demo.py)
  ```python
  from agentica import Assistant, DeepseekLLM, SearchSerperTool
  m = Assistant(llm=DeepseekLLM(), tools=[SearchSerperTool()])
  r = m.run("一句话介绍林黛玉")
  print(r, "".join(r))
  r = m.run("北京最近的新闻top3", stream=True)
  print(r, "".join(r))
  r = m.run("总结前面的问答", stream=False)
  print(r)
  ```

  [shibing624/ChatPilot](https://github.com/shibing624/ChatPilot) 兼容`agentica`，可以通过Web UI进行交互。
  Web Demo: https://chat.mulanai.com
  <img src="https://github.com/shibing624/ChatPilot/blob/main/docs/shot.png" width="800" />
  ```shell
  git clone https://github.com/shibing624/ChatPilot.git
  cd ChatPilot
  pip install -r requirements.txt
  cp .env.example .env
  bash start.sh
  ```

  | 示例                                                                                                                                    | 描述                                                                                                                              |
  |---------------------------------------------------------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------|
  | [examples/naive_rag_demo.py](https://github.com/shibing624/agentica/blob/main/examples/naive_rag_demo.py)                             | 实现了基础版RAG，基于Txt文档回答问题                                                                                                           |
  | [examples/advanced_rag_demo.py](https://github.com/shibing624/agentica/blob/main/examples/advanced_rag_demo.py)                       | 实现了高级版RAG，基于PDF文档回答问题，新增功能：pdf文件解析、query改写，字面+语义多路召回，召回排序（rerank）                                                               |
  | [examples/python_assistant_demo.py](https://github.com/shibing624/agentica/blob/main/examples/python_assistant_demo.py)               | 实现了Code Interpreter功能，自动生成python代码，并执行                                                                                          |
  | [examples/research_demo.py](https://github.com/shibing624/agentica/blob/main/examples/research_demo.py)                               | 实现了Research功能，自动调用搜索工具，汇总信息后撰写科技报告                                                                                              |
  | [examples/team_news_article_demo.py](https://github.com/shibing624/agentica/blob/main/examples/team_news_article_demo.py)             | 实现了写新闻稿的team协作，multi-role实现，委托不用角色完成各自任务：研究员检索分析文章，撰写员根据排版写文章，汇总多角色成果输出结果                                                       |
  | [examples/workflow_news_article_demo.py](https://github.com/shibing624/agentica/blob/main/examples/workflow_news_article_demo.py)     | 实现了写新闻稿的工作流，multi-agent的实现，定义了多个Assistant和Task，多次调用搜索工具，并生成高级排版的新闻文章                                                            |
  | [examples/workflow_investment_demo.py](https://github.com/shibing624/agentica/blob/main/examples/workflow_investment_demo.py)         | 实现了投资研究的工作流：股票信息收集 - 股票分析 - 撰写分析报告 - 复查报告等多个Task                                                                                |
  | [examples/crawl_webpage_demo.py](https://github.com/shibing624/agentica/blob/main/examples/crawl_webpage_demo.py)                     | 实现了网页分析工作流：从Url爬取融资快讯 - 分析网页内容和格式 - 提取核心信息 - 汇总保存为md文件                                                                          |
  | [examples/find_paper_from_arxiv_demo.py](https://github.com/shibing624/agentica/blob/main/examples/find_paper_from_arxiv_demo.py)     | 实现了论文推荐工作流：自动从arxiv搜索多组论文 - 相似论文去重 - 提取核心论文信息 - 保存为csv文件                                                                        |
  | [examples/remove_image_background_demo.py](https://github.com/shibing624/agentica/blob/main/examples/remove_image_background_demo.py) | 实现了自动去除图片背景功能，包括自动通过pip安装库，调用库实现去除图片背景                                                                                          |
  | [examples/text_classification_demo.py](https://github.com/shibing624/agentica/blob/main/examples/text_classification_demo.py)         | 实现了自动训练分类模型的工作流：读取训练集文件并理解格式 - 谷歌搜索pytextclassifier库 - 爬取github页面了解pytextclassifier的调用方法 - 写代码并执行fasttext模型训练 - check训练好的模型预测结果 |
  | [examples/llm_os_demo.py](https://github.com/shibing624/agentica/blob/main/examples/llm_os_demo.py)                                   | 实现了LLM OS的初步设计，基于LLM设计操作系统，可以通过LLM调用RAG、代码执行器、Shell等工具，并协同代码解释器、研究助手、投资助手等来解决问题。                                                |
  | [examples/workflow_write_novel_demo.py](https://github.com/shibing624/agentica/blob/main/examples/workflow_write_novel_demo.py)       | 实现了写小说的工作流：定小说提纲 - 搜索谷歌反思提纲 - 撰写小说内容 - 保存为md文件                                                                                  |
  | [examples/workflow_write_tutorial_demo.py](https://github.com/shibing624/agentica/blob/main/examples/workflow_write_tutorial_demo.py) | 实现了写技术教程的工作流：定教程目录 - 反思目录内容 - 撰写教程内容 - 保存为md文件                                                                                  |
  | [examples/self_evolving_agent_demo.py](https://github.com/shibing624/agentica/blob/main/examples/self_evolving_agent_demo.py)         | 实现了基于长期记忆的自我进化智能体，可以基于历史问答信息自我调整决策                                                                                              |

  The LLM OS design:
  <img alt="LLM OS" src="https://github.com/shibing624/agentica/blob/main/docs/llmos.png" width="800" />

  ```shell
  cd examples
  streamlit run llm_os_demo.py
  ```
  <img alt="LLM OS" src="https://github.com/shibing624/agentica/blob/main/docs/llm_os_snap.png" width="800" />

  The self-evolving agent design:
  <img alt="LLM OS" src="https://github.com/shibing624/agentica/blob/main/docs/sage_arch.png" width="800" />

  具有反思和增强记忆能力的自我进化智能体(self-evolving Agents with Reflective and Memory-augmented Abilities, SAGE)
  实现方法:
  1. 使用PythonAssistant作为SAGE智能体，使用AzureOpenAILLM作为LLM, 具备code-interpreter功能，可以执行Python代码，并自动纠错。
  2. 使用CsvMemoryDb作为SAGE智能体的记忆，用于存储用户的问题和答案，下次遇到相似的问题时，可以直接返回答案。

  ```shell
  cd examples
  streamlit run self_evolving_agent_demo.py
  ```
  <img alt="sage_snap" src="https://github.com/shibing624/agentica/blob/main/docs/sage_snap.png" width="800" />

  - Issue(建议)
    ：[![GitHub issues](https://img.shields.io/github/issues/shibing624/agentica.svg)](https://github.com/shibing624/agentica/issues)
  - 邮件我：xuming: xuming624@qq.com
  - 微信我： 加我*微信号：xuming624, 备注：姓名-公司-NLP* 进NLP交流群。
  <img src="https://github.com/shibing624/agentica/blob/main/docs/wechat.jpeg" width="200" />

  如果你在研究中使用了`agentica`，请按如下格式引用：
  APA:
  ```
  Xu, M. agentica: A Human-Centric Framework for Large Language Model Agent Workflows (Version 0.0.2) [Computer software]. https://github.com/shibing624/agentica
  ```
  BibTeX:
  ```
  @misc{Xu_agentica,
    title={agentica: A Human-Centric Framework for Large Language Model Agent Workflows},
    author={Xu Ming},
    year={2024},
    howpublished={\url{https://github.com/shibing624/agentica}},
  }
  ```

  授权协议为 [The Apache License 2.0](/LICENSE)，可免费用做商业用途。请在产品说明中附加`agentica`的链接和授权协议。

  项目代码还很粗糙，如果大家对代码有所改进，欢迎提交回本项目，在提交之前，注意以下两点：
  - 在`tests`添加相应的单元测试
  - 使用`python -m pytest`来运行所有单元测试，确保所有单测都是通过的
  之后即可提交PR。

  - [https://github.com/langchain-ai/langchain](https://github.com/langchain-ai/langchain)
  - [https://github.com/simonmesmith/agentflow](https://github.com/simonmesmith/agentflow)
  - [https://github.com/phidatahq/phidata](https://github.com/phidatahq/phidata)
  Thanks for their great work!


pkgId: ff7c0308bbb3111ff7dee784ccc4f90f578717e3ab069637a04ad9c23770d98a
name: python-agentifyme
arch: src
version: 0.0.23
epoch: 0
release: 1
summary: Framework for building agentic workflows
url: https://pypi.org/project/agentifyme/
rpm_license: None
rpm_group: Unspecified
rpm_buildhost: localhost
location_href: Packages/python-agentifyme-0.0.23-1.src.rpm
checksum_type: sha256
description:
  Framework for agentic workflows








  ```bash
  rye run coverage run -m pytest


  rye run coverage report


  rye run coverage html
  ```


pkgId: 2d25dafd764590c1cde04eb71a8a12314d4bcc30cf442a53fdec011e97c9f1cb
name: python-agentk8s
arch: src
version: 0.1.12
epoch: 0
release: 1
summary: k8s agent that does all the work for you.
url: https://pypi.org/project/agentk8s/
rpm_license: UNKNOWN
rpm_group: Unspecified
rpm_buildhost: localhost
location_href: Packages/python-agentk8s-0.1.12-1.src.rpm
checksum_type: sha256
description:
  **KGPT**, or **Kubernetes General Purpose Tasker**, is a cutting-edge Kubernetes agent designed to simplify and streamline the management of complex and manual tasks within your Kubernetes cluster. In the dynamic world of container orchestration and cloud-native computing, KGPT emerges as a powerful ally, offering automation and intelligence to help you efficiently handle a wide range of tasks, from deployment and scaling to monitoring and troubleshooting. This innovative agent is engineered to alleviate the burden of manual interventions, enhancing the agility and reliability of your Kubernetes infrastructure. With KGPT at your side, you can confidently navigate the intricate landscape of Kubernetes, ensuring optimal performance and resource utilization while freeing up valuable time for more strategic endeavors.




  - You already setup an k8s cluster locally or on the cloud, and **kubectl** is working normally
  - You need **Python** and **pip** installed
  - openAI GPT-4 **API key** ready



  ```commandline
  pip install agentk8s
  ```


  ```commandline
  $ kgpt --install-completion
  ```



  ```commandline
  kgpt setup
  ```


  ```commandline
  kgpt chat "create an deployment called mynginx, image name is nginx, three replicas, expose port 80"
  ```
  After a few seconds you should see the following output if everything is executed successfully.

  ```
  user_proxy (to assistant):

  exitcode: 0 (execution succeeded)
  Code output:
  deployment.apps/mynginx created

  service/mynginx exposed
  ```



  ```commandline
  kgpt chat "Change mynginx service's target port to 8001"
  ```

  If everything is executed successfully, you should see the following output

  ```commandline
  exitcode: 0 (execution succeeded)
  Code output:
  service/mynginx patched
  ```


  ```commandline
  kgpt chat "delete mynginx deployment and service"
  ```
  You should be able to see the following output, if everything is executed successfully.

  ```commandline
  user_proxy (to assistant):

  exitcode: 0 (execution succeeded)
  Code output:
  deployment.apps "mynginx" deleted
  service "mynginx" deleted
  ```


  ```commandline
  kgpt chat "find vulnerability in this k8s yaml file" --doc example_file/deployment1.yaml
  ```
  you should be seeing the following output
  ```commandline
  Intent: Code generation task (to find vulnerability in the provided k8s yaml file).

  The provided YAML file has a few issues that could potentially be considered vulnerabilities or misconfigurations:

  1. The `image` field does not specify a tag. Using the `latest` tag or not specifying a tag can lead to unpredictable deployments because it's not clear which version of the image is being used. It's better to use a specific version for reproducibility and to avoid accidentally pulling in an updated version with potential vulnerabilities.

  2. There are no resource requests or limits specified for the container. This can lead to resource exhaustion on the node where the pod is running, potentially affecting other pods and the stability of the node itself.

  3. There is no readiness probe defined. While not necessarily a vulnerability, a readiness probe is important for ensuring that traffic is not sent to a container that isn't ready to handle it.

  4. The deployment does not define any security context. Without a security context, the container may run with default settings, which could include running as root, potentially leading to security risks if the container is compromised.

  5. The YAML syntax is incorrect. The dashes before `name` and `containerPort` should not be indented.

  Please note that the specific values for image version, resource requests, limits, and security context should be adjusted according to the actual requirements and best practices for the application and the organization's security policies.
  ```
  You can also supply kgpt with multiply docs
  ```commandline
  kgpt chat "combine these to yaml into one yaml" --doc example_file/deployment1.yaml --doc example_file/service1.yaml
  ```


  - "create an deployment called mynginx, image name is nginx, three replicas, expose port 80"
  - "change mynginx service's target port to 8001"
  - "delete mynginx deployment and service"
  - "remove all deployment and service in namespace model"
  - "watch the status of deployment nginx"
  - "list all deployment and service"
  - "list all running deployment with more than two replica"
  - "create a namespace called test"
  - "create a namespace called gpu and change the nginx deployment's namespace to gpu"
  - "remove the namespace gpu if no deployment with the namespace gpu"
  - "create a docker-registry secret called my-docker-secret, the docker server is mydocker.io usename is vurtne and the password is yqxzv193"


pkgId: b15f5b47c8fa6080c0387e60935c4e89752c84002452d5ab0dc8a78f762074a0
name: python-agentkit-llm
arch: src
version: 0.1.8.1
epoch: 0
release: 1
summary: A LLM prompting framework for LLM agents
url: https://github.com/rhyswynn/AgentKit
rpm_license: CC-BY-4.0-Attribution
rpm_group: Unspecified
rpm_buildhost: localhost
location_href: Packages/python-agentkit-llm-0.1.8.1-1.src.rpm
checksum_type: sha256
description:
  <div align="center">
  <img src="https://github.com/Holmeswww/AgentKit/raw/main/imgs/AgentKit.png" width="350px">

  **AgentKit: Flow Engineering with Graphs, not Coding**

  [[Arxiv Paper]](https://arxiv.org/abs/2404.11483)
  [[PDF]](https://arxiv.org/pdf/2404.11483.pdf)
  [[Docs]](https://agentkit.readthedocs.io/)

  [![PyPI - Python Version](https://img.shields.io/pypi/pyversions/agentkit-llm)](https://pypi.org/project/agentkit-llm/)
  [![PyPI](https://img.shields.io/pypi/v/agentkit-llm)](https://pypi.org/project/agentkit-llm/)
  [![PyPI Status](https://static.pepy.tech/badge/agentkit-llm)](https://pepy.tech/project/agentkit-llm)
  [![Docs](https://readthedocs.org/projects/agentkit/badge/?version=latest)](https://agentkit.readthedocs.io/en/latest/?badge=latest)
  [![GitHub license](https://img.shields.io/github/license/holmeswww/agentkit)](https://github.com/holmeswww/AgentKit/blob/main/LICENSE)
  ______________________________________________________________________
  ![](https://github.com/Holmeswww/AgentKit/raw/main/imgs/teaser.png)
  </div>

  <img src="https://github.com/Holmeswww/AgentKit/raw/main/imgs/AgentKit.png" width="65px"> offers a unified framework for explicitly constructing a complex human "thought process" from simple natural language prompts.
  The user puts together chains of *nodes*, like stacking LEGO pieces. The chains of nodes can be designed to explicitly enforce a naturally *structured* "thought process".

  Different arrangements of nodes could represent different functionalities, allowing the user to integrate various functionalities to build multifunctional agents.

  A basic agent could be implemented as simple as a list of prompts for the subtasks and therefore could be designed and tuned by someone *without any programming experience*.




  - [Installation](#Installation)
  - [Getting Started](#Getting-Started)
  - [Using Built-in LLM_API](#Built-in-LLM-API)
  - [Using AgentKit without Programming Experience](#Using-AgentKit-without-Programming-Experience)
  - [Node Components](#Node-Components)
  - [Commonly Asked Questions](#Commonly-Asked-Questions)
  - [Citing AgnetKit](#Citing-AgentKit)



  Installing the AgentKit stable version is as simple as:

  ```bash
  pip install agentkit-llm
  ```

  To install AgentKit with wandb:

  ```bash
  pip install agentkit-llm[logging]
  ```

  To install AgentKit with OpenAI and Claude LLM-API support:

  ```bash
  pip install agentkit-llm[proprietary]
  ```

  To install AgentKit with full built-in LLM-API support (including llama):

  ```bash
  pip install agentkit-llm[all]
  ```

  Otherwise, to install the cutting edge version from the main branch of this repo, run:

  ```bash
  git clone https://github.com/holmeswww/AgentKit && cd AgentKit
  pip install -e .
  ```



  The basic building block in AgentKit is a node, containing a natural language prompt for a specific subtask. The nodes are linked together by the dependency specifications, which specify the order of evaluation. Different arrangements of nodes can represent different different logic and throught processes.

  At inference time, AgentKit evaluates all nodes in specified order as a directed acyclic graph (DAG).

  ```python
  import agentkit
  from agentkit import Graph, BaseNode

  import agentkit.llm_api

  LLM_API_FUNCTION = agentkit.llm_api.get_query("gpt-4-turbo")

  LLM_API_FUNCTION.debug = True # Disable this to enable API-level error handling-retry

  graph = Graph()

  subtask1 = "What are the pros and cons for using LLM Agents for Game AI?"
  node1 = BaseNode(subtask1, subtask1, graph, LLM_API_FUNCTION, agentkit.compose_prompt.BaseComposePrompt(), verbose=True)
  graph.add_node(node1)

  subtask2 = "Give me an outline for an essay titled 'LLM Agents for Games'."
  node2 = BaseNode(subtask2, subtask2, graph, LLM_API_FUNCTION, agentkit.compose_prompt.BaseComposePrompt(), verbose=True)
  graph.add_node(node2)

  subtask3 = "Now, write a full essay on the topic 'LLM Agents for Games'."
  node3 = BaseNode(subtask3, subtask3, graph, LLM_API_FUNCTION, agentkit.compose_prompt.BaseComposePrompt(), verbose=True)
  graph.add_node(node3)


  graph.add_edge(subtask1, subtask2)
  graph.add_edge(subtask1, subtask3)
  graph.add_edge(subtask2, subtask3)

  result = graph.evaluate() # outputs a dictionary of prompt, answer pairs
  ```

  ``LLM_API_FUNCTION`` can be any LLM API function that takes ``msg:list`` and ``shrink_idx:int``, and outputs ``llm_result:str`` and ``usage:dict``. Where ``msg`` is a prompt ([OpenAI format](https://platform.openai.com/docs/guides/text-generation/chat-completions-api) by default), and ``shrink_idx:int`` is an index at which the LLM should reduce the length of the prompt in case of overflow.

  AgentKit tracks token usage of each node through the ``LLM_API_FUNCTION`` with:
  ```python
  usage = {
      'prompt': $prompt token counts,
      'completion': $completion token counts,
  }
  ```



  The built-in `agentkit.llm_api` functions require installing with `[proprietary]` or `[all]` setting. See [the installation guide](#Installation) for details.

  Currently, the built-in API supports OpenAI and Anthropic, see https://pypi.org/project/openai/ and https://pypi.org/project/anthropic/ for details.

  To use the OpenAI models, set environment variables `OPENAI_KEY` and `OPENAI_ORG`. Alternatively, you can put the openai 'key' and 'organization' in the first 2 lines of `~/.openai/openai.key`.

  To use the Azure OpenAI models, set environment variables `AZURE_OPENAI_API_KEY`, `AZURE_OPENAI_API_VERSION`, `AZURE_OPENAI_ENDPOINT`, and `AZURE_DEPLOYMENT_NAME`. Alternatively, you can store the Azure OpenAI API key, API version, Azure endpoint, and deployment name in the first 4 lines of `~/.openai/azure_openai.key`.

  To use the Anthropic models, set environment variable `ANTHROPIC_KEY`. Alternatively, you can put the anthropic 'key' in 3rd line of `~/.openai/openai.key`.

  To use Ollama models, see https://github.com/ollama/ollama for installation instructions. Then set `OLLAMA_URL` and `OLLAMA_TOKENIZER_PATH`, or store `OLLAMA_TOKENIZER_PATH`, `OLLAMA_URL` in the first 2 lines of `~/.ollama/ollama_model.info`.

  ```
  LLM_API_FUNCTION = agentkit.llm_api.get_query("ollama-llama3")
  ```



  First, follow [the installation guide](#Installation) to install AgentKit with `[all]` setting.

  Then, set environment variables `OPENAI_KEY` and `OPENAI_ORG` to be your OpenAI key and org_key.

  Finally, run the following to evoke the command line interface (CLI):

  ```bash
  git clone https://github.com/holmeswww/AgentKit && cd AgentKit
  cd examples/prompt_without_coding
  python generate_graph.py
  ```
  ![](https://github.com/Holmeswww/AgentKit/raw/main/imgs/screenshot.png)



  ![](https://github.com/Holmeswww/AgentKit/raw/main/imgs/node_archi.png)
  Inside each node (as shown to the left of the figure), AgentKit runs a built-in flow that **preprocesses** the input (Compose), queries the LLM with a preprocessed input and prompt $q_v$, and optionally **postprocesses** the output of the LLM (After-query).

  To support advanced capabilities such as branching, AgentKit offers API to dynamically modify the DAG at inference time (as shown to the right of the figure). Nodes/edges could be dynamically added or removed based on the LLM response at some ancestor nodes.



  **Q:** I'm using the default `agentkit.llm_api`, and `graph.evaluate()` seems to be stuck.

  **A:** The LLM_API function catches and retries all API errors by default. Set `verbose=True` for each node to see which node you are stuck on, and `LLM_API_FUNCTION.debug=True` to see what error is causing the error.


  ```bibtex
  @inproceedings{agentkit,
    title = {AgentKit: Flow Engineering with Graphs, not Coding},
    author = {Wu, Yue and Fan, Yewen and Min, So Yeon and Prabhumoye, Shrimai and McAleer, Stephen and Bisk, Yonatan and Salakhutdinov, Ruslan and Li, Yuanzhi and Mitchell, Tom},
    year = {2024},
    booktitle = {COLM},
  }
  ```



  <a href="https://star-history.com/#holmeswww/agentkit&Date">
   <picture>
     <source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=holmeswww/agentkit&type=Date&theme=dark" />
     <source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=holmeswww/agentkit&type=Date" />
     <img alt="Star History Chart" src="https://api.star-history.com/svg?repos=holmeswww/agentkit&type=Date" />
   </picture>
  </a>


pkgId: 514acda3a2ebc608315b2d7d2552e1abcabfec8aac25303c6446bfe4ff481191
name: python-agentlab
arch: src
version: 0.3.1
epoch: 0
release: 1
summary: Main package for developing agents and experiments
url: https://github.com/ServiceNow/AgentLab
rpm_license: Apache-2.0
rpm_group: Unspecified
rpm_buildhost: localhost
location_href: Packages/python-agentlab-0.3.1-1.src.rpm
checksum_type: sha256
description:
  <div align="center">

  ![AgentLab Banner](https://github.com/user-attachments/assets/a23b3cd8-b5c4-4918-817b-654ae6468cb4)



  [![pypi](https://badge.fury.io/py/agentlab.svg)](https://pypi.org/project/agentlab/)
  [![PyPI - License](https://img.shields.io/pypi/l/agentlab?style=flat-square)]([https://opensource.org/licenses/MIT](http://www.apache.org/licenses/LICENSE-2.0))
  [![PyPI - Downloads](https://img.shields.io/pypi/dm/agentlab?style=flat-square)](https://pypistats.org/packages/agentlab)
  [![GitHub star chart](https://img.shields.io/github/stars/ServiceNow/AgentLab?style=flat-square)](https://star-history.com/#ServiceNow/AgentLab)
  [![Code Format](https://github.com/ServiceNow/AgentLab/actions/workflows/code_format.yml/badge.svg)](https://github.com/ServiceNow/AgentLab/actions/workflows/code_format.yml)
  [![Tests](https://github.com/ServiceNow/AgentLab/actions/workflows/unit_tests.yml/badge.svg)](https://github.com/ServiceNow/AgentLab/actions/workflows/unit_tests.yml)



  [🛠️ Setup](#%EF%B8%8F-setup-agentlab) &nbsp;|&nbsp;
  [🤖 Assistant](#-ui-assistant) &nbsp;|&nbsp;
  [🚀 Launch Experiments](#-launch-experiments) &nbsp;|&nbsp;
  [🔍 Analyse Results](#-analyse-results) &nbsp;|&nbsp;
  [🤖 Build Your Agent](#-implement-a-new-agent) &nbsp;|&nbsp;
  [↻ Reproducibility](#-reproducibility)

  https://github.com/ServiceNow/BrowserGym/assets/26232819/e0bfc788-cc8e-44f1-b8c3-0d1114108b85

  </div>

  AgentLab is a framework for developing and evaluating agents on a variety of
  [benchmarks](#-supported-benchmarks) supported by
  [BrowserGym](https://github.com/ServiceNow/BrowserGym).

  AgentLab Features:
  * Easy large scale parallel [agent experiments](#-launch-experiments) using [ray](https://www.ray.io/)
  * Building blocks for making agents over BrowserGym
  * Unified LLM API for OpenRouter, OpenAI, Azure, or self hosted using TGI.
  * Prefered way for running benchmarks like WebArena
  * Various [reproducibility features](#reproducibility-features)
  * Unified LeaderBoard (soon)



  | Benchmark | Setup  <br> Link | # Task <br> Template| Seed  <br> Diversity | Max  <br> Step | Multi-tab | Hosted Method | BrowserGym <br> Leaderboard |
  |-----------|------------|---------|----------------|-----------|-----------|---------------|----------------------|
  | [WebArena](https://webarena.dev/) | [setup](https://github.com/ServiceNow/BrowserGym/blob/main/browsergym/webarena/README.md) | 812 | None | 30 | yes | self hosted (docker) | soon |
  | [WorkArena](https://github.com/ServiceNow/WorkArena) L1 | [setup](https://github.com/ServiceNow/WorkArena?tab=readme-ov-file#getting-started) | 33 | High | 30 | no | demo instance | soon |
  | [WorkArena](https://github.com/ServiceNow/WorkArena) L2 | [setup](https://github.com/ServiceNow/WorkArena?tab=readme-ov-file#getting-started) | 341 | High | 50 | no | demo instance | soon |
  | [WorkArena](https://github.com/ServiceNow/WorkArena) L3 | [setup](https://github.com/ServiceNow/WorkArena?tab=readme-ov-file#getting-started) | 341 | High | 50 | no | demo instance | soon |
  | [WebLinx](https://mcgill-nlp.github.io/weblinx/) | - | 31586 | None | 1 | no | self hosted (dataset) | soon |
  | [VisualWebArena](https://github.com/web-arena-x/visualwebarena) | [setup](https://github.com/ServiceNow/BrowserGym/blob/main/browsergym/visualwebarena/README.md) | 910 | None | 30 | yes | self hosted (docker) | soon |
  | [AssistantBench](https://assistantbench.github.io/) | [setup](https://github.com/ServiceNow/BrowserGym/blob/main/browsergym/assistantbench/README.md) | 214 | None | 30 | yes | live web | soon |
  | [GAIA](https://huggingface.co/spaces/gaia-benchmark/leaderboard) (soon) | - | - | None | - | - | live web | soon |
  | [Mind2Web-live](https://huggingface.co/datasets/iMeanAI/Mind2Web-Live) (soon) | - | - | None | - | - | live web | soon |
  | [MiniWoB](https://miniwob.farama.org/index.html) | [setup](https://github.com/ServiceNow/BrowserGym/blob/main/browsergym/miniwob/README.md) | 125 | Medium | 10 | no | self hosted (static files) | soon |




  ```bash
  pip install agentlab
  ```

  If not done already, install playwright:
  ```bash
  playwright install
  ```

  Make sure to prepare the required benchmark according to instructions provided in the [setup
  column](#-supported-benchmarks).

  ```bash
  export AGENTLAB_EXP_ROOT=<root directory of experiment results>  # defaults to $HOME/agentlab_results
  export OPENAI_API_KEY=<your openai api key> # if openai models are used
  ```

  <details>
  <summary>Setup OpenRouter API</summary>

  ```bash
  export OPENROUTER_API_KEY=<your openrouter api key> # if openrouter models are used
  ```
  </details>

  <details>
  <summary>Setup Azure API</summary>

  ```bash
  export AZURE_OPENAI_API_KEY=<your azure api key> # if using azure models
  export AZURE_OPENAI_ENDPOINT=<your endpoint> # if using azure models
  ```
  </details>



  Use an assistant to work for you (at your own cost and risk).

  ```bash
  agentlab-assistant --start_url https://www.google.com
  ```

  Try your own agent:

  ```bash
  agentlab-assistant --agent_config="module.path.to.your.AgentArgs"
  ```



  ```python


  from agentlab.agents.generic_agent import AGENT_4o_MINI

  from agentlab.experiments.study import make_study

  study = make_study(
      benchmark="miniwob",  # or "webarena", "workarnea_l1" ...
      agent_args=[AGENT_4o_MINI],
      comment="My first study",
  )

  study.run(n_jobs=5)
  ```

  Relaunching incomplete or errored tasks

  ```python
  from agentlab.experiments.study import Study
  study = Study.load("/path/to/your/study/dir")
  study.find_incomplete(include_errors=True)
  study.run()
  ```

  See [main.py](main.py) to launch experiments with a variety of options. This is like a lazy CLI that
  is actually more convenient. Just comment and uncomment the lines you need or modify at will (but
  don't push to the repo).




  The complexity of the wild web, Playwright, and asyncio can sometimes cause jobs to hang. This
  disables workers until the study is terminated and relaunched. If you are running jobs sequentially
  or with a small number of workers, this could halt your entire study until you manually kill and
  relaunch it. In the Ray parallel backend, we've implemented a system to automatically terminate jobs
  exceeding a specified timeout. This feature is particularly useful when task hanging limits your
  experiments.



  For debugging, run experiments with `n_jobs=1` and use VSCode's debug mode. This allows you to pause
  execution at breakpoints.



  Running one agent on one task corresponds to a single job. Conducting ablation studies or random
  searches across hundreds of tasks with multiple seeds can generate more than 10,000 jobs. Efficient
  parallel execution is therefore critical. Agents typically wait for responses from the LLM server or
  updates from the web server. As a result, you can run 10–50 jobs in parallel on a single computer,
  depending on available RAM.

  ⚠️ **Note for (Visual)WebArena**: These benchmarks have task dependencies designed to minimize
  "corrupting" the instance between tasks. For example, an agent on task 323 could alter the instance
  state, making task 201 impossible. To address this, the Ray backend accounts for task dependencies,
  enabling some degree of parallelism. On WebArena, you can disable dependencies to increase
  parallelism, but this might reduce performance by 1–2%.

  ⚠️ **Instance Reset for (Visual)WebArena**: Before evaluating an agent, the instance is
  automatically reset, a process that takes about 5 minutes. When evaluating multiple agents, the
  `make_study` function returns a `SequentialStudies` object to ensure proper sequential evaluation of
  each agent. AgentLab currently does not support evaluations across multiple instances, but you could
  either create a quick script to handle this or submit a PR to AgentLab. For a smoother parallel
  experience, consider using benchmarks like WorkArena instead.





  The class [`ExpResult`](https://github.com/ServiceNow/BrowserGym/blob/da26a5849d99d9a3169d7b1fde79f909c55c9ba7/browsergym/experiments/src/browsergym/experiments/loop.py#L595) provides a lazy loader for all the information of a specific experiment. You can use [`yield_all_exp_results`](https://github.com/ServiceNow/BrowserGym/blob/da26a5849d99d9a3169d7b1fde79f909c55c9ba7/browsergym/experiments/src/browsergym/experiments/loop.py#L872) to recursivley find all results in a directory. Finally [`load_result_df`](https://github.com/ServiceNow/AgentLab/blob/be1998c5fad5bda47ba50497ec3899aae03e85ec/src/agentlab/analyze/inspect_results.py#L119C5-L119C19) gathers all the summary information in a single dataframe. See [`inspect_results.ipynb`](src/agentlab/analyze/inspect_results.ipynb) for example usage.

  ```python
  from agentlab.analyze import inspect_results
  result_df = inspect_results.load_result_df("path/to/your/study")
  ```




  https://github.com/user-attachments/assets/06c4dac0-b78f-45b7-9405-003da4af6b37

  In a terminal, execute:
  ```bash
  agentlab-xray
  ```

  You can load previous or ongoing experiments in the directory `AGENTLAB_EXP_ROOT` and visualize
  the results in a gradio interface.

  In the following order, select:
  * The experiment you want to visualize
  * The agent if there is more than one
  * The task
  * And the seed

  Once this is selected, you can see the trace of your agent on the given task. Click on the profiling
  image to select a step and observe the action taken by the agent.


  **⚠️ Note**: Gradio is still in developement and unexpected behavior have been frequently noticed. Version 5.5 seems to work properly so far. If you're not sure that the proper information is displaying, refresh the page and select your experiment again.




  Get inspiration from the `MostBasicAgent` in
  [agentlab/agents/most_basic_agent/most_basic_agent.py](src/agentlab/agents/most_basic_agent/most_basic_agent.py).
  For a better integration with the tools, make sure to implement most functions in the
  [AgentArgs](src/agentlab/agents/agent_args.py#L5) API and the extended `bgym.AbstractAgentArgs`.

  If you think your agent should be included directly in AgenLab, let us know and it can be added in
  agentlab/agents/ with the name of your agent.


  Several factors can influence reproducibility of results in the context of evaluating agents on
  dynamic benchmarks.


  * **Software version**: Different version of Playwright or any package in the software stack could
    influence the behavior of the benchmark or the agent.
  * **API based LLMs silently changing**: Even for a fixed version, an LLM may be updated e.g. to
    incorporate latest web knowledge.
  * **Live websites**:
    * WorkArena: The demo instance is mostly fixed in time to a specific version but ServiceNow
      sometime push minor modifications.
    * AssistantBench and GAIA: These rely on the agent navigating the open web. The experience may
      change depending on which country or region, some websites might be in different languages by
      default.
  * **Stochastic Agents**: Setting temperature of the LLM to 0 can reduce most stochasticity.
  * **Non deterministic tasks**: For a fixed seed, the changes should be minimal


  * `Study` contains a dict of information about reproducibility, including benchmark version, package
    version and commit hash
  * The `Study` class allows automatic upload of your results to
    [`reproducibility_journal.csv`](reproducibility_journal.csv). This makes it easier to populate a
    large amount of reference points.
  * **Reproduced results in the leaderboard**. For agents that are repdocudibile, we encourage users
    to try to reproduce the results and upload them to the leaderboard. There is a special column
    containing information about all reproduced results of an agent on a benchmark.
  * **ReproducibilityAgent**: [You can run this agent](src/agentlab/agents/generic_agent/reproducibility_agent.py) on an existing study and it will try to re-run
    the same actions on the same task seeds. A vsiual diff of the two prompts will be displayed in the
    AgentInfo HTML tab of AgentXray. You will be able to inspect on some tasks what kind of changes
    between to two executions. **Note**: this is a beta feature and will need some adaptation for your
    own agent.




  if you want to download HF models more quickly
  ```
  pip install hf-transfer
  pip install torch
  export HF_HUB_ENABLE_HF_TRANSFER=1
  ```


pkgId: 5043df94f800aa275094bfce444311063750c34d46cccb281d34b236155e7fa5
name: python-agentlabs
arch: src
version: 0.1.0
epoch: 0
release: 1
summary: agentlabs: A Python library for implementing agents on Weavel
url: https://pypi.org/project/agentlabs/
rpm_license: UNKNOWN
rpm_group: Unspecified
rpm_buildhost: localhost
location_href: Packages/python-agentlabs-0.1.0-1.src.rpm
checksum_type: sha256
description:
  > Python library for implementing agents on [Weavel](https://weavel.vercel.app)



  ```bash
  pip install agentlabs
  ```



  ```python
  from agentlabs import Agent, InputType

  agent = Agent()


  @agent.service(
      id=3,
      name="blog_post",
      description="Given a keyword as input, this service generates a SEO-optimized blog post",
  )
  @agent.service_input(
      name="keyword",
      display_name="키워드",
      description="The keyword for which the blog post should be generated",
      type=InputType.TEXT,
      options=[
          "아로니아",
          "아로니아 농장",
      ],
  )
  @agent.service_input(
      name="post_length",
      display_name="글 길이",
      description="Desired length of the blog post",
      type=InputType.TEXT,
      placeholder="Medium",
      options=[
          "Short",
          "Medium",
          "Long",
      ],
  )
  async def generate_blog(keyword: str):
      await agent.aupdate_status("Generating blog outline...")
      await agent.aupdate_status("Writing post...")
      await agent.aupdate_status("Searching for images...")
      await agent.aupdate_status("Adding images to post...")
      await agent.aupdate_status("Generating title...")
      return {
          "blog": "블로그",
      }


  if __name__ == "__main__":
      agent.run(token="5f2593e7-1a10-492e-a9c1-e7521d400e2b")

  ```


pkgId: 78d791907c05c3fad91a85a0015af88f3203dcd10d95432ea98cd34e9c200643
name: python-agentlens
arch: src
version: 0.1.17
epoch: 0
release: 1
summary: lightweight abstractions for building agent scaffolds
url: https://pypi.org/project/agentlens/
rpm_license: None
rpm_group: Unspecified
rpm_buildhost: localhost
location_href: Packages/python-agentlens-0.1.17-1.src.rpm
checksum_type: sha256
description:
  This library contains a set of lightweight abstractions for building agent scaffolds that are easy to evaluate and maintain.

  ```bash
  pip install agentlens
  ```


  - [Configuration](#configuration)
  - [Tasks](#tasks)
  - [Inference](#inference)
  - [Datasets](#datasets)
  - [Evaluation](#evaluation)



  The basic building block of the library is a **task** -- an asynchronous function decorated with `@task`. Tasks have access to customizable context variables via the `lens` object, whose state is initialized automatically when some top-level task is called in your application.



  When tasks are called, they will automatically initialize a `Run` context if one has not already been initialized by a parent task. This contains metadata that groups together all of the tasks that are called within the same run.

  If tasks are run from the CLI, then a new run directory with a unique ID will be created, and each task will be able to read and write files to this directory as well as to subdirectories nested in the same hierarchy in which the tasks are called.

  e.g.:

  ```bash
  agentlens run path/to/file.py task_name
  ```

  Then tasks will be able to read and write files to the run directory, e.g.:

  ```python
  import json

  from agentlens import lens, task

  @task
  def write_report():
      (lens.run.dir / "report.md").write_text("...")


  @task
  def write_output():
      (lens.task.dir / "output.json").write_text(json.dumps({"result": 42}))
  ```

  This provides a flexible way to observe the behavior of your agent as it runs.



  You can define context objects using the `@context` decorator and provide them to all nested tasks like so:

  ```python
  from agentlens import context, task, lens, provide


  @context
  class State:
      some_value: int


  @task
  async def main_task():
      state = State(some_value=1)

      with provide(state):
          result = await nested_task()
          return result + 1  # 2


  @task
  async def nested_task():
      state = lens[State]  # access the State object, erroring if none is provided
      return state.some_value  # 1
  ```

  These context variables are async-friendly and thread-safe. They will only be accessible by code that is nested within the context manager that provides them.

  You can delete or set context variables like so:

  ```python
  @task
  async def nested_task():
      del lens[State]  # delete the State object
      lens[State] = State(some_value=2)  # set the State object
  ```

  Todo: describe how this is implemented using contextvars...




  Hooks are functions that can modify the behavior of tasks. They can take any of the tasks arguments and can modify the arguments that the task is called with by passing in a dictionary of keyword arguments to the `yield` statement:

  ```python
  from agentlens import task, provide, lens
  import agentlens.evaluation as ev

  @ev.hook(some_task)
  def hook_some_task(a: int) -> ev.GeneratorHook[int]:
      state = lens[State]
      state.a += 1
      task_output = yield {"a": a + 1}  # modify the arguments that the task is called with
      state.a += 1


  @task
  async def eval_some_task():
      state = State(a=1)
      hooks = [hook_some_task]

      with provide(state, hooks=hooks):
          return await some_task()

      (lens / "report.md").write_text(f"a: {state.a}")
  ```



  Often you will want to run a particular slice of the graph in isolation
  to do this, you can attach mock functions to your tasks, which should adopt the
  same interface as the task itself -- potentially reading from your database or local
  filesystem to provide the necessary data, instead of calling expensive third-party APIs
  like inference providers.

  This API makes no assumptions about how your backend works


  The arguments and return types must match that of the target function (the
  arguments can be a subset of the target function's arguments)
  This will be checked at runtime, similar to how hooks are validated.
  This behavior can be turned off in the Lens config with `strict=False`.

  Mocks are functions that can be used to replace the behavior of other functions for the purpose of testing. They are defined using the `@mock` decorator, and they can be used to replace the behavior of other functions by passing in a `replace` argument to the `provide` context manager.

  ```python
  import agentlens.evaluation as ev


  @ev.mock(some_task)
  def mock_some_task(a: int) -> int:
      return a + 1


  @task
  async def eval_some_task():
      mocks = [mock_some_task]
      with provide(mocks=mocks):
          return await some_task(1)  # 2
  ```

  This will replace the behavior of `some_task` with that of the mock function.

  If you want finer-grained control over mocking behavior--e.g. if you are running a certain task in a loop and only want to mock the first few calls--you can simply delete the mock from the `lens` object, and since this uses contextvars, it will only affect tasks nested below.

  ```python
  @task
  async def eval_some_task():
      with provide(mocks=[mock_some_task]):
          for i in range(10):
              if i < 3:
                  with remove(mock_some_task):
                      await some_task(1)  # 1
              else:
                  await some_task(1)  # 2
      ```



  The library exposes a boilerplate-free wrapper around the OpenAI and Anthropic APIs.

  In the simplest case, you might just want to feed some model a user prompt and (optionally) a system prompt, and have it return a string using `generate_text`:

  ```python
  from agentlens import generate_text, OpenAI, Anthropic


  anthropic = Anthropic(
      api_key="...",
      max_connections_default=10,
      max_connections={
          "claude-3-5-sonnet": 30,
      },
  )

  openai = OpenAI(
      api_key="...",
      max_connections_default=10,
      max_connections={
          "gpt-4o-mini": 30,
      },
  )


  @task
  async def summarize(text: str) -> str:
      return await generate_text(
          model=anthropic / "claude-3-5-sonnet",
          system="You are a helpful assistant.",
          prompt=f"""
              Please summarize the following text:

              {text}
              """,
          dedent=True,  # defaults to True, eliminating indents from all prompts using textwrap.dedent
          max_retries=3,  # number of retries on failure, defaults to 3
      )
  ```

  To phrase more complex requests, you may opt to pass the model a list of messages:

  ```python
  from PIL import Image


  @task
  async def transcribe_pdf(image: Image.Image) -> str:
      return await generate_text(
          model=openai / "gpt-4o-mini",
          messages=[
              ai.message.system("You are a helpful assistant."),
              ai.message.user(
                  "Please transcribe the following PDF page to Markdown:",
                  ai.message.image(image),
              ),
          ],
      )
  ```
  > If you pass a `messages` argument, an exception will be raised if you also pass a `system` or `prompt` argument.

  To request a structured output from the model, you can use `generate_object` and pass a Pydantic model as the `schema` argument.

  ```python
  from pydantic import BaseModel


  class PDFMetadata(BaseModel):
      title: str | None
      author: str | None


  @task
  async def extract_pdf_metadata(image: Image) -> PDFMetadata:
      return await generate_object(
          model=openai / "gpt-4o",
          schema=PDFMetadata,
          messages=[
              ai.message.system("You are a helpful assistant."),
              ai.message.user(
                  "Extract metadata from the following PDF page:",
                  ai.message.image(image),
              ),
          ],
      )
  ```


pkgId: 3c9f06123b91deda5dc2bd0283f79257ae2f932f5fbe53e1e4783f19d6eb03ba
name: python-agentlens
arch: src
version: 0.1.8
epoch: 0
release: 1
summary: lightweight abstractions for building agent scaffolds
url: https://pypi.org/project/agentlens/
rpm_license: None
rpm_group: Unspecified
rpm_buildhost: localhost
location_href: Packages/python-agentlens-0.1.8-1.src.rpm
checksum_type: sha256
description:
  This library contains a set of lightweight abstractions for building agent scaffolds that are easy to evaluate and maintain.

  ```bash
  pip install agentlens
  ```



  - **Decorator-driven logic**—define arbitrarily complex scaffolds and evaluations by composing functions
  - **Expressive evaluation framework**—run evals with hooks for full control over your agent's computation graph
  - **Type-safe datasets**—bootstrap type-safe, validated datasets with zero boilerplate
  - **Built-in observability**—easy integration with Langfuse
  - **Clean inference API**—call models using a syntax inspired by Vercel's very elegant [AI SDK](https://sdk.vercel.ai/docs/introduction)


  - [Configuration](#configuration)
  - [Tasks](#tasks)
  - [Inference](#inference)
  - [Datasets](#datasets)
  - [Evaluation](#evaluation)



  Initialize a `Lens` object to manage your project's observability and evaluation logic, and an `AI` object for clean access to OpenAI and Anthropic models.

  ```python


  import os
  from pathlib import Path

  from dotenv import load_dotenv

  from agentlens import AI, Lens, OpenAIProvider, AnthropicProvider

  load_dotenv()

  ROOT_DIR = Path(__file__).parent

  ls = Lens(
      runs_dir=ROOT_DIR / "runs",  # where to store runs
      dataset_dir=ROOT_DIR / "datasets",  # where to store datasets
  )

  ai = AI(
      providers=[
          OpenAIProvider(
              api_key=os.environ["OPENAI_API_KEY"],
              max_connections={ # global concurrency limits set on a per-model basis
                  "DEFAULT": 10,
                  "o1-preview": 2,
                  "gpt-4o-mini": 30,
              },
          ),
          AnthropicProvider(
              api_key=os.environ["ANTHROPIC_API_KEY"],
              max_connections={
                  "DEFAULT": 10,
                  "claude-3-5-sonnet": 5,
              },
          ),
      ],
  )
  ```
  By default API keys will be read from environment variables, but you can also pass them in directly.



  The basic building block of the library is a **task**. A task is a function that makes one or more calls to an AI model.

  Declaring a function as a task enters it into a unified observability and evaluation ecosystem. Do so using the `task` decorator on the `Lens` object:

  ```python
  from your_project.config import ls


  @ls.task()
  def some_task(some_input: str) -> str:
      pass  # insert some AI logic here
  ```

  The `task` decorator takes the following optional arguments:
  - `name: str | None = None`--a name for the task, which will be used in the UI and in logging
  - `max_retries: int = 0`--number of retries on failure, defaults to 0



  The library exposes a boilerplate-free wrapper around the OpenAI and Anthropic APIs.

  In the simplest case, you might just want to feed some model a user prompt and (optionally) a system prompt, and have it return a string using `generate_text`:

  ```python
  from your_project.config import ai, ls


  @ls.task()
  async def summarize(text: str) -> str:
      return await ai.generate_text(
          model="gpt-4o-mini",
          system="You are a helpful assistant.",
          prompt=f"""
              Please summarize the following text:

              {text}
              """,
          dedent=True,  # defaults to True, eliminating indents from all prompts using textwrap.dedent
          max_attempts=3,  # number of retries on failure, defaults to 3
      )
  ```

  To phrase more complex requests, you may opt to pass the model a list of messages:

  ```python
  from PIL import Image
  from your_project.config import ai, ls


  @ls.task()
  async def transcribe_pdf(image: Image.Image) -> str:
      return await ai.generate_text(
          model="gpt-4o-mini",
          messages=[
              ai.message.system("You are a helpful assistant."),
              ai.message.user(
                  "Please transcribe the following PDF page to Markdown:",
                  ai.message.image(image),
              ),
          ],
      )
  ```
  > If you pass a `messages` argument, an exception will be raised if you also pass a `system` or `prompt` argument.

  To request a structured output from the model, you can use `generate_object` and pass a Pydantic model as the `type` argument.

  ```python
  class PDFMetadata(BaseModel):
      title: str | None
      author: str | None


  @ls.task()
  async def extract_pdf_metadata(image: Image) -> PDFMetadata:
      return await ai.generate_object(
          model="gpt-4o",
          type=PDFMetadata,
          messages=[
              ai.message.system("You are a helpful assistant."),
              ai.message.user(
                  "Extract metadata from the following PDF page:",
                  ai.message.image(image),
              ),
          ],
      )
  ```



  The library exposes an ORM-like API for developing evaluation datasets.

  A `Dataset` is defined by a `Row` schema and a name. The name will identify it in the datasets directory, as well as in the UI and in eval logs.

  `Row` is just like a normal Pydantic model, except it will not error on missing labels when you load the dataset -- it will only error if you try to access a missing label, e.g. in a hook. This allows you to progressively bootstrap type-safe labels.

  ```python
  from datetime import datetime
  from agentlens import Dataset, Example, Label


  class InvoiceExample(Example):
      markdown: str
      date: str
      total_cost: float = Label()
      contains_error: bool = Label()



  class InvoiceDataset(Dataset[InvoiceExample]):
      def __init__(self, subset: str | None = None):
          super().__init__(name="invoices", lens=ls, subset=subset)

      def filter(self, row: InvoiceExample):
          if self.subset == "september":
              return row.date_created.month == 9
          else:
              raise ValueError("Subset not implemented")



  example1 = InvoiceExample(markdown="invoice1...", date="2024-09-01")
  example2 = InvoiceExample(markdown="invoice2...", date="2024-09-02")


  dataset = InvoiceDataset()


  dataset.extend([example1, example2])


  for row in dataset:
      print(row.markdown)  # type-safe


  first_example = dataset[0]
  specific_example = dataset["some_example_id"]


  first_example.total_cost = 100  # set a Label
  print(first_example.total_cost)  # access a Label (throws error if not set)


  dataset.save()


  september_invoices = InvoiceDataset("september")
  ```



  The evaluation API uses hooks to give you fine-grained control over your agent's computation graph, and you can run them either from a Jupyter cell or from the CLI.

  First let's define a simple set of tasks, riffing off of the invoice data structure we defined in the `Dataset` section:

  ```python
  @ls.task()
  async def process_invoice(invoice: str) -> float | str:
      looks_fine = await check_integrity(invoice)

      if not looks_fine:
          return await generate_error_report(invoice)

      return await extract_total_cost(invoice)


  @ls.task()
  async def check_integrity(invoice: str, model: str = "gpt-4o-mini") -> bool:
      return await ai.generate_object(
          model=model,
          type=bool,
          prompt=f"Return True if the invoice looks uncorrupted: {invoice.text}",
      )


  @ls.task()
  async def generate_error_report(invoice: str) -> str:
      return await ai.generate_text(
          model="gpt-4o",
          prompt=f"Write an error report for this corrupted invoice: {invoice.text}",
      )


  @ls.task()
  async def extract_total_cost(invoice: str, model: str = "gpt-4o") -> float:
      return await ai.generate_object(
          model=model,
          type=float,
          prompt=f"Extract the total cost from this invoice: {invoice.text}",
      )
  ```

  The first thing we'll want to do is bootstrap labels for our `InvoiceDataset`. This is easy to do using the hooks system.

  We will use hooks to:
  1. Modify the `check_integrity` and `extract_total_cost` tasks to use the `o1-preview` model, which is the most expensive and capable model available
  2. Write the results to the dataset as target labels

  ```python
  @ls.hook(check_integrity, "wrap")
  def boot_check_integrity(example, state, *args, **kwargs):
      kwargs["model"] = "o1-preview"
      output = yield args, kwargs
      example.contains_error = not output


  @ls.hook(extract_total_cost, "wrap")
  def boot_extract_total_cost(example, state, *args, **kwargs):
      kwargs["model"] = "o1-preview"
      output = yield args, kwargs
      example.total_cost = output


  @ls.task()
  def bootstrap_invoice_labels():
      dataset = InvoiceDataset("september")
      with ls.context(
          hooks=[
              boot_check_integrity,
              boot_extract_total_cost,
          ]
      ):

          def eval(example):
              return process_invoice(example.markdown)

          dataset.run(eval)
          dataset.save()

  bootstrap_invoice_labels()
  ```

  Now that we have labels, we can evaluate the `check_integrity` and `extract_total_cost` tasks as they were originally defined.

  TODO: describe how to run evals from the CLI + the console UI / writing files

  ```python

  @dataclass
  class State:
      total_cost_diffs: list[float]
      correct_integrities: list[bool]


  @ls.hook(check_integrity, "post")
  def hook_check_integrity(example, state, output, *args, **kwargs):
      score = output == example.contains_error
      state.correct_integrities.append(score)


  @ls.hook(extract_total_cost, "post")
  def hook_extract_total_cost(example, state, output, *args, **kwargs):
      score = output == example.total_cost
      state.total_cost_diffs.append(score)


  def eval_process_invoice(subset):
      dataset = InvoiceDataset(subset)
      state = State(total_cost_diffs=[], correct_integrities=[])

      with ls.context(
          state=state,
          hooks=[
              hook_check_integrity,
              hook_extract_total_cost,
          ],
      ):

          def eval(example):
              return process_invoice(example.markdown)

          results = dataset.run(eval)

          (ls / "report.md").write_text(f"""
              Average total cost error: {sum(state.total_cost_diffs) / len(state.total_cost_diffs)}
              Percent integrity correct: {sum(state.correct_integrities) / len(state.correct_integrities)}
              First result: {results[0]}
          """)
  ```

  This process is I/O bound, so we'll want to run it asynchronously. The library maxes out your call rate on a per-model basis and prioritizes completing tasks in order.

  ```python
  @ls.task()
  async def eval_process_invoice_async(subset):
      dataset = InvoiceDataset(subset)
      state = State(total_cost_diffs=[], correct_integrities=[])

      async with ls.eval_context(
          state=state,
          hooks=[
              hook_check_integrity,
              hook_extract_total_cost,
          ],
          cache=[check_integrity, extract_total_cost],
      ):

          async def eval(example):
              return await process_invoice(example.markdown)

          results = await dataset.run(eval)

          (ls / "report.md").write_text(f"""
              Average total cost error: {sum(state.total_cost_diffs) / len(state.total_cost_diffs)}
              Percent integrity correct: {sum(state.correct_integrities) / len(state.correct_integrities)}
              First result: {results[0]}
          """)
  ```


pkgId: 696936675d1f00dae852b1eac7e988bcdedc07af81f1eac639f3c403ca1d3856
name: python-agentlib
arch: src
version: 0.8.2
epoch: 0
release: 1
summary: Framework for development and execution of agents for control and simulation of energy systems.
url: https://pypi.org/project/agentlib/
rpm_license: BSD-3-Clause
rpm_group: Unspecified
rpm_buildhost: localhost
location_href: Packages/python-agentlib-0.8.2-1.src.rpm
checksum_type: sha256
description:
  <img src="./docs/images/logos/agentlib_logo/logo.svg" alt="drawing" height="150"/>


  [![License](https://img.shields.io/badge/License-BSD%203--Clause-blue.svg)](https://opensource.org/licenses/BSD-3-Clause)
  [![Coverage](https://rwth-ebc.github.io/AgentLib/main/coverage/badge.svg)](https://rwth-ebc.github.io/AgentLib/main/coverage/)
  [![pylint](https://rwth-ebc.github.io/AgentLib/main/pylint/pylint.svg)](https://rwth-ebc.github.io/AgentLib/main/pylint/pylint.html)
  [![documentation](https://rwth-ebc.github.io/AgentLib/main/docs/doc.svg)](https://rwth-ebc.github.io/AgentLib/main/docs/index.html)


  This is a collection of base classes for the implementation of agents in Python.
  The original purpose of this library is the execution of distributed simulations and controllers for energy systems, however it is not limited to any specific field.
  To get started, please check out our examples.



  To install the agentlib with minimal dependencies, run:

  ```
  pip install agentlib
  ```

  To install with full dependencies (recommended), run:
  ```
  pip install agentlib[full]
  ```

  If you want to work on the agentlib, first clone it, go its directory and then install it in editable mode:

  ```
  pip install -e .[full]
  ```


  The AgentLib has a number of optional dependencies, ranging from additional features to performance improvements:

   - **fmu**: Support simulation of FMU models (https://fmi-standard.org/).
   - **scipy**: Support simulation of linear state space models, based on scipy.
   - **mqtt**: Support communication between agents through the mqtt protocol.
   - **plot**: Installs matplotlib, allows to plot the result of examples.
   - **orjson**: Faster json library, improves performance when using network communicators.
   - **fuzz**: Improves error messages when providing wrong configurations.

  **clonemap**: Support the execution of agents and their communication through [clonemap](https://github.com/sogno-platform/clonemap). As clonemapy is not available through PYPI, please install it from source, or through the AgentLib's ``requirements.txt`` .



  A publication regarding the AgentLib is currently in the work.
  If you use the AgentLib in your work which you plan to publish, please check back at a later date for a reference.



  This project is licensed under the BSD 3 Clause License - see the [LICENSE](LICENSE) file for details.



  We gratefully acknowledge the financial support by Federal Ministry \\ for Economic Affairs and Climate Action (BMWK), promotional reference 03ET1495A.

  <img src="./docs/images/logos/BMWK_logo.png" alt="BMWK" width="200"/>


pkgId: 9509d13ea1e4b86b93dfe6aaac675593c486b157a81a266bbf57c42e1ce90b42
name: python-agentlib
arch: src
version: 0.8.4
epoch: 0
release: 1
summary: Framework for development and execution of agents for control and simulation of energy systems.
url: https://pypi.org/project/agentlib/
rpm_license: BSD-3-Clause
rpm_group: Unspecified
rpm_buildhost: localhost
location_href: Packages/python-agentlib-0.8.4-1.src.rpm
checksum_type: sha256
description:
  <img src="./docs/images/logos/agentlib_logo/logo.svg" alt="drawing" height="150"/>


  [![License](https://img.shields.io/badge/License-BSD%203--Clause-blue.svg)](https://opensource.org/licenses/BSD-3-Clause)
  [![Coverage](https://rwth-ebc.github.io/AgentLib/main/coverage/badge.svg)](https://rwth-ebc.github.io/AgentLib/main/coverage/)
  [![pylint](https://rwth-ebc.github.io/AgentLib/main/pylint/pylint.svg)](https://rwth-ebc.github.io/AgentLib/main/pylint/pylint.html)
  [![documentation](https://rwth-ebc.github.io/AgentLib/main/docs/doc.svg)](https://rwth-ebc.github.io/AgentLib/main/docs/index.html)


  This is a collection of base classes for the implementation of agents in Python.
  The original purpose of this library is the execution of distributed simulations and controllers for energy systems, however it is not limited to any specific field.
  To get started, please check out our examples.



  To install the agentlib with minimal dependencies, run:

  ```
  pip install agentlib
  ```

  To install with full dependencies (recommended), run:
  ```
  pip install agentlib[full]
  ```

  If you want to work on the agentlib, first clone it, go its directory and then install it in editable mode:

  ```
  pip install -e .[full]
  ```


  The AgentLib has a number of optional dependencies, ranging from additional features to performance improvements:

   - **fmu**: Support simulation of FMU models (https://fmi-standard.org/).
   - **scipy**: Support simulation of linear state space models, based on scipy.
   - **mqtt**: Support communication between agents through the mqtt protocol.
   - **plot**: Installs matplotlib, allows to plot the result of examples.
   - **orjson**: Faster json library, improves performance when using network communicators.
   - **fuzz**: Improves error messages when providing wrong configurations.

  **clonemap**: Support the execution of agents and their communication through [clonemap](https://github.com/sogno-platform/clonemap). As clonemapy is not available through PYPI, please install it from source, or through the AgentLib's ``requirements.txt`` .



  A publication regarding the AgentLib is currently in the work.
  A preprint is available under http://dx.doi.org/10.2139/ssrn.4884846 and can be cited as:

  > Eser, Steffen and Storek, Thomas and Wüllhorst, Fabian and Dähling, Stefan and Gall, Jan and Stoffel, Phillip and Müller, Dirk, A Modular Python Framework for Rapid Development of Advanced Control Algorithms for Energy Systems. Available at SSRN: https://ssrn.com/abstract=4884846 or http://dx.doi.org/10.2139/ssrn.4884846



  This project is licensed under the BSD 3 Clause License - see the [LICENSE](LICENSE) file for details.



  We gratefully acknowledge the financial support by Federal Ministry \\ for Economic Affairs and Climate Action (BMWK), promotional references 03ET1495A and 03EN1006A.

  <img src="./docs/images/logos/BMWK_logo.png" alt="BMWK" width="200"/>


pkgId: d18991ca07c85facbcfb0845449fcdae85b0e4734a111d5f7bb0b742fae61f23
name: python-agently-workflow
arch: src
version: 0.1.0
epoch: 0
release: 1
url: https://pypi.org/project/agently-workflow/
rpm_license: None
rpm_group: Unspecified
rpm_buildhost: localhost
location_href: Packages/python-agently-workflow-0.1.0-1.src.rpm
checksum_type: sha256
summary:
  A standalone workflow spun off from [Agently](https://github.com/Maplemx/Agently), featuring minimal third-party dependencies (e.g., json5).


pkgId: 343c44c7f7c1257c7d7972b829a5cb2bfd4ed99a3020dec995a292ff25ece018
name: python-agentmatrix
arch: src
version: 0.2.0
epoch: 0
release: 1
summary: A multi-agent system for processing queries using DuckDuckGo and LLM agents
url: https://github.com/kiranbeethoju/agentmatrix
rpm_license: None
rpm_group: Unspecified
rpm_buildhost: localhost
location_href: Packages/python-agentmatrix-0.2.0-1.src.rpm
checksum_type: sha256
description:
  A Python package that implements agentmatrix a multi-agent system for processing queries using DuckDuckGo and LLM agents.



  ```bash
  pip install agentmatrix
  ```



  ```python
  from agentmatrix import MultiAgentSystem


  mas = MultiAgentSystem()


  mas.add_duckduckgo_agent()
  mas.add_llm_agent(api_key="your-api-key", model="gpt-4")


  result = mas.process_query(
      search_term="Your search term",
      expert_type="Expert type",
      expert_description="Expert description",
      user_prompt="Your prompt",
      response_format="json",
      listed_urls=["https://example.com"]
  )

  print(result)
  ```



  This project is licensed under the MIT License.


  requests==2.26.0
  openai==0.27.0


  __pycache__/
  *.py[cod]
  *.so
  .Python
  build/
  develop-eggs/
  dist/
  downloads/
  eggs/
  .eggs/
  lib/
  lib64/
  parts/
  sdist/
  var/
  wheels/
  *.egg-info/
  .installed.cfg
  *.egg
  MANIFEST
  .env


pkgId: 25948d56afa0b440e3f42ff505d41d5b6f6a75ea4745b1e0440074af133b752e
name: python-agentmemory
arch: src
version: 0.4.8
epoch: 0
release: 1
summary: Easy-to-use memory for agents, document search, knowledge graphing and more.
url: https://github.com/AutonomousResearchGroup/agentmemory
rpm_license: MIT
rpm_group: Unspecified
rpm_buildhost: localhost
location_href: Packages/python-agentmemory-0.4.8-1.src.rpm
checksum_type: sha256
description:
  The `set_epoch` function sets the epoch in the agent's memory to the specified value.
  **Arguments:**
  - `epoch` (int): The desired epoch value.
  **Usage:**
  ```python
  set_epoch(epoch)
  ```
  **Example:**
  ```python
  set_epoch(5)


pkgId: e06a0088a25f8a2e593782eccd65518ab96033a526301531854dd9a6309a4a43
name: python-agentools
arch: src
version: 0.5.10
epoch: 0
release: 1
summary: please add a summary manually as the author left a blank one
url: https://pypi.org/project/agentools/
rpm_license: None
rpm_group: Unspecified
rpm_buildhost: localhost
location_href: Packages/python-agentools-0.5.10-1.src.rpm
checksum_type: sha256
description:
  A simple set of modules, wrappers and utils that are essential for LLM-based assistants and agents using the OpenAI API and function tools. It is useful for:

  - **OpenAI API:** Simple wrapper for the OpenAI API to provide mocked endpoints for easy testing without costing money, accumulating the delta chunks from streamed responses into partial responses, and easier token counting/tracking.
  - **Function Tools:** Easily convert any (async) python function into a function tool that the LLM model can call, with automatic validation and retrying with error messages.
  - **Structured Data:** Easily define a Pydantic model that can be generated by the LLM model, also with validation and retries.
  - **Assistants:** Event-based architecture with async generators that yield events that you can iterate through and handle only the events you care about, such as whether you want to stream the response or not, cancel the generation prematurely, or wait for user input (human-in-the-loop) before continuing, etc.
  - **Copilots:** Integrate right into an editor with stateful system messages to allow the copilot to see the latest state of the editor and function tools to interact with the editor.

  **Yet to come:**

  - **Agents:** Autoprompting, self-prompting, chain-of-thought, sketchpads, memory management, planning, and more.
  - **Multi-Agents**: Communication channels, organization structuring, and more.





  ```bash
  pip install agentools
  ```




  A high-level interface to use ChatGPT or other LLM-based assistants! The default implementation of ChatGPT has:

  - a message history to remember the conversation so far (including the system prompt)
  - ability to use tools
  - efficient async streaming support
  - simple way to customize/extend/override the default behavior



  ```python
  from agentools import *


  model = ChatGPT()
  ```

  You can then simply call the model as if it was a function, with a prompt:



  ```python
  await model("Hey!")
  ```





  > <code>'Hello! How can I assist you today?'</code><br/>


  As you can see, the model is async and it simply returns the resonse as a string.

  Both your prompt and the response are stored in the history, so you can keep calling the model with new prompts and it will remember the conversation so far.



  ```python
  await model("Can you repeat my last message please?")
  ```





  > <code>'Of course! You said, "Hey!"'</code><br/>



  ```python
  model.messages.history
  ```





  > <code>[{'role': 'user', 'content': 'Hey!'},</code><br/>
  > <code> {'content': 'Hello! How can I assist you today?', 'role': 'assistant'},</code><br/>
  > <code> {'role': 'user', 'content': 'Can you repeat my last message please?'},</code><br/>
  > <code> {'content': 'Of course! You said, "Hey!"', 'role': 'assistant'}]</code><br/>




  Notice that our model has no system prompt in the beginning. `ChatGPT`'s constructor by default creates an empty chat history, but you can explicitly create a `MessageHistory` object and pass it to the constructor:



  ```python
  translate = ChatGPT(
      messages=SimpleHistory.system("Translate the user message to English")
  )


  print(await translate("Ich liebe Katzen!"))
  print(await translate("고양이랑 강아지 둘다 좋아!"))
  ```


  > <code>I love cats!</code><br/>
  > <code>I like both cats and dogs!</code><br/>

  ```python
  translate.messages.history
  ```





  > <code>[{'role': 'system', 'content': 'Translate the user message to English'},</code><br/>
  > <code> {'role': 'user', 'content': 'Ich liebe Katzen!'},</code><br/>
  > <code> {'content': 'I love cats!', 'role': 'assistant'},</code><br/>
  > <code> {'role': 'user', 'content': '고양이랑 강아지 둘다 좋아!'},</code><br/>
  > <code> {'content': 'I like both cats and dogs!', 'role': 'assistant'}]</code><br/>


  Notice that here, we're wasting tokens by remembering the chat history, since it's not really a conversation. There's a simple `GPT` class, which simply resets the message history after each prompt:



  ```python
  translate = GPT(messages=SimpleHistory.system("Translate the user message to English"))

  await translate("Ich liebe Katzen!")
  await translate("고양이랑 강아지 둘다 좋아!")

  translate.messages.history
  ```





  > <code>[{'role': 'system', 'content': 'Translate the user message to English'}]</code><br/>




  You can set the default model in the constructor, or override it for each prompt:



  ```python

  model = ChatGPT(model="gpt-4")


  await model("Heyo!", model="mocked")
  ```





  > <code>'Hello, world!'</code><br/>


  As you see, our wrapper provides a simple mocked "model", which will simply return `"Hello, world!"` for any prompt, with some simulated latency. This will also work with streaming responses, and in either cases, you won't be able to tell the difference between the real API and the mocked one.

  There are more mocked models for your convinience:

  - `mocked`: always returns `"Hello, world!"`
  - `mocked:TEST123`: returns the string after the colon, e.g. `"TEST123"`
  - `echo`: returns the user prompt itself

  Let's print all events to the console to take a peek at the event-based generator:



  ```python
  await model("Heya!", model="echo", event_logger=print)
  ```


  > <code>[ResponseStartEvent]: prompt=Heya!, tools=None, model=echo, max_function_calls=100, openai_kwargs={}</code><br/>
  > <code>[CompletionStartEvent]: call_index=0</code><br/>
  > <code>[CompletionEvent]: completion=ChatCompletion(id='mock', choices=[Choice(finish_reason='stop', index=0, logprobs=None, message=ChatCompletionMessage(content='Heya!', role='assistant', function_call=None, tool_calls=None))], created=1721161834, model='mock', object='chat.completion', service_tier=None, system_fingerprint=None, usage=None), call_index=0</code><br/>
  > <code>[FullMessageEvent]: message=ChatCompletionMessage(content='Heya!', role='assistant', function_call=None, tool_calls=None), choice_index=0</code><br/>
  > <code>[TextMessageEvent]: content=Heya!</code><br/>
  > <code>[ResponseEndEvent]: content=Heya!</code><br/>




  > <code>'Heya!'</code><br/>


  Wow, quite a lot going on for a simple prompt! While it might seem like too many events, this offers a lot of flexibility and customizability.

  You can easily handle only the events you are interested in, useful when e.g:

  - updating the frontend when streaming the responses,
  - cancelling the generation early,
  - or implementing human-in-the-loop for function calls.

  For instance, the `GPT` class from above is as simple as:

  ```python
  async for event in self.response_events(prompt, **openai_kwargs):
      match event:
          case self.ResponseEndEvent():
              await self.messages.reset()
              return event.content
  ```

  This generator-based architecture is a good balance between flexibility and simplicity!

  While we won't go deeper into the low-level API in this quickstart, you can look at the `advanced.ipynb` notebook for more details.




  You can turn any function into a tool usable by the model by decorating it with `@function_tool`:



  ```python
  @function_tool
  def print_to_console(text: str) -> str:
      """
      Print text to console

      Args:
          text: text to print
      """
      print(text)
      return "success"  # the model will see the return value



  print_to_console("Hello from python!")
  ```


  > <code>Hello from python!</code><br/>




  > <code>'success'</code><br/>


  You can use the tool from python as you normally would, and the model will also be able to use it simply by passing it to the `tools` parameter during init (as default) or prompting it (as a one-off).



  ```python
  model = ChatGPT(tools=print_to_console)
  await model("Say 'hello from GPT' to console!")
  ```


  > <code>hello from GPT</code><br/>




  > <code>'The message "hello from GPT" has been successfully printed to the console.'</code><br/>


  To make the function a `@function_tool`, you must do the following:

  - The parameters must be type annotated, and all parameters must be JSON-serializable (e.g. `str`, `int`, `float`, `bool`, `list`, `dict`, `None`, etc).
  - The return type should be a `str` or something that can be converted to a `str`.
  - It must be documented with a `'''docstring'''`, including each parameter (most [formats supported](https://github.com/rr-/docstring_parser), e.g. [Google-style](https://gist.github.com/redlotus/3bc387c2591e3e908c9b63b97b11d24e#file-docstrings-py-L67), [NumPy-style](https://gist.github.com/eikonomega/910512d92769b0cc382a09ae4de41771), sphinx-style, etc, see [this overview](https://gist.github.com/nipunsadvilkar/fec9d2a40f9c83ea7fd97be59261c400))


  Showing off some more goodies:

  - Even async functions should seamlessly work, just don't forget to `await` them.
  - `@fail_with_message(err)` is a decorator that will catch any exceptions thrown by the function and instead return the error message. This is useful for when you want to handle errors in a more graceful way than just crashing the model. It also takes an optional logger, which by default takes the `print` function, but any callable that takes a string will work, such as `logger.error` from the `logging` module.
  - Usually, the `@function_tool` decorator will throw an assertion error if you forget to provide the description for any of the function or their parameters. If you really don't want to provide descriptions for some (or all), maybe because it's so self-explanatory or you need to save tokens, then you can explicitly turn off the docstring parsing by passing `@function_tool(check_description=False)`. This is not recommended, but it's there if you need it.

  Note that by returning descriptive error strings, the model can read the error message and retry, increasing the robustness!



  ```python
  import asyncio
  import logging


  @function_tool(name="Fibonacci", require_doc=False)
  @fail_with_message("Error", logger=logging.error)
  async def fib(n: int):
      if n < 0:
          raise ValueError("n must be >= 0")
      if n < 2:
          return n

      await asyncio.sleep(0.1)
      return sum(await asyncio.gather(fib(n - 1), fib(n - 2)))


  await fib(-10)
  ```


  > <code>ERROR:root:Tool call fib(-10) failed: n must be >= 0</code><br/>




  > <code>'Error: n must be >= 0'</code><br/>




  Toolkits are a collection of related function tools, esp. useful when they share a state. Also good for keeping the state bound to a single instance of the toolkit, rather than a global state.
  To create a toolkit, simply subclass `Toolkit` and decorate its methods with `@function_tool`.



  ```python
  class Notepad(Toolkit):
      def __init__(self):
          super().__init__()
          self.content = "<Fill me in>"

      @function_tool
      def write(self, text: str):
          """
          Write text to the notepad

          Args:
              text: The text to write
          """
          self.content = text

      @function_tool(require_doc=False)
      def read(self):
          return self.content


  notes = Notepad()
  notes.write("Shhh... here's a secret: 42")
  notes.read()
  ```





  > <code>"Shhh... here's a secret: 42"</code><br/>


  As before, simply pass the toolkit to the model. To use multiple tools and toolkits, simply put them in a list:



  ```python
  model = ChatGPT(
      tools=[notes, print_to_console, fib],
  )

  await model("What's on my notepad?")
  ```





  > <code>'On your notepad, it says: "Shhh... here\'s a secret: 42"'</code><br/>



  ```python
  await model(
      "Can you calculate the 8th fibonacci number, add it to the number in my notes, and write it? also print it to console as well.",
      event_logger=lambda x: print(x) if x.startswith("[Tool") else None,
      parallel_tool_calls=False,
  )
  ```


  > <code>[ToolCallsEvent]: tool_calls=[ChatCompletionMessageToolCall(id='call_wxaisBbFMYRa0XNcTnP9MH1b', function=Function(arguments='{"n":8}', name='Fibonacci'), type='function')]</code><br/>
  > <code>[ToolResultEvent]: result=21, tool_call=ChatCompletionMessageToolCall(id='call_wxaisBbFMYRa0XNcTnP9MH1b', function=Function(arguments='{"n":8}', name='Fibonacci'), type='function'), index=0</code><br/>
  > <code>[ToolCallsEvent]: tool_calls=[ChatCompletionMessageToolCall(id='call_gt5ZnA5v2VJL5R2gyPeHRN0a', function=Function(arguments='{"text":"The sum of the 8th Fibonacci number (21) and the number on your notepad (42) is 63"}', name='write'), type='function')]</code><br/>
  > <code>[ToolResultEvent]: result=None, tool_call=ChatCompletionMessageToolCall(id='call_gt5ZnA5v2VJL5R2gyPeHRN0a', function=Function(arguments='{"text":"The sum of the 8th Fibonacci number (21) and the number on your notepad (42) is 63"}', name='write'), type='function'), index=0</code><br/>
  > <code>[ToolCallsEvent]: tool_calls=[ChatCompletionMessageToolCall(id='call_ErYx6g7gpVTnLsqg59oxHI9C', function=Function(arguments='{"text":"The sum of the 8th Fibonacci number (21) and the number on your notepad (42) is 63"}', name='print_to_console'), type='function')]</code><br/>
  > <code>The sum of the 8th Fibonacci number (21) and the number on your notepad (42) is 63</code><br/>
  > <code>[ToolResultEvent]: result=success, tool_call=ChatCompletionMessageToolCall(id='call_ErYx6g7gpVTnLsqg59oxHI9C', function=Function(arguments='{"text":"The sum of the 8th Fibonacci number (21) and the number on your notepad (42) is 63"}', name='print_to_console'), type='function'), index=0</code><br/>




  > <code>'I have written on your notepad. The sum of the 8th Fibonacci number (21) and the number on your notepad (42) is 63. I have also printed it to the console.'</code><br/>



  ```python
  notes.read()
  ```





  > <code>'The sum of the 8th Fibonacci number (21) and the number on your notepad (42) is 63'</code><br/>


  Notice how since our `write` function doesn't return anything, it defaults to `None` and our model gets confused! So don't forget to return an encouraging success message to make our model happy :)




  When using streaming, and you're using function tools with a long input, you might want to preview the tool's output before it's fully processed. With the help of the `json_autocomplete` package, the JSON argument generated by the model can be parsed before it's fully complete, and the preview can be shown to the user.



  ```python
  @function_tool(require_doc=False)
  async def create_slogan(title: str, content: str):
      print(f"\n\n[Final Slogan] {title}: {content}")
      return "Slogan created and shown to user! Simply tell the user that it was created."


  @create_slogan.preview
  async def preview(title: str = "", content: str = ""):
      assert isinstance(title, str) and isinstance(content, str)
      print(f"[Preview] {title}: {content}", flush=True)
  ```


  ```python
  model = ChatGPT(tools=create_slogan)
  await model(
      "Create a 1-sentence slogan about how ducks can help with debugging.", stream=True
  )
  ```


  > <code>[Preview] : </code><br/>
  > <code>[Preview] D: </code><br/>
  > <code>[Preview] Ducks: </code><br/>
  > <code>[Preview] Ducks and: </code><br/>
  > <code>[Preview] Ducks and Debug: </code><br/>
  > <code>[Preview] Ducks and Debugging: </code><br/>
  > <code>[Preview] Ducks and Debugging: </code><br/>
  > <code>[Preview] Ducks and Debugging: Qu</code><br/>
  > <code>[Preview] Ducks and Debugging: Quack</code><br/>
  > <code>[Preview] Ducks and Debugging: Quack your</code><br/>
  > <code>[Preview] Ducks and Debugging: Quack your code</code><br/>
  > <code>[Preview] Ducks and Debugging: Quack your code bugs</code><br/>
  > <code>[Preview] Ducks and Debugging: Quack your code bugs away</code><br/>
  > <code>[Preview] Ducks and Debugging: Quack your code bugs away with</code><br/>
  > <code>[Preview] Ducks and Debugging: Quack your code bugs away with the</code><br/>
  > <code>[Preview] Ducks and Debugging: Quack your code bugs away with the help</code><br/>
  > <code>[Preview] Ducks and Debugging: Quack your code bugs away with the help of</code><br/>
  > <code>[Preview] Ducks and Debugging: Quack your code bugs away with the help of a</code><br/>
  > <code>[Preview] Ducks and Debugging: Quack your code bugs away with the help of a debugging</code><br/>
  > <code>[Preview] Ducks and Debugging: Quack your code bugs away with the help of a debugging duck</code><br/>
  > <code>[Preview] Ducks and Debugging: Quack your code bugs away with the help of a debugging duck by</code><br/>
  > <code>[Preview] Ducks and Debugging: Quack your code bugs away with the help of a debugging duck by your</code><br/>
  > <code>[Preview] Ducks and Debugging: Quack your code bugs away with the help of a debugging duck by your side</code><br/>
  > <code>[Preview] Ducks and Debugging: Quack your code bugs away with the help of a debugging duck by your side.</code><br/>
  > <code>[Preview] Ducks and Debugging: Quack your code bugs away with the help of a debugging duck by your side.</code><br/>
  > <code>[Final Slogan] Ducks and Debugging: Quack your code bugs away with the help of a debugging duck by your side.</code><br/>




  > <code>'I have created a slogan about how ducks can help with debugging!'</code><br/>


  If you need a more coherent logic shared between the `@preview` and the final `@function_tool`, e.g. do something at the start of the function call, share some data between previews, etc... It gets messy very fast!

  Instead, you can use the `@streaming_function_tool()` decorator, which receives a single `arg_stream` parameter, which is an async generator that yields the partial arguments, as streamed from the model. Therefore, you simply need to iterate through it, and perform the actual function call at the end of the iteration. The following is the equivalent of the previous example:

  > _Note that currently, you must pass the parameter as a `schema` (either JSON Schema or Pydantic BaseModel)._



  ```python
  from pydantic import BaseModel, Field


  class Slogan(BaseModel):
      """A slogan for a product"""

      title: str = Field(description="MUST BE EXACTLY 3 WORDS!")
      content: str = Field(description="less than 10 words")


  @streaming_function_tool(schema=Slogan)
  async def create_slogan(arg_stream):
      print("Starting slogan creation...")

      async for args in arg_stream:
          title, content = args.get("title", ""), args.get("content", "")
          print(f'{args} -> "{title}", "{content}"', flush=True)

      print(f"\n\n[Final Slogan] {title}: {content}")
      return "Slogan created and shown to user! Simply tell the user that it was created."
  ```


  ```python
  model = ChatGPT(tools=create_slogan)
  await model(
      "Create a 1-sentence slogan about how ducks can help with debugging.", stream=True
  )
  ```


  > <code>Starting slogan creation...</code><br/>
  > <code>{'': None} -> "", ""</code><br/>
  > <code>{'title': None} -> "None", ""</code><br/>
  > <code>{'title': ''} -> "", ""</code><br/>
  > <code>{'title': 'Debug'} -> "Debug", ""</code><br/>
  > <code>{'title': 'Debugging'} -> "Debugging", ""</code><br/>
  > <code>{'title': 'Debugging Ducks'} -> "Debugging Ducks", ""</code><br/>
  > <code>{'title': 'Debugging Ducks', '': None} -> "Debugging Ducks", ""</code><br/>
  > <code>{'title': 'Debugging Ducks', 'content': None} -> "Debugging Ducks", "None"</code><br/>
  > <code>{'title': 'Debugging Ducks', 'content': ''} -> "Debugging Ducks", ""</code><br/>
  > <code>{'title': 'Debugging Ducks', 'content': 'Qu'} -> "Debugging Ducks", "Qu"</code><br/>
  > <code>{'title': 'Debugging Ducks', 'content': 'Quack'} -> "Debugging Ducks", "Quack"</code><br/>
  > <code>{'title': 'Debugging Ducks', 'content': 'Quack through'} -> "Debugging Ducks", "Quack through"</code><br/>
  > <code>{'title': 'Debugging Ducks', 'content': 'Quack through errors'} -> "Debugging Ducks", "Quack through errors"</code><br/>
  > <code>{'title': 'Debugging Ducks', 'content': 'Quack through errors effortlessly'} -> "Debugging Ducks", "Quack through errors effortlessly"</code><br/>
  > <code>{'title': 'Debugging Ducks', 'content': 'Quack through errors effortlessly.'} -> "Debugging Ducks", "Quack through errors effortlessly."</code><br/>
  > <code>{'title': 'Debugging Ducks', 'content': 'Quack through errors effortlessly.'} -> "Debugging Ducks", "Quack through errors effortlessly."</code><br/>
  > <code>{'title': 'Debugging Ducks', 'content': 'Quack through errors effortlessly.'} -> "Debugging Ducks", "Quack through errors effortlessly."</code><br/>
  > <code>[Final Slogan] Debugging Ducks: Quack through errors effortlessly.</code><br/>




  > <code>'I have created a slogan: "Debugging Ducks - Quack through errors effortlessly."'</code><br/>




  We can very easily define a Pydantic model that can be generated by the LLM model, with validation and retries:



  ```python
  from enum import StrEnum
  from pydantic import BaseModel, Field


  class Language(StrEnum):
      EN = "en"
      DE = "de"
      KO = "ko"


  class Song(BaseModel):
      title: str
      genres: list[str] = Field(description="AT LEAST 3 genres!")
      duration: float
      language: Language
      has_lyrics: bool



  Song(title="Hello", genres=["pop"], duration=3.5, language=Language.EN, has_lyrics=True)
  ```





  > <code>Song(title='Hello', genres=['pop'], duration=3.5, language=<Language.EN: 'en'>, has_lyrics=True)</code><br/>


  Create a `StructGPT` object with your pydantic model, and prompting it will always return a valid instance of the model, or raise an exception if it fails to generate a valid instance after the maximum number of retries. Your docstring and field descriptions will also be visible to the model, so make sure to write good descriptions!



  ```python
  generate_song = StructGPT(Song)

  await generate_song("Come up with an all-time best K-hiphop song")
  ```





  > <code>Song(title='Eternal Sunshine', genres=['Hip-hop', 'R&B', 'K-pop'], duration=240.0, language=<Language.KO: 'ko'>, has_lyrics=True)</code><br/>




  Streaming can be enabled as usual by passing `stream=True` when prompting, and handle the partial events as they come in. Check the `Assistant` class for a list of events including the ones for streaming.

  There are some other useful utilities in the `utils` module, such as:

  - `tokens`: for token counting
  - `trackers`: for transparent token tracking and prompt/response logging


pkgId: a6e1fad3f2313d4c1a3ab1b9e2213a6675e728316e48d8eeea12f79c3612c106
name: python-agentopia
arch: src
version: 0.1.0
epoch: 0
release: 1
summary: please add a summary manually as the author left a blank one
url: https://pypi.org/project/agentopia/
rpm_license: None
rpm_group: Unspecified
rpm_buildhost: localhost
location_href: Packages/python-agentopia-0.1.0-1.src.rpm
checksum_type: sha256
description:
  ![Agentopia Logo](./logo.png)


  - Add superpowers to your AI agent. Our SDK empowers AI agents to discover and pay for services, products, and other agents on demand—seamlessly and autonomously.
  - Devs, you can easily:
    - Add new capabilities to your AI agent 10x faster. Discover and pay for services, APIs, data set or infra your AI agent needs. 100% automated, no credit cards or bank account needed
    - Sell your products & services to AI agents. Build and monetise your own service or remix the existing ones to build new ones and start earning instantly. No permissions required.



  ```bash
  pip install agentopia
  ```



  You can build a API/Data service and sell it on Agentopia Marketplace where users/AI Agents can pay for your service on per use basis with USDC on the base blockchain.





  ```python
  from fastapi import FastAPI, Request
  from fastapi.responses import JSONResponse
  from agentopia import payable

  app = FastAPI()

  @app.get("/hello_world")
  @payable(
      hold_amount=100000, hold_expires_in=3600
  )  # Hold $0.1 in the users account for 1hr
  async def hello_world(
      request: Request,
  ):
      print("Executing hello_world endpoint")
      
      print("Preparing response with $0.000001 charge")
      response = JSONResponse(
          content={"message": "Hello from Agentopia!"}, headers={"X-Usdc-Used": "1"}
      )
      print("Returning response")
      return response
  ```

  Github link to this repo is here: [Hello World Service](https://github.com/nurturelabs-co/example_agentopia_services/tree/main/hello_world)



  ```python
  import json
  import os

  import httpx
  import requests
  from fastapi import FastAPI, HTTPException, Request, status
  from fastapi.responses import JSONResponse, StreamingResponse
  from agentopia import Agentopia  # type: ignore

  app = FastAPI()

  OPENROUTER_API_KEY = os.getenv("OPENROUTER_API_KEY")
  if not OPENROUTER_API_KEY:
      raise Exception("OPENROUTER_API_KEY environment variable not set")


  @app.post("/chat/completions")
  async def chat_completions(request: Request):
      print("Starting payable stream wrapper")
      
      x_hold_id = request.headers.get("X-Hold-Id")

      if x_hold_id is None:
          print("No hold ID provided, raising 402 error")
          raise HTTPException(
              status_code=status.HTTP_402_PAYMENT_REQUIRED,
              detail="A Agentopia `X-Hold-Id` header is required",
          )

      print(f"Received hold ID: {x_hold_id}")

      
      print("Creating Agentopia client")
      agentopia_client = Agentopia()

      
      print(f"Verifying hold {x_hold_id}")
      try:
          x_hold = agentopia_client.hold.get(x_hold_id)
          print(f"Hold verification successful: {x_hold}")
      except requests.exceptions.HTTPError:
          print("Hold verification failed")
          raise HTTPException(
              status_code=status.HTTP_402_PAYMENT_REQUIRED,
              detail="Invalid hold ID",
          )

      try:
          
          body = await request.json()

          
          async with httpx.AsyncClient() as client:
              headers = {
                  "Authorization": f"Bearer {OPENROUTER_API_KEY}",
                  "HTTP-Referer": "https://agentopia.xyz",
                  "X-Title": "Agentopia LLM Service",
              }

              
              if body.get("stream", False):
                  response = await client.post(
                      "https://openrouter.ai/api/v1/chat/completions",
                      json=body,
                      headers=headers,
                      follow_redirects=True,
                      timeout=30.0,
                  )

                  async def generate():
                      try:
                          async for line in response.aiter_lines():
                              if line:
                                  
                                  if (
                                      line.strip() == ""
                                      or "OPENROUTER PROCESSING" in line
                                  ):
                                      continue

                                  
                                  if line.startswith("data: "):
                                      line = line[6:]  # Remove "data: " prefix

                                  try:
                                      parsed_line = json.loads(line)
                                      if "error" in parsed_line:
                                          raise HTTPException(
                                              status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                                              detail=parsed_line["error"],
                                          )
                                      
                                      yield f"data: {json.dumps(parsed_line)}\n\n"
                                  except json.JSONDecodeError:
                                      print(f"JSONDecodeError on line: {line}")
                                      continue

                          yield "data: [DONE]\n\n"
                      finally:
                          
                          print(f"Releasing hold {x_hold_id} with amount 1000")
                          try:
                              agentopia_client.hold.release(hold_id=x_hold_id, amount=1000)
                              print("Hold released successfully")
                          except requests.exceptions.HTTPError:
                              print("Failed to release hold")
                              raise HTTPException(
                                  status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                                  detail="Failed to process payment",
                              )

                  return StreamingResponse(
                      generate(),
                      media_type="text/event-stream",
                      headers={
                          "Content-Type": "text/event-stream",
                          "Cache-Control": "no-cache",
                          "Connection": "keep-alive",
                          "X-Usdc-Used": "1000",
                      },
                  )

              
              response = await client.post(
                  "https://openrouter.ai/api/v1/chat/completions",
                  json=body,
                  headers=headers,
              )

              
              try:
                  agentopia_client.hold.release(hold_id=x_hold_id, amount=1000)
                  print("Hold released successfully")
              except requests.exceptions.HTTPError:
                  print("Failed to release hold")
                  raise HTTPException(
                      status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                      detail="Failed to process payment",
                  )

              return JSONResponse(
                  content=response.json(), headers={"X-Usdc-Used": "1000"}
              )

      except Exception as e:
          raise HTTPException(
              status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e)
          )

  ```

  Github link to this repo is here: [Open Router Service](https://github.com/nurturelabs-co/example_agentopia_services/tree/main/llm_service)



  You need to register your service on Agentopia Marketplace to make it available for users to use.

  ```python
  from agentopia import Agentopia, AgentopiaServiceModel
  agentopia_client = Agentopia(private_key="your_private_key")

  service: AgentopiaServiceModel = agentopia_client.service.register(
      name="Hello World",
      description="A simple hello world service",
      base_url="http://api.hello.world",
      slug="hello-world-1234",
      initial_hold_amount=100000,  # $0.1 USDC
      initial_hold_expires_in=3600,  # 1 hour
      api_schema_url="http://api.hello.world/openapi.json",
  )
  ```





  ```python
  from agentopia import Agentopia
  agentopia_client = Agentopia(private_key="your_private_key")
  balance = agentopia_client.get_balance()
  ```



  ```python
  from agentopia import Agentopia
  agentopia_client = Agentopia(private_key="your_private_key")
  agentopia_client.withdraw(amount=100000)
  ```

  This will initiate a withdrawal request which will be processed in a few minutes on the base blockchain.



  Search and use services on Agentopia Marketplace.



  ```python
  from agentopia import Agentopia
  agentopia_client = Agentopia(private_key="your_private_key")
  agentopia_client.deposit(amount=1000_000)
  ```

  This will initiate a deposit of 1 USDC (the values used in the SDK are in micro USDC) request which will be processed in a few minutes on the base blockchain.



  ```python
  from agentopia import Agentopia
  agentopia_client = Agentopia(private_key="your_private_key")
  response = agentopia_client.service.execute_via_proxy(
      service_slug="hello-world-1234", endpoint_path="hello_world", method="GET"
  )
  print(response)
  ```



  If you have any questions or feedback, please contact us at

  - [Telegram](https://t.me/yashdotagarwal)
  - [Twitter](https://x.com/yashdotagarwal)
  - [Email](mailto:yash@nurturelabs.co)


pkgId: 20cea23ef983b8844ed6ccaa8ff48b64ed1f2867118e1cda1562b2c38c8b1a08
name: python-agentopia
arch: src
version: 0.1.4
epoch: 0
release: 1
summary: please add a summary manually as the author left a blank one
url: https://pypi.org/project/agentopia/
rpm_license: None
rpm_group: Unspecified
rpm_buildhost: localhost
location_href: Packages/python-agentopia-0.1.4-1.src.rpm
checksum_type: sha256
description:
  <img alt="Logo" align="right" src="https://raw.githubusercontent.com/nurturelabs-co/Agentopia/main/logo.png" width="20%" />

  - Add superpowers to your AI agent. Our SDK empowers AI agents to discover and pay for services, products, and other agents on demand—seamlessly and autonomously.
  - Devs, you can easily:
    - Add new capabilities to your AI agent 10x faster. Discover and pay for services, APIs, data set or infra your AI agent needs. 100% automated, no credit cards or bank account needed
    - Sell your products & services to AI agents. Build and monetise your own service or remix the existing ones to build new ones and start earning instantly. No permissions required.



  ```bash
  pip install agentopia
  ```



  You can build a API/Data service and sell it on Agentopia Marketplace where users/AI Agents can pay for your service on per use basis with USDC on the base blockchain.





  ```python
  from fastapi import FastAPI, Request
  from fastapi.responses import JSONResponse
  from agentopia import payable

  app = FastAPI()

  @app.get("/hello_world")
  @payable(
      hold_amount=100000, hold_expires_in=3600
  )  # Hold $0.1 in the users account for 1hr
  async def hello_world(
      request: Request,
  ):
      print("Executing hello_world endpoint")
      
      print("Preparing response with $0.000001 charge")
      response = JSONResponse(
          content={"message": "Hello from Agentopia!"}, headers={"X-Usdc-Used": "1"}
      )
      print("Returning response")
      return response
  ```

  Github link to this repo is here: [Hello World Service](https://github.com/nurturelabs-co/example_agentopia_services/tree/main/hello_world)



  ```python
  import json
  import os

  import httpx
  import requests
  from fastapi import FastAPI, HTTPException, Request, status
  from fastapi.responses import JSONResponse, StreamingResponse
  from agentopia import Agentopia  # type: ignore

  app = FastAPI()

  OPENROUTER_API_KEY = os.getenv("OPENROUTER_API_KEY")
  if not OPENROUTER_API_KEY:
      raise Exception("OPENROUTER_API_KEY environment variable not set")


  @app.post("/chat/completions")
  async def chat_completions(request: Request):
      print("Starting payable stream wrapper")
      
      x_hold_id = request.headers.get("X-Hold-Id")

      if x_hold_id is None:
          print("No hold ID provided, raising 402 error")
          raise HTTPException(
              status_code=status.HTTP_402_PAYMENT_REQUIRED,
              detail="A Agentopia `X-Hold-Id` header is required",
          )

      print(f"Received hold ID: {x_hold_id}")

      
      print("Creating Agentopia client")
      agentopia_client = Agentopia()

      
      print(f"Verifying hold {x_hold_id}")
      try:
          x_hold = agentopia_client.hold.get(x_hold_id)
          print(f"Hold verification successful: {x_hold}")
      except requests.exceptions.HTTPError:
          print("Hold verification failed")
          raise HTTPException(
              status_code=status.HTTP_402_PAYMENT_REQUIRED,
              detail="Invalid hold ID",
          )

      try:
          
          body = await request.json()

          
          async with httpx.AsyncClient() as client:
              headers = {
                  "Authorization": f"Bearer {OPENROUTER_API_KEY}",
                  "HTTP-Referer": "https://agentopia.xyz",
                  "X-Title": "Agentopia LLM Service",
              }

              
              if body.get("stream", False):
                  response = await client.post(
                      "https://openrouter.ai/api/v1/chat/completions",
                      json=body,
                      headers=headers,
                      follow_redirects=True,
                      timeout=30.0,
                  )

                  async def generate():
                      try:
                          async for line in response.aiter_lines():
                              if line:
                                  
                                  if (
                                      line.strip() == ""
                                      or "OPENROUTER PROCESSING" in line
                                  ):
                                      continue

                                  
                                  if line.startswith("data: "):
                                      line = line[6:]  # Remove "data: " prefix

                                  try:
                                      parsed_line = json.loads(line)
                                      if "error" in parsed_line:
                                          raise HTTPException(
                                              status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                                              detail=parsed_line["error"],
                                          )
                                      
                                      yield f"data: {json.dumps(parsed_line)}\n\n"
                                  except json.JSONDecodeError:
                                      print(f"JSONDecodeError on line: {line}")
                                      continue

                          yield "data: [DONE]\n\n"
                      finally:
                          
                          print(f"Releasing hold {x_hold_id} with amount 1000")
                          try:
                              agentopia_client.hold.release(hold_id=x_hold_id, amount=1000)
                              print("Hold released successfully")
                          except requests.exceptions.HTTPError:
                              print("Failed to release hold")
                              raise HTTPException(
                                  status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                                  detail="Failed to process payment",
                              )

                  return StreamingResponse(
                      generate(),
                      media_type="text/event-stream",
                      headers={
                          "Content-Type": "text/event-stream",
                          "Cache-Control": "no-cache",
                          "Connection": "keep-alive",
                          "X-Usdc-Used": "1000",
                      },
                  )

              
              response = await client.post(
                  "https://openrouter.ai/api/v1/chat/completions",
                  json=body,
                  headers=headers,
              )

              
              try:
                  agentopia_client.hold.release(hold_id=x_hold_id, amount=1000)
                  print("Hold released successfully")
              except requests.exceptions.HTTPError:
                  print("Failed to release hold")
                  raise HTTPException(
                      status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                      detail="Failed to process payment",
                  )

              return JSONResponse(
                  content=response.json(), headers={"X-Usdc-Used": "1000"}
              )

      except Exception as e:
          raise HTTPException(
              status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e)
          )

  ```

  Github link to this repo is here: [Open Router Service](https://github.com/nurturelabs-co/example_agentopia_services/tree/main/llm_service)



  You need to register your service on Agentopia Marketplace to make it available for users to use.

  ```python
  from agentopia import Agentopia, AgentopiaServiceModel
  agentopia_client = Agentopia(private_key="your_private_key")

  service: AgentopiaServiceModel = agentopia_client.service.register(
      name="Hello World",
      description="A simple hello world service",
      base_url="http://api.hello.world",
      slug="hello-world-1234",
      initial_hold_amount=100000,  # $0.1 USDC
      initial_hold_expires_in=3600,  # 1 hour
      api_schema_url="http://api.hello.world/openapi.json",
  )
  ```





  ```python
  from agentopia import Agentopia
  agentopia_client = Agentopia(private_key="your_private_key")
  balance = agentopia_client.get_balance()
  ```



  ```python
  from agentopia import Agentopia
  agentopia_client = Agentopia(private_key="your_private_key")
  agentopia_client.withdraw(amount=100000)
  ```

  This will initiate a withdrawal request which will be processed in a few minutes on the base blockchain.



  Search and use services on Agentopia Marketplace.



  ```python
  from agentopia import Agentopia
  agentopia_client = Agentopia(private_key="your_private_key")
  agentopia_client.deposit(amount=1000_000)
  ```

  This will initiate a deposit of 1 USDC (the values used in the SDK are in micro USDC) request which will be processed in a few minutes on the base blockchain.



  ```python
  from agentopia import Agentopia
  agentopia_client = Agentopia(private_key="your_private_key")
  response = agentopia_client.service.execute_via_proxy(
      service_slug="hello-world-1234", endpoint_path="hello_world", method="GET"
  )
  print(response)
  ```



  If you have any questions or feedback, please contact us at

  - [Telegram](https://t.me/yashdotagarwal)
  - [Twitter](https://x.com/yashdotagarwal)
  - [Email](mailto:yash@nurturelabs.co)


pkgId: 2a198d2fcb9e4905af02830425fe83d413b2fd3dc234112398ff9b4c89656e13
name: python-agentops
arch: src
version: 0.3.14
epoch: 0
release: 1
summary: Observability and DevTool Platform for AI Agents
url: https://github.com/AgentOps-AI/agentops
rpm_license: None
rpm_group: Unspecified
rpm_buildhost: localhost
location_href: Packages/python-agentops-0.3.14-1.src.rpm
checksum_type: sha256
description:
  <div align="center">
    <a href="https://agentops.ai?ref=gh">
      <img src="docs/images/external/logo/banner-badge.png" style="max-width: 500px" width="50%" alt="Logo">
    </a>
  </div>

  <div align="center">
    <em>Observability and DevTool platform for AI Agents</em>
  </div>

  <br />

  <div align="center">
    <a href="https://pepy.tech/project/agentops">
      <img src="https://static.pepy.tech/badge/agentops/month" alt="Downloads">
    </a>
    <a href="https://github.com/agentops-ai/agentops/issues">
    <img src="https://img.shields.io/github/commit-activity/m/agentops-ai/agentops" alt="git commit activity">
    </a>
    <img src="https://img.shields.io/pypi/v/agentops?&color=3670A0" alt="PyPI - Version">
    <a href="https://opensource.org/licenses/MIT">
      <img src="https://img.shields.io/badge/License-MIT-yellow.svg?&color=3670A0" alt="License: MIT">
    </a>
  </div>

  <p align="center">
  <a href="https://twitter.com/agentopsai/">🐦 Twitter</a>
  <span>&nbsp;&nbsp;•&nbsp;&nbsp;</span>
  <a href="https://discord.gg/FagdcwwXRR">📢 Discord</a>
  <span>&nbsp;&nbsp;•&nbsp;&nbsp;</span>
  <a href="https://app.agentops.ai/?ref=gh">🖇️ Dashboard</a>
  <span>&nbsp;&nbsp;•&nbsp;&nbsp;</span>
  <a href="https://docs.agentops.ai/introduction">📙 Documentation</a>
  </p>

  <div style="justify-content: center">
    <img src="docs/images/external/app_screenshots/dashboard_banner.png" alt="Dashboard Banner">
  </div>

  <br/>


  AgentOps helps developers build, evaluate, and monitor AI agents. From prototype to production.

  |                                       |                                                               |
  | ------------------------------------- | ------------------------------------------------------------- |
  | 📊 **Replay Analytics and Debugging** | Step-by-step agent execution graphs                           |
  | 💸 **LLM Cost Management**            | Track spend with LLM foundation model providers               |
  | 🧪 **Agent Benchmarking**             | Test your agents against 1,000+ evals                         |
  | 🔐 **Compliance and Security**        | Detect common prompt injection and data exfiltration exploits |
  | 🤝 **Framework Integrations**         | Native Integrations with CrewAI, AutoGen, & LangChain         |



  ```bash
  pip install agentops
  ```




  Initialize the AgentOps client and automatically get analytics on all your LLM calls.

  [Get an API key](https://app.agentops.ai/settings/projects)

  ```python
  import agentops


  agentops.init( < INSERT YOUR API KEY HERE >)

  ...


  agentops.end_session('Success')
  ```

  All your sessions can be viewed on the [AgentOps dashboard](https://app.agentops.ai?ref=gh)
  <br/>

  <details>
    <summary>Agent Debugging</summary>
    <a href="https://app.agentops.ai?ref=gh">
      <img src="docs/images/external/app_screenshots/session-overview.png" style="width: 90%;" alt="Agent Debugging"/>
    </a>
  </details>

  <details>
    <summary>Session Replays</summary>
    <a href="https://app.agentops.ai?ref=gh">
      <img src="docs/images/external/app_screenshots/session-replay.png" style="width: 90%;" alt="Session Replays"/>
    </a>
  </details>

  <details open>
    <summary>Summary Analytics</summary>
    <a href="https://app.agentops.ai?ref=gh">
     <img src="docs/images/external/app_screenshots/overview.png" style="width: 90%;" alt="Summary Analytics"/>
    </a>
  </details>



  Add powerful observability to your agents, tools, and functions with as little code as possible: one line at a time.
  <br/>
  Refer to our [documentation](http://docs.agentops.ai)

  ```python

  from agentops import track_agent

  @track_agent(name='SomeCustomName')
  class MyAgent:
    ...
  ```

  ```python

  from agentops import record_tool

  @record_tool('SampleToolName')
  def sample_tool(...):
    ...
  ```

  ```python

  from agentops import record_action

  @agentops.record_action('sample function being record')
  def sample_function(...):
    ...
  ```

  ```python

  from agentops import record, ActionEvent

  record(ActionEvent("received_user_input"))
  ```





  Build Crew agents with observability with only 2 lines of code. Simply set an `AGENTOPS_API_KEY` in your environment, and your crews will get automatic monitoring on the AgentOps dashboard.

  ```bash
  pip install 'crewai[agentops]'
  ```

  - [AgentOps integration example](https://docs.agentops.ai/v1/integrations/crewai)
  - [Official CrewAI documentation](https://docs.crewai.com/how-to/AgentOps-Observability)


  With only two lines of code, add full observability and monitoring to Autogen agents. Set an `AGENTOPS_API_KEY` in your environment and call `agentops.init()`

  - [Autogen Observability Example](https://microsoft.github.io/autogen/docs/notebooks/agentchat_agentops)
  - [Autogen - AgentOps Documentation](https://microsoft.github.io/autogen/docs/ecosystem/agentops)



  AgentOps works seamlessly with applications built using Langchain. To use the handler, install Langchain as an optional dependency:

  <details>
    <summary>Installation</summary>

  ```shell
  pip install agentops[langchain]
  ```

  To use the handler, import and set

  ```python
  import os
  from langchain.chat_models import ChatOpenAI
  from langchain.agents import initialize_agent, AgentType
  from agentops.partners.langchain_callback_handler import LangchainCallbackHandler

  AGENTOPS_API_KEY = os.environ['AGENTOPS_API_KEY']
  handler = LangchainCallbackHandler(api_key=AGENTOPS_API_KEY, tags=['Langchain Example'])

  llm = ChatOpenAI(openai_api_key=OPENAI_API_KEY,
                   callbacks=[handler],
                   model='gpt-3.5-turbo')

  agent = initialize_agent(tools,
                           llm,
                           agent=AgentType.CHAT_ZERO_SHOT_REACT_DESCRIPTION,
                           verbose=True,
                           callbacks=[handler], # You must pass in a callback handler to record your agent
                           handle_parsing_errors=True)
  ```

  Check out the [Langchain Examples Notebook](./examples/langchain_examples.ipynb) for more details including Async handlers.

  </details>



  First class support for Cohere(>=5.4.0). This is a living integration, should you need any added functionality please message us on Discord!

  - [AgentOps integration example](https://docs.agentops.ai/v1/integrations/cohere)
  - [Official Cohere documentation](https://docs.cohere.com/reference/about)

  <details>
    <summary>Installation</summary>

  ```bash
  pip install cohere
  ```

  ```python python
  import cohere
  import agentops


  agentops.init(<INSERT YOUR API KEY HERE>)
  co = cohere.Client()

  chat = co.chat(
      message="Is it pronounced ceaux-hear or co-hehray?"
  )

  print(chat)

  agentops.end_session('Success')
  ```

  ```python python
  import cohere
  import agentops


  agentops.init(<INSERT YOUR API KEY HERE>)

  co = cohere.Client()

  stream = co.chat_stream(
      message="Write me a haiku about the synergies between Cohere and AgentOps"
  )

  for event in stream:
      if event.event_type == "text-generation":
          print(event.text, end='')

  agentops.end_session('Success')
  ```
  </details>




  Track agents built with the Anthropic Python SDK (>=0.32.0).

  - [AgentOps integration example](examples/anthropic-sdk/anthropic_example.ipynb)
  - [Official Anthropic documentation](https://docs.anthropic.com/en/docs/welcome)

  <details>
    <summary>Installation</summary>

  ```bash
  pip install anthropic
  ```

  ```python python
  import anthropic
  import agentops


  agentops.init(<INSERT YOUR API KEY HERE>)

  client = anthropic.Anthropic(
      
      api_key=os.environ.get("ANTHROPIC_API_KEY"),
  )

  message = client.messages.create(
          max_tokens=1024,
          messages=[
              {
                  "role": "user",
                  "content": "Tell me a cool fact about AgentOps",
              }
          ],
          model="claude-3-opus-20240229",
      )
  print(message.content)

  agentops.end_session('Success')
  ```

  Streaming
  ```python python
  import anthropic
  import agentops


  agentops.init(<INSERT YOUR API KEY HERE>)

  client = anthropic.Anthropic(
      
      api_key=os.environ.get("ANTHROPIC_API_KEY"),
  )

  stream = client.messages.create(
      max_tokens=1024,
      model="claude-3-opus-20240229",
      messages=[
          {
              "role": "user",
              "content": "Tell me something cool about streaming agents",
          }
      ],
      stream=True,
  )

  response = ""
  for event in stream:
      if event.type == "content_block_delta":
          response += event.delta.text
      elif event.type == "message_stop":
          print("\n")
          print(response)
          print("\n")
  ```

  Async

  ```python python
  import asyncio
  from anthropic import AsyncAnthropic

  client = AsyncAnthropic(
      
      api_key=os.environ.get("ANTHROPIC_API_KEY"),
  )


  async def main() -> None:
      message = await client.messages.create(
          max_tokens=1024,
          messages=[
              {
                  "role": "user",
                  "content": "Tell me something interesting about async agents",
              }
          ],
          model="claude-3-opus-20240229",
      )
      print(message.content)


  await main()
  ```
  </details>



  AgentOps provides support for LiteLLM(>=1.3.1), allowing you to call 100+ LLMs using the same Input/Output Format.

  - [AgentOps integration example](https://docs.agentops.ai/v1/integrations/litellm)
  - [Official LiteLLM documentation](https://docs.litellm.ai/docs/providers)

  <details>
    <summary>Installation</summary>

  ```bash
  pip install litellm
  ```

  ```python python






  import litellm
  ...
  response = litellm.completion(model="claude-3", messages=messages)

  response = await litellm.acompletion(model="claude-3", messages=messages)
  ```
  </details>




  AgentOps works seamlessly with applications built using LlamaIndex, a framework for building context-augmented generative AI applications with LLMs.

  <details>
    <summary>Installation</summary>

  ```shell
  pip install llama-index-instrumentation-agentops
  ```

  To use the handler, import and set

  ```python
  from llama_index.core import set_global_handler





  set_global_handler("agentops")
  ```

  Check out the [LlamaIndex docs](https://docs.llamaindex.ai/en/stable/module_guides/observability/?h=agentops#agentops) for more details.

  </details>



  <div style="justify-content: center">
    <img src="docs/images/external/app_screenshots/time_travel_banner.png" alt="Time Travel Banner">
  </div>

  <br />

  [Try it out!](https://app.agentops.ai/timetravel)



  (coming soon!)



  | Platform                                                                     | Dashboard                                  | Evals                                  |
  | ---------------------------------------------------------------------------- | ------------------------------------------ | -------------------------------------- |
  | ✅ Python SDK                                                                | ✅ Multi-session and Cross-session metrics | ✅ Custom eval metrics                 |
  | 🚧 Evaluation builder API                                                    | ✅ Custom event tag tracking               | 🔜 Agent scorecards                    |
  | ✅ [Javascript/Typescript SDK](https://github.com/AgentOps-AI/agentops-node) | ✅ Session replays                         | 🔜 Evaluation playground + leaderboard |



  | Performance testing                       | Environments                                                                        | LLM Testing                                 | Reasoning and execution testing                   |
  | ----------------------------------------- | ----------------------------------------------------------------------------------- | ------------------------------------------- | ------------------------------------------------- |
  | ✅ Event latency analysis                 | 🔜 Non-stationary environment testing                                               | 🔜 LLM non-deterministic function detection | 🚧 Infinite loops and recursive thought detection |
  | ✅ Agent workflow execution pricing       | 🔜 Multi-modal environments                                                         | 🚧 Token limit overflow flags               | 🔜 Faulty reasoning detection                     |
  | 🚧 Success validators (external)          | 🔜 Execution containers                                                             | 🔜 Context limit overflow flags             | 🔜 Generative code validators                     |
  | 🔜 Agent controllers/skill tests          | ✅ Honeypot and prompt injection detection ([PromptArmor](https://promptarmor.com)) | 🔜 API bill tracking                        | 🔜 Error breakpoint analysis                      |
  | 🔜 Information context constraint testing | 🔜 Anti-agent roadblocks (i.e. Captchas)                                            | 🔜 CI/CD integration checks                 |                                                   |
  | 🔜 Regression testing                     | 🔜 Multi-agent framework visualization                                              |                                             |                                                   |



  Without the right tools, AI agents are slow, expensive, and unreliable. Our mission is to bring your agent from prototype to production. Here's why AgentOps stands out:

  - **Comprehensive Observability**: Track your AI agents' performance, user interactions, and API usage.
  - **Real-Time Monitoring**: Get instant insights with session replays, metrics, and live monitoring tools.
  - **Cost Control**: Monitor and manage your spend on LLM and API calls.
  - **Failure Detection**: Quickly identify and respond to agent failures and multi-agent interaction issues.
  - **Tool Usage Statistics**: Understand how your agents utilize external tools with detailed analytics.
  - **Session-Wide Metrics**: Gain a holistic view of your agents' sessions with comprehensive statistics.

  AgentOps is designed to make agent observability, testing, and monitoring easy.




  Check out our growth in the community:

  <img src="https://api.star-history.com/svg?repos=AgentOps-AI/agentops&type=Date" style="max-width: 500px" width="50%" alt="Logo">




  | Repository | Stars  |
  | :--------  | -----: |
  |<img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/2707039?s=40&v=4" width="20" height="20" alt="">  &nbsp; [geekan](https://github.com/geekan) / [MetaGPT](https://github.com/geekan/MetaGPT) | 42787 |
  |<img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/130722866?s=40&v=4" width="20" height="20" alt="">  &nbsp; [run-llama](https://github.com/run-llama) / [llama_index](https://github.com/run-llama/llama_index) | 34446 |
  |<img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/170677839?s=40&v=4" width="20" height="20" alt="">  &nbsp; [crewAIInc](https://github.com/crewAIInc) / [crewAI](https://github.com/crewAIInc/crewAI) | 18287 |
  |<img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/134388954?s=40&v=4" width="20" height="20" alt="">  &nbsp; [camel-ai](https://github.com/camel-ai) / [camel](https://github.com/camel-ai/camel) | 5166 |
  |<img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/152537519?s=40&v=4" width="20" height="20" alt="">  &nbsp; [superagent-ai](https://github.com/superagent-ai) / [superagent](https://github.com/superagent-ai/superagent) | 5050 |
  |<img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/30197649?s=40&v=4" width="20" height="20" alt="">  &nbsp; [iyaja](https://github.com/iyaja) / [llama-fs](https://github.com/iyaja/llama-fs) | 4713 |
  |<img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/162546372?s=40&v=4" width="20" height="20" alt="">  &nbsp; [BasedHardware](https://github.com/BasedHardware) / [Omi](https://github.com/BasedHardware/Omi) | 2723 |
  |<img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/454862?s=40&v=4" width="20" height="20" alt="">  &nbsp; [MervinPraison](https://github.com/MervinPraison) / [PraisonAI](https://github.com/MervinPraison/PraisonAI) | 2007 |
  |<img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/140554352?s=40&v=4" width="20" height="20" alt="">  &nbsp; [AgentOps-AI](https://github.com/AgentOps-AI) / [Jaiqu](https://github.com/AgentOps-AI/Jaiqu) | 272 |
  |<img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/3074263?s=40&v=4" width="20" height="20" alt="">  &nbsp; [strnad](https://github.com/strnad) / [CrewAI-Studio](https://github.com/strnad/CrewAI-Studio) | 134 |
  |<img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/18406448?s=40&v=4" width="20" height="20" alt="">  &nbsp; [alejandro-ao](https://github.com/alejandro-ao) / [exa-crewai](https://github.com/alejandro-ao/exa-crewai) | 55 |
  |<img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/64493665?s=40&v=4" width="20" height="20" alt="">  &nbsp; [tonykipkemboi](https://github.com/tonykipkemboi) / [youtube_yapper_trapper](https://github.com/tonykipkemboi/youtube_yapper_trapper) | 47 |
  |<img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/17598928?s=40&v=4" width="20" height="20" alt="">  &nbsp; [sethcoast](https://github.com/sethcoast) / [cover-letter-builder](https://github.com/sethcoast/cover-letter-builder) | 27 |
  |<img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/109994880?s=40&v=4" width="20" height="20" alt="">  &nbsp; [bhancockio](https://github.com/bhancockio) / [chatgpt4o-analysis](https://github.com/bhancockio/chatgpt4o-analysis) | 19 |
  |<img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/14105911?s=40&v=4" width="20" height="20" alt="">  &nbsp; [breakstring](https://github.com/breakstring) / [Agentic_Story_Book_Workflow](https://github.com/breakstring/Agentic_Story_Book_Workflow) | 14 |
  |<img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/124134656?s=40&v=4" width="20" height="20" alt="">  &nbsp; [MULTI-ON](https://github.com/MULTI-ON) / [multion-python](https://github.com/MULTI-ON/multion-python) | 13 |


  _Generated using [github-dependents-info](https://github.com/nvuillam/github-dependents-info), by [Nicolas Vuillamy](https://github.com/nvuillam)_


pkgId: df892182c06e402d69c1e76ddf7ef1f1c8fa58b425c18a32adadf4f79efd829e
name: python-agentops
arch: src
version: 0.3.17
epoch: 0
release: 1
summary: Observability and DevTool Platform for AI Agents
url: https://github.com/AgentOps-AI/agentops
rpm_license: None
rpm_group: Unspecified
rpm_buildhost: localhost
location_href: Packages/python-agentops-0.3.17-1.src.rpm
checksum_type: sha256
description:
  <div align="center">
    <a href="https://agentops.ai?ref=gh">
      <img src="docs/images/external/logo/banner-badge.png" style="max-width: 500px" width="50%" alt="Logo">
    </a>
  </div>

  <div align="center">
    <em>Observability and DevTool platform for AI Agents</em>
  </div>

  <br />

  <div align="center">
    <a href="https://pepy.tech/project/agentops">
      <img src="https://static.pepy.tech/badge/agentops/month" alt="Downloads">
    </a>
    <a href="https://github.com/agentops-ai/agentops/issues">
    <img src="https://img.shields.io/github/commit-activity/m/agentops-ai/agentops" alt="git commit activity">
    </a>
    <img src="https://img.shields.io/pypi/v/agentops?&color=3670A0" alt="PyPI - Version">
    <a href="https://opensource.org/licenses/MIT">
      <img src="https://img.shields.io/badge/License-MIT-yellow.svg?&color=3670A0" alt="License: MIT">
    </a>
  </div>

  <p align="center">
    <a href="https://twitter.com/agentopsai/">
      <img src="https://img.shields.io/twitter/follow/agentopsai?style=social" alt="Twitter" style="height: 20px;">
    </a>
    <a href="https://discord.gg/FagdcwwXRR">
      <img src="https://img.shields.io/badge/discord-7289da.svg?style=flat-square&logo=discord" alt="Discord" style="height: 20px;">
    </a>
    <a href="https://app.agentops.ai/?ref=gh">
      <img src="https://img.shields.io/badge/Dashboard-blue.svg?style=flat-square" alt="Dashboard" style="height: 20px;">
    </a>
    <a href="https://docs.agentops.ai/introduction">
      <img src="https://img.shields.io/badge/Documentation-orange.svg?style=flat-square" alt="Documentation" style="height: 20px;">
    </a>
    <a href="https://entelligence.ai/AgentOps-AI&agentops">
      <img src="https://img.shields.io/badge/Chat%20with%20Docs-green.svg?style=flat-square" alt="Chat with Docs" style="height: 20px;">
    </a>
  </p>



  <div style="justify-content: center">
    <img src="docs/images/external/app_screenshots/dashboard-banner.png" alt="Dashboard Banner">
  </div>

  <br/>


  AgentOps helps developers build, evaluate, and monitor AI agents. From prototype to production.

  |                                       |                                                               |
  | ------------------------------------- | ------------------------------------------------------------- |
  | 📊 **Replay Analytics and Debugging** | Step-by-step agent execution graphs                           |
  | 💸 **LLM Cost Management**            | Track spend with LLM foundation model providers               |
  | 🧪 **Agent Benchmarking**             | Test your agents against 1,000+ evals                         |
  | 🔐 **Compliance and Security**        | Detect common prompt injection and data exfiltration exploits |
  | 🤝 **Framework Integrations**         | Native Integrations with CrewAI, AutoGen, & LangChain         |



  ```bash
  pip install agentops
  ```




  Initialize the AgentOps client and automatically get analytics on all your LLM calls.

  [Get an API key](https://app.agentops.ai/settings/projects)

  ```python
  import agentops


  agentops.init( < INSERT YOUR API KEY HERE >)

  ...


  agentops.end_session('Success')
  ```

  All your sessions can be viewed on the [AgentOps dashboard](https://app.agentops.ai?ref=gh)
  <br/>

  <details>
    <summary>Agent Debugging</summary>
    <a href="https://app.agentops.ai?ref=gh">
      <img src="docs/images/external/app_screenshots/session-drilldown-metadata.png" style="width: 90%;" alt="Agent Metadata"/>
    </a>
    <a href="https://app.agentops.ai?ref=gh">
      <img src="docs/images/external/app_screenshots/chat-viewer.png" style="width: 90%;" alt="Chat Viewer"/>
    </a>
    <a href="https://app.agentops.ai?ref=gh">
      <img src="docs/images/external/app_screenshots/session-drilldown-graphs.png" style="width: 90%;" alt="Event Graphs"/>
    </a>
  </details>

  <details>
    <summary>Session Replays</summary>
    <a href="https://app.agentops.ai?ref=gh">
      <img src="docs/images/external/app_screenshots/session-replay.png" style="width: 90%;" alt="Session Replays"/>
    </a>
  </details>

  <details open>
    <summary>Summary Analytics</summary>
    <a href="https://app.agentops.ai?ref=gh">
     <img src="docs/images/external/app_screenshots/overview.png" style="width: 90%;" alt="Summary Analytics"/>
    </a>
    <a href="https://app.agentops.ai?ref=gh">
     <img src="docs/images/external/app_screenshots/overview-charts.png" style="width: 90%;" alt="Summary Analytics Charts"/>
    </a>
  </details>



  Add powerful observability to your agents, tools, and functions with as little code as possible: one line at a time.
  <br/>
  Refer to our [documentation](http://docs.agentops.ai)

  ```python

  from agentops import track_agent

  @track_agent(name='SomeCustomName')
  class MyAgent:
    ...
  ```

  ```python

  from agentops import record_tool

  @record_tool('SampleToolName')
  def sample_tool(...):
    ...
  ```

  ```python

  from agentops import record_action

  @agentops.record_action('sample function being record')
  def sample_function(...):
    ...
  ```

  ```python

  from agentops import record, ActionEvent

  record(ActionEvent("received_user_input"))
  ```





  Build Crew agents with observability with only 2 lines of code. Simply set an `AGENTOPS_API_KEY` in your environment, and your crews will get automatic monitoring on the AgentOps dashboard.

  ```bash
  pip install 'crewai[agentops]'
  ```

  - [AgentOps integration example](https://docs.agentops.ai/v1/integrations/crewai)
  - [Official CrewAI documentation](https://docs.crewai.com/how-to/AgentOps-Observability)


  With only two lines of code, add full observability and monitoring to Autogen agents. Set an `AGENTOPS_API_KEY` in your environment and call `agentops.init()`

  - [Autogen Observability Example](https://microsoft.github.io/autogen/docs/notebooks/agentchat_agentops)
  - [Autogen - AgentOps Documentation](https://microsoft.github.io/autogen/docs/ecosystem/agentops)



  AgentOps works seamlessly with applications built using Langchain. To use the handler, install Langchain as an optional dependency:

  <details>
    <summary>Installation</summary>

  ```shell
  pip install agentops[langchain]
  ```

  To use the handler, import and set

  ```python
  import os
  from langchain.chat_models import ChatOpenAI
  from langchain.agents import initialize_agent, AgentType
  from agentops.partners.langchain_callback_handler import LangchainCallbackHandler

  AGENTOPS_API_KEY = os.environ['AGENTOPS_API_KEY']
  handler = LangchainCallbackHandler(api_key=AGENTOPS_API_KEY, tags=['Langchain Example'])

  llm = ChatOpenAI(openai_api_key=OPENAI_API_KEY,
                   callbacks=[handler],
                   model='gpt-3.5-turbo')

  agent = initialize_agent(tools,
                           llm,
                           agent=AgentType.CHAT_ZERO_SHOT_REACT_DESCRIPTION,
                           verbose=True,
                           callbacks=[handler], # You must pass in a callback handler to record your agent
                           handle_parsing_errors=True)
  ```

  Check out the [Langchain Examples Notebook](./examples/langchain_examples.ipynb) for more details including Async handlers.

  </details>



  First class support for Cohere(>=5.4.0). This is a living integration, should you need any added functionality please message us on Discord!

  - [AgentOps integration example](https://docs.agentops.ai/v1/integrations/cohere)
  - [Official Cohere documentation](https://docs.cohere.com/reference/about)

  <details>
    <summary>Installation</summary>

  ```bash
  pip install cohere
  ```

  ```python python
  import cohere
  import agentops


  agentops.init(<INSERT YOUR API KEY HERE>)
  co = cohere.Client()

  chat = co.chat(
      message="Is it pronounced ceaux-hear or co-hehray?"
  )

  print(chat)

  agentops.end_session('Success')
  ```

  ```python python
  import cohere
  import agentops


  agentops.init(<INSERT YOUR API KEY HERE>)

  co = cohere.Client()

  stream = co.chat_stream(
      message="Write me a haiku about the synergies between Cohere and AgentOps"
  )

  for event in stream:
      if event.event_type == "text-generation":
          print(event.text, end='')

  agentops.end_session('Success')
  ```
  </details>




  Track agents built with the Anthropic Python SDK (>=0.32.0).

  - [AgentOps integration guide](https://docs.agentops.ai/v1/integrations/anthropic)
  - [Official Anthropic documentation](https://docs.anthropic.com/en/docs/welcome)

  <details>
    <summary>Installation</summary>

  ```bash
  pip install anthropic
  ```

  ```python python
  import anthropic
  import agentops


  agentops.init(<INSERT YOUR API KEY HERE>)

  client = anthropic.Anthropic(
      
      api_key=os.environ.get("ANTHROPIC_API_KEY"),
  )

  message = client.messages.create(
          max_tokens=1024,
          messages=[
              {
                  "role": "user",
                  "content": "Tell me a cool fact about AgentOps",
              }
          ],
          model="claude-3-opus-20240229",
      )
  print(message.content)

  agentops.end_session('Success')
  ```

  Streaming
  ```python python
  import anthropic
  import agentops


  agentops.init(<INSERT YOUR API KEY HERE>)

  client = anthropic.Anthropic(
      
      api_key=os.environ.get("ANTHROPIC_API_KEY"),
  )

  stream = client.messages.create(
      max_tokens=1024,
      model="claude-3-opus-20240229",
      messages=[
          {
              "role": "user",
              "content": "Tell me something cool about streaming agents",
          }
      ],
      stream=True,
  )

  response = ""
  for event in stream:
      if event.type == "content_block_delta":
          response += event.delta.text
      elif event.type == "message_stop":
          print("\n")
          print(response)
          print("\n")
  ```

  Async

  ```python python
  import asyncio
  from anthropic import AsyncAnthropic

  client = AsyncAnthropic(
      
      api_key=os.environ.get("ANTHROPIC_API_KEY"),
  )


  async def main() -> None:
      message = await client.messages.create(
          max_tokens=1024,
          messages=[
              {
                  "role": "user",
                  "content": "Tell me something interesting about async agents",
              }
          ],
          model="claude-3-opus-20240229",
      )
      print(message.content)


  await main()
  ```
  </details>



  Track agents built with the Anthropic Python SDK (>=0.32.0).

  - [AgentOps integration example](./examples/mistral//mistral_example.ipynb)
  - [Official Mistral documentation](https://docs.mistral.ai)

  <details>
    <summary>Installation</summary>

  ```bash
  pip install mistralai
  ```

  Sync

  ```python python
  from mistralai import Mistral
  import agentops


  agentops.init(<INSERT YOUR API KEY HERE>)

  client = Mistral(
      
      api_key=os.environ.get("MISTRAL_API_KEY"),
  )

  message = client.chat.complete(
          messages=[
              {
                  "role": "user",
                  "content": "Tell me a cool fact about AgentOps",
              }
          ],
          model="open-mistral-nemo",
      )
  print(message.choices[0].message.content)

  agentops.end_session('Success')
  ```

  Streaming

  ```python python
  from mistralai import Mistral
  import agentops


  agentops.init(<INSERT YOUR API KEY HERE>)

  client = Mistral(
      
      api_key=os.environ.get("MISTRAL_API_KEY"),
  )

  message = client.chat.stream(
          messages=[
              {
                  "role": "user",
                  "content": "Tell me something cool about streaming agents",
              }
          ],
          model="open-mistral-nemo",
      )

  response = ""
  for event in message:
      if event.data.choices[0].finish_reason == "stop":
          print("\n")
          print(response)
          print("\n")
      else:
          response += event.text

  agentops.end_session('Success')
  ```

  Async

  ```python python
  import asyncio
  from mistralai import Mistral

  client = Mistral(
      
      api_key=os.environ.get("MISTRAL_API_KEY"),
  )


  async def main() -> None:
      message = await client.chat.complete_async(
          messages=[
              {
                  "role": "user",
                  "content": "Tell me something interesting about async agents",
              }
          ],
          model="open-mistral-nemo",
      )
      print(message.choices[0].message.content)


  await main()
  ```

  Async Streaming

  ```python python
  import asyncio
  from mistralai import Mistral

  client = Mistral(
      
      api_key=os.environ.get("MISTRAL_API_KEY"),
  )


  async def main() -> None:
      message = await client.chat.stream_async(
          messages=[
              {
                  "role": "user",
                  "content": "Tell me something interesting about async streaming agents",
              }
          ],
          model="open-mistral-nemo",
      )

      response = ""
      async for event in message:
          if event.data.choices[0].finish_reason == "stop":
              print("\n")
              print(response)
              print("\n")
          else:
              response += event.text


  await main()
  ```
  </details>



  AgentOps provides support for LiteLLM(>=1.3.1), allowing you to call 100+ LLMs using the same Input/Output Format.

  - [AgentOps integration example](https://docs.agentops.ai/v1/integrations/litellm)
  - [Official LiteLLM documentation](https://docs.litellm.ai/docs/providers)

  <details>
    <summary>Installation</summary>

  ```bash
  pip install litellm
  ```

  ```python python






  import litellm
  ...
  response = litellm.completion(model="claude-3", messages=messages)

  response = await litellm.acompletion(model="claude-3", messages=messages)
  ```
  </details>




  AgentOps works seamlessly with applications built using LlamaIndex, a framework for building context-augmented generative AI applications with LLMs.

  <details>
    <summary>Installation</summary>

  ```shell
  pip install llama-index-instrumentation-agentops
  ```

  To use the handler, import and set

  ```python
  from llama_index.core import set_global_handler





  set_global_handler("agentops")
  ```

  Check out the [LlamaIndex docs](https://docs.llamaindex.ai/en/stable/module_guides/observability/?h=agentops#agentops) for more details.

  </details>



  <div style="justify-content: center">
    <img src="docs/images/external/app_screenshots/time_travel_banner.png" alt="Time Travel Banner">
  </div>

  <br />

  [Try it out!](https://app.agentops.ai/timetravel)



  (coming soon!)



  | Platform                                                                     | Dashboard                                  | Evals                                  |
  | ---------------------------------------------------------------------------- | ------------------------------------------ | -------------------------------------- |
  | ✅ Python SDK                                                                | ✅ Multi-session and Cross-session metrics | ✅ Custom eval metrics                 |
  | 🚧 Evaluation builder API                                                    | ✅ Custom event tag tracking               | 🔜 Agent scorecards                    |
  | ✅ [Javascript/Typescript SDK](https://github.com/AgentOps-AI/agentops-node) | ✅ Session replays                         | 🔜 Evaluation playground + leaderboard |



  | Performance testing                       | Environments                                                                        | LLM Testing                                 | Reasoning and execution testing                   |
  | ----------------------------------------- | ----------------------------------------------------------------------------------- | ------------------------------------------- | ------------------------------------------------- |
  | ✅ Event latency analysis                 | 🔜 Non-stationary environment testing                                               | 🔜 LLM non-deterministic function detection | 🚧 Infinite loops and recursive thought detection |
  | ✅ Agent workflow execution pricing       | 🔜 Multi-modal environments                                                         | 🚧 Token limit overflow flags               | 🔜 Faulty reasoning detection                     |
  | 🚧 Success validators (external)          | 🔜 Execution containers                                                             | 🔜 Context limit overflow flags             | 🔜 Generative code validators                     |
  | 🔜 Agent controllers/skill tests          | ✅ Honeypot and prompt injection detection ([PromptArmor](https://promptarmor.com)) | 🔜 API bill tracking                        | 🔜 Error breakpoint analysis                      |
  | 🔜 Information context constraint testing | 🔜 Anti-agent roadblocks (i.e. Captchas)                                            | 🔜 CI/CD integration checks                 |                                                   |
  | 🔜 Regression testing                     | 🔜 Multi-agent framework visualization                                              |                                             |                                                   |



  Without the right tools, AI agents are slow, expensive, and unreliable. Our mission is to bring your agent from prototype to production. Here's why AgentOps stands out:

  - **Comprehensive Observability**: Track your AI agents' performance, user interactions, and API usage.
  - **Real-Time Monitoring**: Get instant insights with session replays, metrics, and live monitoring tools.
  - **Cost Control**: Monitor and manage your spend on LLM and API calls.
  - **Failure Detection**: Quickly identify and respond to agent failures and multi-agent interaction issues.
  - **Tool Usage Statistics**: Understand how your agents utilize external tools with detailed analytics.
  - **Session-Wide Metrics**: Gain a holistic view of your agents' sessions with comprehensive statistics.

  AgentOps is designed to make agent observability, testing, and monitoring easy.




  Check out our growth in the community:

  <img src="https://api.star-history.com/svg?repos=AgentOps-AI/agentops&type=Date" style="max-width: 500px" width="50%" alt="Logo">




  | Repository | Stars  |
  | :--------  | -----: |
  |<img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/2707039?s=40&v=4" width="20" height="20" alt="">  &nbsp; [geekan](https://github.com/geekan) / [MetaGPT](https://github.com/geekan/MetaGPT) | 42787 |
  |<img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/130722866?s=40&v=4" width="20" height="20" alt="">  &nbsp; [run-llama](https://github.com/run-llama) / [llama_index](https://github.com/run-llama/llama_index) | 34446 |
  |<img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/170677839?s=40&v=4" width="20" height="20" alt="">  &nbsp; [crewAIInc](https://github.com/crewAIInc) / [crewAI](https://github.com/crewAIInc/crewAI) | 18287 |
  |<img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/134388954?s=40&v=4" width="20" height="20" alt="">  &nbsp; [camel-ai](https://github.com/camel-ai) / [camel](https://github.com/camel-ai/camel) | 5166 |
  |<img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/152537519?s=40&v=4" width="20" height="20" alt="">  &nbsp; [superagent-ai](https://github.com/superagent-ai) / [superagent](https://github.com/superagent-ai/superagent) | 5050 |
  |<img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/30197649?s=40&v=4" width="20" height="20" alt="">  &nbsp; [iyaja](https://github.com/iyaja) / [llama-fs](https://github.com/iyaja/llama-fs) | 4713 |
  |<img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/162546372?s=40&v=4" width="20" height="20" alt="">  &nbsp; [BasedHardware](https://github.com/BasedHardware) / [Omi](https://github.com/BasedHardware/Omi) | 2723 |
  |<img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/454862?s=40&v=4" width="20" height="20" alt="">  &nbsp; [MervinPraison](https://github.com/MervinPraison) / [PraisonAI](https://github.com/MervinPraison/PraisonAI) | 2007 |
  |<img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/140554352?s=40&v=4" width="20" height="20" alt="">  &nbsp; [AgentOps-AI](https://github.com/AgentOps-AI) / [Jaiqu](https://github.com/AgentOps-AI/Jaiqu) | 272 |
  |<img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/3074263?s=40&v=4" width="20" height="20" alt="">  &nbsp; [strnad](https://github.com/strnad) / [CrewAI-Studio](https://github.com/strnad/CrewAI-Studio) | 134 |
  |<img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/18406448?s=40&v=4" width="20" height="20" alt="">  &nbsp; [alejandro-ao](https://github.com/alejandro-ao) / [exa-crewai](https://github.com/alejandro-ao/exa-crewai) | 55 |
  |<img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/64493665?s=40&v=4" width="20" height="20" alt="">  &nbsp; [tonykipkemboi](https://github.com/tonykipkemboi) / [youtube_yapper_trapper](https://github.com/tonykipkemboi/youtube_yapper_trapper) | 47 |
  |<img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/17598928?s=40&v=4" width="20" height="20" alt="">  &nbsp; [sethcoast](https://github.com/sethcoast) / [cover-letter-builder](https://github.com/sethcoast/cover-letter-builder) | 27 |
  |<img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/109994880?s=40&v=4" width="20" height="20" alt="">  &nbsp; [bhancockio](https://github.com/bhancockio) / [chatgpt4o-analysis](https://github.com/bhancockio/chatgpt4o-analysis) | 19 |
  |<img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/14105911?s=40&v=4" width="20" height="20" alt="">  &nbsp; [breakstring](https://github.com/breakstring) / [Agentic_Story_Book_Workflow](https://github.com/breakstring/Agentic_Story_Book_Workflow) | 14 |
  |<img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/124134656?s=40&v=4" width="20" height="20" alt="">  &nbsp; [MULTI-ON](https://github.com/MULTI-ON) / [multion-python](https://github.com/MULTI-ON/multion-python) | 13 |


  _Generated using [github-dependents-info](https://github.com/nvuillam/github-dependents-info), by [Nicolas Vuillamy](https://github.com/nvuillam)_


pkgId: eaff0a2cf466213f5ef8fc6846bca8fdb46e8ef696bee0cd3dffc27698b981bf
name: python-agentops
arch: src
version: 0.3.18
epoch: 0
release: 1
summary: Observability and DevTool Platform for AI Agents
url: https://github.com/AgentOps-AI/agentops
rpm_license: None
rpm_group: Unspecified
rpm_buildhost: localhost
location_href: Packages/python-agentops-0.3.18-1.src.rpm
checksum_type: sha256
description:
  <div align="center">
    <a href="https://agentops.ai?ref=gh">
      <img src="docs/images/external/logo/github-banner.png" alt="Logo">
    </a>
  </div>

  <div align="center">
    <em>Observability and DevTool platform for AI Agents</em>
  </div>

  <br />

  <div align="center">
    <a href="https://pepy.tech/project/agentops">
      <img src="https://static.pepy.tech/badge/agentops/month" alt="Downloads">
    </a>
    <a href="https://github.com/agentops-ai/agentops/issues">
    <img src="https://img.shields.io/github/commit-activity/m/agentops-ai/agentops" alt="git commit activity">
    </a>
    <img src="https://img.shields.io/pypi/v/agentops?&color=3670A0" alt="PyPI - Version">
    <a href="https://opensource.org/licenses/MIT">
      <img src="https://img.shields.io/badge/License-MIT-yellow.svg?&color=3670A0" alt="License: MIT">
    </a>
  </div>

  <p align="center">
    <a href="https://twitter.com/agentopsai/">
      <img src="https://img.shields.io/twitter/follow/agentopsai?style=social" alt="Twitter" style="height: 20px;">
    </a>
    <a href="https://discord.gg/FagdcwwXRR">
      <img src="https://img.shields.io/badge/discord-7289da.svg?style=flat-square&logo=discord" alt="Discord" style="height: 20px;">
    </a>
    <a href="https://app.agentops.ai/?ref=gh">
      <img src="https://img.shields.io/badge/Dashboard-blue.svg?style=flat-square" alt="Dashboard" style="height: 20px;">
    </a>
    <a href="https://docs.agentops.ai/introduction">
      <img src="https://img.shields.io/badge/Documentation-orange.svg?style=flat-square" alt="Documentation" style="height: 20px;">
    </a>
    <a href="https://entelligence.ai/AgentOps-AI&agentops">
      <img src="https://img.shields.io/badge/Chat%20with%20Docs-green.svg?style=flat-square" alt="Chat with Docs" style="height: 20px;">
    </a>
  </p>



  <div style="justify-content: center">
    <img src="docs/images/external/app_screenshots/dashboard-banner.png" alt="Dashboard Banner">
  </div>

  <br/>


  AgentOps helps developers build, evaluate, and monitor AI agents. From prototype to production.

  |                                       |                                                               |
  | ------------------------------------- | ------------------------------------------------------------- |
  | 📊 **Replay Analytics and Debugging** | Step-by-step agent execution graphs                           |
  | 💸 **LLM Cost Management**            | Track spend with LLM foundation model providers               |
  | 🧪 **Agent Benchmarking**             | Test your agents against 1,000+ evals                         |
  | 🔐 **Compliance and Security**        | Detect common prompt injection and data exfiltration exploits |
  | 🤝 **Framework Integrations**         | Native Integrations with CrewAI, AutoGen, & LangChain         |



  ```bash
  pip install agentops
  ```




  Initialize the AgentOps client and automatically get analytics on all your LLM calls.

  [Get an API key](https://app.agentops.ai/settings/projects)

  ```python
  import agentops


  agentops.init( < INSERT YOUR API KEY HERE >)

  ...


  agentops.end_session('Success')
  ```

  All your sessions can be viewed on the [AgentOps dashboard](https://app.agentops.ai?ref=gh)
  <br/>

  <details>
    <summary>Agent Debugging</summary>
    <a href="https://app.agentops.ai?ref=gh">
      <img src="docs/images/external/app_screenshots/session-drilldown-metadata.png" style="width: 90%;" alt="Agent Metadata"/>
    </a>
    <a href="https://app.agentops.ai?ref=gh">
      <img src="docs/images/external/app_screenshots/chat-viewer.png" style="width: 90%;" alt="Chat Viewer"/>
    </a>
    <a href="https://app.agentops.ai?ref=gh">
      <img src="docs/images/external/app_screenshots/session-drilldown-graphs.png" style="width: 90%;" alt="Event Graphs"/>
    </a>
  </details>

  <details>
    <summary>Session Replays</summary>
    <a href="https://app.agentops.ai?ref=gh">
      <img src="docs/images/external/app_screenshots/session-replay.png" style="width: 90%;" alt="Session Replays"/>
    </a>
  </details>

  <details open>
    <summary>Summary Analytics</summary>
    <a href="https://app.agentops.ai?ref=gh">
     <img src="docs/images/external/app_screenshots/overview.png" style="width: 90%;" alt="Summary Analytics"/>
    </a>
    <a href="https://app.agentops.ai?ref=gh">
     <img src="docs/images/external/app_screenshots/overview-charts.png" style="width: 90%;" alt="Summary Analytics Charts"/>
    </a>
  </details>



  Add powerful observability to your agents, tools, and functions with as little code as possible: one line at a time.
  <br/>
  Refer to our [documentation](http://docs.agentops.ai)

  ```python

  from agentops import track_agent

  @track_agent(name='SomeCustomName')
  class MyAgent:
    ...
  ```

  ```python

  from agentops import record_tool

  @record_tool('SampleToolName')
  def sample_tool(...):
    ...
  ```

  ```python

  from agentops import record_action

  @agentops.record_action('sample function being record')
  def sample_function(...):
    ...
  ```

  ```python

  from agentops import record, ActionEvent

  record(ActionEvent("received_user_input"))
  ```





  Build Crew agents with observability with only 2 lines of code. Simply set an `AGENTOPS_API_KEY` in your environment, and your crews will get automatic monitoring on the AgentOps dashboard.

  ```bash
  pip install 'crewai[agentops]'
  ```

  - [AgentOps integration example](https://docs.agentops.ai/v1/integrations/crewai)
  - [Official CrewAI documentation](https://docs.crewai.com/how-to/AgentOps-Observability)


  With only two lines of code, add full observability and monitoring to Autogen agents. Set an `AGENTOPS_API_KEY` in your environment and call `agentops.init()`

  - [Autogen Observability Example](https://microsoft.github.io/autogen/docs/notebooks/agentchat_agentops)
  - [Autogen - AgentOps Documentation](https://microsoft.github.io/autogen/docs/ecosystem/agentops)



  AgentOps works seamlessly with applications built using Langchain. To use the handler, install Langchain as an optional dependency:

  <details>
    <summary>Installation</summary>

  ```shell
  pip install agentops[langchain]
  ```

  To use the handler, import and set

  ```python
  import os
  from langchain.chat_models import ChatOpenAI
  from langchain.agents import initialize_agent, AgentType
  from agentops.partners.langchain_callback_handler import LangchainCallbackHandler

  AGENTOPS_API_KEY = os.environ['AGENTOPS_API_KEY']
  handler = LangchainCallbackHandler(api_key=AGENTOPS_API_KEY, tags=['Langchain Example'])

  llm = ChatOpenAI(openai_api_key=OPENAI_API_KEY,
                   callbacks=[handler],
                   model='gpt-3.5-turbo')

  agent = initialize_agent(tools,
                           llm,
                           agent=AgentType.CHAT_ZERO_SHOT_REACT_DESCRIPTION,
                           verbose=True,
                           callbacks=[handler], # You must pass in a callback handler to record your agent
                           handle_parsing_errors=True)
  ```

  Check out the [Langchain Examples Notebook](./examples/langchain_examples.ipynb) for more details including Async handlers.

  </details>



  First class support for Cohere(>=5.4.0). This is a living integration, should you need any added functionality please message us on Discord!

  - [AgentOps integration example](https://docs.agentops.ai/v1/integrations/cohere)
  - [Official Cohere documentation](https://docs.cohere.com/reference/about)

  <details>
    <summary>Installation</summary>

  ```bash
  pip install cohere
  ```

  ```python python
  import cohere
  import agentops


  agentops.init(<INSERT YOUR API KEY HERE>)
  co = cohere.Client()

  chat = co.chat(
      message="Is it pronounced ceaux-hear or co-hehray?"
  )

  print(chat)

  agentops.end_session('Success')
  ```

  ```python python
  import cohere
  import agentops


  agentops.init(<INSERT YOUR API KEY HERE>)

  co = cohere.Client()

  stream = co.chat_stream(
      message="Write me a haiku about the synergies between Cohere and AgentOps"
  )

  for event in stream:
      if event.event_type == "text-generation":
          print(event.text, end='')

  agentops.end_session('Success')
  ```
  </details>




  Track agents built with the Anthropic Python SDK (>=0.32.0).

  - [AgentOps integration guide](https://docs.agentops.ai/v1/integrations/anthropic)
  - [Official Anthropic documentation](https://docs.anthropic.com/en/docs/welcome)

  <details>
    <summary>Installation</summary>

  ```bash
  pip install anthropic
  ```

  ```python python
  import anthropic
  import agentops


  agentops.init(<INSERT YOUR API KEY HERE>)

  client = anthropic.Anthropic(
      
      api_key=os.environ.get("ANTHROPIC_API_KEY"),
  )

  message = client.messages.create(
          max_tokens=1024,
          messages=[
              {
                  "role": "user",
                  "content": "Tell me a cool fact about AgentOps",
              }
          ],
          model="claude-3-opus-20240229",
      )
  print(message.content)

  agentops.end_session('Success')
  ```

  Streaming
  ```python python
  import anthropic
  import agentops


  agentops.init(<INSERT YOUR API KEY HERE>)

  client = anthropic.Anthropic(
      
      api_key=os.environ.get("ANTHROPIC_API_KEY"),
  )

  stream = client.messages.create(
      max_tokens=1024,
      model="claude-3-opus-20240229",
      messages=[
          {
              "role": "user",
              "content": "Tell me something cool about streaming agents",
          }
      ],
      stream=True,
  )

  response = ""
  for event in stream:
      if event.type == "content_block_delta":
          response += event.delta.text
      elif event.type == "message_stop":
          print("\n")
          print(response)
          print("\n")
  ```

  Async

  ```python python
  import asyncio
  from anthropic import AsyncAnthropic

  client = AsyncAnthropic(
      
      api_key=os.environ.get("ANTHROPIC_API_KEY"),
  )


  async def main() -> None:
      message = await client.messages.create(
          max_tokens=1024,
          messages=[
              {
                  "role": "user",
                  "content": "Tell me something interesting about async agents",
              }
          ],
          model="claude-3-opus-20240229",
      )
      print(message.content)


  await main()
  ```
  </details>



  Track agents built with the Anthropic Python SDK (>=0.32.0).

  - [AgentOps integration example](./examples/mistral//mistral_example.ipynb)
  - [Official Mistral documentation](https://docs.mistral.ai)

  <details>
    <summary>Installation</summary>

  ```bash
  pip install mistralai
  ```

  Sync

  ```python python
  from mistralai import Mistral
  import agentops


  agentops.init(<INSERT YOUR API KEY HERE>)

  client = Mistral(
      
      api_key=os.environ.get("MISTRAL_API_KEY"),
  )

  message = client.chat.complete(
          messages=[
              {
                  "role": "user",
                  "content": "Tell me a cool fact about AgentOps",
              }
          ],
          model="open-mistral-nemo",
      )
  print(message.choices[0].message.content)

  agentops.end_session('Success')
  ```

  Streaming

  ```python python
  from mistralai import Mistral
  import agentops


  agentops.init(<INSERT YOUR API KEY HERE>)

  client = Mistral(
      
      api_key=os.environ.get("MISTRAL_API_KEY"),
  )

  message = client.chat.stream(
          messages=[
              {
                  "role": "user",
                  "content": "Tell me something cool about streaming agents",
              }
          ],
          model="open-mistral-nemo",
      )

  response = ""
  for event in message:
      if event.data.choices[0].finish_reason == "stop":
          print("\n")
          print(response)
          print("\n")
      else:
          response += event.text

  agentops.end_session('Success')
  ```

  Async

  ```python python
  import asyncio
  from mistralai import Mistral

  client = Mistral(
      
      api_key=os.environ.get("MISTRAL_API_KEY"),
  )


  async def main() -> None:
      message = await client.chat.complete_async(
          messages=[
              {
                  "role": "user",
                  "content": "Tell me something interesting about async agents",
              }
          ],
          model="open-mistral-nemo",
      )
      print(message.choices[0].message.content)


  await main()
  ```

  Async Streaming

  ```python python
  import asyncio
  from mistralai import Mistral

  client = Mistral(
      
      api_key=os.environ.get("MISTRAL_API_KEY"),
  )


  async def main() -> None:
      message = await client.chat.stream_async(
          messages=[
              {
                  "role": "user",
                  "content": "Tell me something interesting about async streaming agents",
              }
          ],
          model="open-mistral-nemo",
      )

      response = ""
      async for event in message:
          if event.data.choices[0].finish_reason == "stop":
              print("\n")
              print(response)
              print("\n")
          else:
              response += event.text


  await main()
  ```
  </details>



  AgentOps provides support for LiteLLM(>=1.3.1), allowing you to call 100+ LLMs using the same Input/Output Format.

  - [AgentOps integration example](https://docs.agentops.ai/v1/integrations/litellm)
  - [Official LiteLLM documentation](https://docs.litellm.ai/docs/providers)

  <details>
    <summary>Installation</summary>

  ```bash
  pip install litellm
  ```

  ```python python






  import litellm
  ...
  response = litellm.completion(model="claude-3", messages=messages)

  response = await litellm.acompletion(model="claude-3", messages=messages)
  ```
  </details>




  AgentOps works seamlessly with applications built using LlamaIndex, a framework for building context-augmented generative AI applications with LLMs.

  <details>
    <summary>Installation</summary>

  ```shell
  pip install llama-index-instrumentation-agentops
  ```

  To use the handler, import and set

  ```python
  from llama_index.core import set_global_handler





  set_global_handler("agentops")
  ```

  Check out the [LlamaIndex docs](https://docs.llamaindex.ai/en/stable/module_guides/observability/?h=agentops#agentops) for more details.

  </details>



  <div style="justify-content: center">
    <img src="docs/images/external/app_screenshots/time_travel_banner.png" alt="Time Travel Banner">
  </div>

  <br />

  [Try it out!](https://app.agentops.ai/timetravel)



  (coming soon!)



  | Platform                                                                     | Dashboard                                  | Evals                                  |
  | ---------------------------------------------------------------------------- | ------------------------------------------ | -------------------------------------- |
  | ✅ Python SDK                                                                | ✅ Multi-session and Cross-session metrics | ✅ Custom eval metrics                 |
  | 🚧 Evaluation builder API                                                    | ✅ Custom event tag tracking               | 🔜 Agent scorecards                    |
  | ✅ [Javascript/Typescript SDK](https://github.com/AgentOps-AI/agentops-node) | ✅ Session replays                         | 🔜 Evaluation playground + leaderboard |



  | Performance testing                       | Environments                                                                        | LLM Testing                                 | Reasoning and execution testing                   |
  | ----------------------------------------- | ----------------------------------------------------------------------------------- | ------------------------------------------- | ------------------------------------------------- |
  | ✅ Event latency analysis                 | 🔜 Non-stationary environment testing                                               | 🔜 LLM non-deterministic function detection | 🚧 Infinite loops and recursive thought detection |
  | ✅ Agent workflow execution pricing       | 🔜 Multi-modal environments                                                         | 🚧 Token limit overflow flags               | 🔜 Faulty reasoning detection                     |
  | 🚧 Success validators (external)          | 🔜 Execution containers                                                             | 🔜 Context limit overflow flags             | 🔜 Generative code validators                     |
  | 🔜 Agent controllers/skill tests          | ✅ Honeypot and prompt injection detection ([PromptArmor](https://promptarmor.com)) | 🔜 API bill tracking                        | 🔜 Error breakpoint analysis                      |
  | 🔜 Information context constraint testing | 🔜 Anti-agent roadblocks (i.e. Captchas)                                            | 🔜 CI/CD integration checks                 |                                                   |
  | 🔜 Regression testing                     | 🔜 Multi-agent framework visualization                                              |                                             |                                                   |



  Without the right tools, AI agents are slow, expensive, and unreliable. Our mission is to bring your agent from prototype to production. Here's why AgentOps stands out:

  - **Comprehensive Observability**: Track your AI agents' performance, user interactions, and API usage.
  - **Real-Time Monitoring**: Get instant insights with session replays, metrics, and live monitoring tools.
  - **Cost Control**: Monitor and manage your spend on LLM and API calls.
  - **Failure Detection**: Quickly identify and respond to agent failures and multi-agent interaction issues.
  - **Tool Usage Statistics**: Understand how your agents utilize external tools with detailed analytics.
  - **Session-Wide Metrics**: Gain a holistic view of your agents' sessions with comprehensive statistics.

  AgentOps is designed to make agent observability, testing, and monitoring easy.




  Check out our growth in the community:

  <img src="https://api.star-history.com/svg?repos=AgentOps-AI/agentops&type=Date" style="max-width: 500px" width="50%" alt="Logo">




  | Repository | Stars  |
  | :--------  | -----: |
  |<img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/2707039?s=40&v=4" width="20" height="20" alt="">  &nbsp; [geekan](https://github.com/geekan) / [MetaGPT](https://github.com/geekan/MetaGPT) | 42787 |
  |<img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/130722866?s=40&v=4" width="20" height="20" alt="">  &nbsp; [run-llama](https://github.com/run-llama) / [llama_index](https://github.com/run-llama/llama_index) | 34446 |
  |<img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/170677839?s=40&v=4" width="20" height="20" alt="">  &nbsp; [crewAIInc](https://github.com/crewAIInc) / [crewAI](https://github.com/crewAIInc/crewAI) | 18287 |
  |<img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/134388954?s=40&v=4" width="20" height="20" alt="">  &nbsp; [camel-ai](https://github.com/camel-ai) / [camel](https://github.com/camel-ai/camel) | 5166 |
  |<img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/152537519?s=40&v=4" width="20" height="20" alt="">  &nbsp; [superagent-ai](https://github.com/superagent-ai) / [superagent](https://github.com/superagent-ai/superagent) | 5050 |
  |<img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/30197649?s=40&v=4" width="20" height="20" alt="">  &nbsp; [iyaja](https://github.com/iyaja) / [llama-fs](https://github.com/iyaja/llama-fs) | 4713 |
  |<img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/162546372?s=40&v=4" width="20" height="20" alt="">  &nbsp; [BasedHardware](https://github.com/BasedHardware) / [Omi](https://github.com/BasedHardware/Omi) | 2723 |
  |<img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/454862?s=40&v=4" width="20" height="20" alt="">  &nbsp; [MervinPraison](https://github.com/MervinPraison) / [PraisonAI](https://github.com/MervinPraison/PraisonAI) | 2007 |
  |<img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/140554352?s=40&v=4" width="20" height="20" alt="">  &nbsp; [AgentOps-AI](https://github.com/AgentOps-AI) / [Jaiqu](https://github.com/AgentOps-AI/Jaiqu) | 272 |
  |<img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/3074263?s=40&v=4" width="20" height="20" alt="">  &nbsp; [strnad](https://github.com/strnad) / [CrewAI-Studio](https://github.com/strnad/CrewAI-Studio) | 134 |
  |<img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/18406448?s=40&v=4" width="20" height="20" alt="">  &nbsp; [alejandro-ao](https://github.com/alejandro-ao) / [exa-crewai](https://github.com/alejandro-ao/exa-crewai) | 55 |
  |<img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/64493665?s=40&v=4" width="20" height="20" alt="">  &nbsp; [tonykipkemboi](https://github.com/tonykipkemboi) / [youtube_yapper_trapper](https://github.com/tonykipkemboi/youtube_yapper_trapper) | 47 |
  |<img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/17598928?s=40&v=4" width="20" height="20" alt="">  &nbsp; [sethcoast](https://github.com/sethcoast) / [cover-letter-builder](https://github.com/sethcoast/cover-letter-builder) | 27 |
  |<img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/109994880?s=40&v=4" width="20" height="20" alt="">  &nbsp; [bhancockio](https://github.com/bhancockio) / [chatgpt4o-analysis](https://github.com/bhancockio/chatgpt4o-analysis) | 19 |
  |<img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/14105911?s=40&v=4" width="20" height="20" alt="">  &nbsp; [breakstring](https://github.com/breakstring) / [Agentic_Story_Book_Workflow](https://github.com/breakstring/Agentic_Story_Book_Workflow) | 14 |
  |<img class="avatar mr-2" src="https://avatars.githubusercontent.com/u/124134656?s=40&v=4" width="20" height="20" alt="">  &nbsp; [MULTI-ON](https://github.com/MULTI-ON) / [multion-python](https://github.com/MULTI-ON/multion-python) | 13 |


  _Generated using [github-dependents-info](https://github.com/nvuillam/github-dependents-info), by [Nicolas Vuillamy](https://github.com/nvuillam)_


pkgId: 38b31a198cbdd385789f83ec6e5664749e9599ba4571c5cad8a1a66bf6c307ed
name: python-agentpod
arch: src
version: 0.1.6
epoch: 0
release: 1
summary: A simple framework for agentic systems
url: https://agentpod.ai
rpm_license: MIT
rpm_group: Unspecified
rpm_buildhost: localhost
location_href: Packages/python-agentpod-0.1.6-1.src.rpm
checksum_type: sha256
description:
  AgentPod is a simple framework to build agents on top of LLMs. It currently supports OpenAI and will support Ollama at somepoint in the near future. We do not plan to extend support beyond these at this point. Since it is just a wrapper over a bunch of http calls, we built it on top of asyncio. And, at this point, we do not plan to create a sync client.

  Agentpod supports both structured & unstructured output (even with Vision API). It provides a reliable way to calculate the cost of API calls, with an easy-to-use API to get this cost at a detailed level. You can also access the raw responses from the LLM.

  We currently does internet search with Bing. We did originally support brave search but we evolved to understand brave search is not good enough to give best search result and Google search over API sucks. We also provide simple utilities to read the textual content of the webpages for LLMs to process. We'll be supporting code interpreter so without using OpenAI assistant api, you can still use LLM to generate code and execute it.

  Our goal is to create a reliable, lightweight, and minimalistic framework to interact with LLMs. We are not focusing on building any integrations that isn't used at production by our users. There are many similar client packages available, but Agentpod was created from our frustration with existing frameworks, which are often non-flexible, do too much behind the scenes, change APIs often, and have complex codebases. We are an AI agency, and we use Agentpod in production for all our agents.



  ```
  pip install agentpod
  ```



  Examples can be found at our tests directory [tests/](tests/).



  This project includes code from [Instructor](https://github.com/jxnl/instructor), which is licensed under the MIT License.


pkgId: d82adf4b9405c31c03b814ad53a6f3499d8368786ebba9cd8296fc5e6b8719e7
name: python-agentpress
arch: src
version: 0.1.11
epoch: 0
release: 1
summary: Building blocks for AI Agents
url: https://github.com/kortix-ai/agentpress
rpm_license: MIT
rpm_group: Unspecified
rpm_buildhost: localhost
location_href: Packages/python-agentpress-0.1.11-1.src.rpm
checksum_type: sha256
description:
  AgentPress is a collection of _simple, but powerful_ utilities that serve as building blocks for creating AI agents. *Plug, play, and customize.*

  ![AgentPress Flow](images/cover.png)

  See [How It Works](#how-it-works) for an explanation of this flow.


  - **Threads**: Manage Messages[] as threads.
  - **Tools**: Register code as callable tools with definitions in both OpenAPI and XML
  - **Response Processing**: Support for native-LLM OpenAPI and XML-based tool calling
  - **State Management**: Thread-safe JSON key-value state management
  - **LLM**: +100 LLMs using the OpenAI I/O Format powered by LiteLLM



  1. Install the package:
  ```bash
  pip install agentpress
  ```

  2. Initialize AgentPress in your project:
  ```bash
  agentpress init
  ```
  Creates a `agentpress` directory with all the core utilities.
  Check out [File Overview](#file-overview) for explanations of the generated files.

  3. If you selected the example agent during initialization:
     - Creates an `agent.py` file with a web development agent example
     - Creates a `tools` directory with example tools:
       - `files_tool.py`: File operations (create/update files, read directory and load into state)
       - `terminal_tool.py`: Terminal command execution
     - Creates a `workspace` directory for the agent to work in






  1. Set up your environment variables in a `.env` file:
  ```bash
  OPENAI_API_KEY=your_key_here
  ANTHROPIC_API_KEY=your_key_here
  GROQ_API_KEY=your_key_here
  ```

  2. Create a calculator tool with OpenAPI schema:
  ```python
  from agentpress.tool import Tool, ToolResult, openapi_schema

  class CalculatorTool(Tool):
      @openapi_schema({
          "type": "function",
          "function": {
              "name": "add",
              "description": "Add two numbers",
              "parameters": {
                  "type": "object",
                  "properties": {
                      "a": {"type": "number"},
                      "b": {"type": "number"}
                  },
                  "required": ["a", "b"]
              }
          }
      })
      async def add(self, a: float, b: float) -> ToolResult:
          try:
              result = a + b
              return self.success_response(f"The sum is {result}")
          except Exception as e:
              return self.fail_response(f"Failed to add numbers: {str(e)}")
  ```

  3. Or create a tool with XML schema:
  ```python
  from agentpress.tool import Tool, ToolResult, xml_schema

  class FilesTool(Tool):
      @xml_schema(
          tag_name="create-file",
          mappings=[
              {"param_name": "file_path", "node_type": "attribute", "path": "."},
              {"param_name": "file_contents", "node_type": "content", "path": "."}
          ],
          example='''
          <create-file file_path="path/to/file">
          File contents go here
          </create-file>
          '''
      )
      async def create_file(self, file_path: str, file_contents: str) -> ToolResult:
          
          pass
  ```

  4. Use the Thread Manager with tool execution:
  ```python
  import asyncio
  from agentpress.thread_manager import ThreadManager
  from calculator_tool import CalculatorTool

  async def main():
      
      manager = ThreadManager()
      manager.add_tool(CalculatorTool)

      
      thread_id = await manager.create_thread()

      
      await manager.add_message(thread_id, {
          "role": "user",
          "content": "What's 2 + 2?"
      })

      
      response = await manager.run_thread(
          thread_id=thread_id,
          system_message={
              "role": "system",
              "content": "You are a helpful assistant with calculation abilities."
          },
          model_name="anthropic/claude-3-5-sonnet-latest",
          execute_tools=True,
          native_tool_calling=True, # Contrary to xml_tool_calling = True
          parallel_tool_execution=True # Will execute tools in parallel, contrary to sequential (one after another)
      )

  asyncio.run(main())
  ```

  5. View conversation threads in a web UI:
  ```bash
  streamlit run agentpress/thread_viewer_ui.py
  ```



  Each AI agent iteration follows a clear, modular flow:

  1. **Message & LLM Handling**
     - Messages are managed in threads via `ThreadManager`
     - LLM API calls are made through a unified interface (`llm.py`)
     - Supports streaming responses for real-time interaction

  2. **Response Processing**
     - LLM returns both content and tool calls
     - Content is streamed in real-time
     - Tool calls are parsed using either:
       - Standard OpenAPI function calling
       - XML-based tool definitions
       - Custom parsers (extend `ToolParserBase`)

  3. **Tool Execution**
     - Tools are executed either:
       - In real-time during streaming (`execute_tools_on_stream`)
       - After complete response
       - In parallel or sequential order
     - Supports both standard and XML tool formats
     - Extensible through `ToolExecutorBase`

  4. **Results Management**
     - Results from both content and tool executions are handled
     - Supports different result formats (standard/XML)
     - Customizable through `ResultsAdderBase`

  This modular architecture allows you to:
  - Use standard OpenAPI function calling
  - Switch to XML-based tool definitions
  - Create custom processors by extending base classes
  - Mix and match different approaches






  LLM API interface using LiteLLM. Supports 100+ LLMs with OpenAI-compatible format. Includes streaming, retry logic, and error handling.


  Manages conversation threads with support for:
  - Message history management
  - Tool registration and execution
  - Streaming responses
  - Both OpenAPI and XML tool calling patterns


  Base infrastructure for tools with:
  - OpenAPI schema decorator for standard function calling
  - XML schema decorator for XML-based tool calls
  - Standardized ToolResult responses


  Central registry for tool management:
  - Registers both OpenAPI and XML tools
  - Maintains tool schemas and implementations
  - Provides tool lookup and validation


  Thread-safe state persistence:
  - JSON-based key-value storage
  - Atomic operations with locking
  - Automatic file handling




  Handles LLM response processing with support for:
  - Streaming and complete responses
  - Tool call extraction and execution
  - Result formatting and message management


  - `standard_tool_parser.py`: Parses OpenAPI function calls
  - `standard_tool_executor.py`: Executes standard tool calls
  - `standard_results_adder.py`: Manages standard results


  - `xml_tool_parser.py`: Parses XML-formatted tool calls
  - `xml_tool_executor.py`: Executes XML tool calls
  - `xml_results_adder.py`: Manages XML results


  - **Plug & Play**: Start with our defaults, then customize to your needs.
  - **Agnostic**: Built on LiteLLM, supporting any LLM provider. Minimal opinions, maximum flexibility.
  - **Simplicity**: Clean, readable code that's easy to understand and modify.
  - **No Lock-in**: Take full ownership of the code. Copy what you need directly into your codebase.



  We welcome contributions! Feel free to:
  - Submit issues for bugs or suggestions
  - Fork the repository and send pull requests
  - Share how you've used AgentPress in your projects



  1. Clone:
  ```bash
  git clone https://github.com/kortix-ai/agentpress
  cd agentpress
  ```

  2. Install dependencies:
  ```bash
  pip install poetry
  poetry install
  ```

  3. For quick testing:
  ```bash
  pip install -e .
  ```



  [MIT License](LICENSE)

  Built with ❤️ by [Kortix AI Corp](https://kortix.ai)


pkgId: f9b17add742794753052959f865d631e369f9777d82c56d310d8cbe910ce0c20
name: python-agentpress
arch: src
version: 0.1.8
epoch: 0
release: 1
summary: Building blocks for AI Agents
url: https://github.com/kortix-ai/agentpress
rpm_license: MIT
rpm_group: Unspecified
rpm_buildhost: localhost
location_href: Packages/python-agentpress-0.1.8-1.src.rpm
checksum_type: sha256
description:
  AgentPress is a collection of _simple, but powerful_ utilities that serve as building blocks for creating AI agents. *Plug, play, and customize.*

  ![AgentPress Flow](images/cover.png)

  See [How It Works](#how-it-works) for an explanation of this flow.


  - **Threads**: Manage Messages[] as threads.
  - **Tools**: Register code as callable tools with definitions in both OpenAPI and XML
  - **Response Processing**: Support for native-LLM OpenAPI and XML-based tool calling
  - **State Management**: Thread-safe JSON key-value state management
  - **LLM**: +100 LLMs using the OpenAI I/O Format powered by LiteLLM



  1. Install the package:
  ```bash
  pip install agentpress
  ```

  2. Initialize AgentPress in your project:
  ```bash
  agentpress init
  ```
  Creates a `agentpress` directory with all the core utilities.
  Check out [File Overview](#file-overview) for explanations of the generated files.

  3. If you selected the example agent during initialization:
     - Creates an `agent.py` file with a web development agent example
     - Creates a `tools` directory with example tools:
       - `files_tool.py`: File operations (create/update files, read directory and load into state)
       - `terminal_tool.py`: Terminal command execution
     - Creates a `workspace` directory for the agent to work in






  1. Set up your environment variables in a `.env` file:
  ```bash
  OPENAI_API_KEY=your_key_here
  ANTHROPIC_API_KEY=your_key_here
  GROQ_API_KEY=your_key_here
  ```

  2. Create a calculator tool with OpenAPI schema:
  ```python
  from agentpress.tool import Tool, ToolResult, openapi_schema

  class CalculatorTool(Tool):
      @openapi_schema({
          "type": "function",
          "function": {
              "name": "add",
              "description": "Add two numbers",
              "parameters": {
                  "type": "object",
                  "properties": {
                      "a": {"type": "number"},
                      "b": {"type": "number"}
                  },
                  "required": ["a", "b"]
              }
          }
      })
      async def add(self, a: float, b: float) -> ToolResult:
          try:
              result = a + b
              return self.success_response(f"The sum is {result}")
          except Exception as e:
              return self.fail_response(f"Failed to add numbers: {str(e)}")
  ```

  3. Or create a tool with XML schema:
  ```python
  from agentpress.tool import Tool, ToolResult, xml_schema

  class FilesTool(Tool):
      @xml_schema(
          tag_name="create-file",
          mappings=[
              {"param_name": "file_path", "node_type": "attribute", "path": "."},
              {"param_name": "file_contents", "node_type": "content", "path": "."}
          ],
          example='''
          <create-file file_path="path/to/file">
          File contents go here
          </create-file>
          '''
      )
      async def create_file(self, file_path: str, file_contents: str) -> ToolResult:
          
          pass
  ```

  4. Use the Thread Manager with streaming and tool execution:
  ```python
  import asyncio
  from agentpress.thread_manager import ThreadManager
  from calculator_tool import CalculatorTool

  async def main():
      
      manager = ThreadManager()
      manager.add_tool(CalculatorTool)

      
      thread_id = await manager.create_thread()

      
      await manager.add_message(thread_id, {
          "role": "user",
          "content": "What's 2 + 2?"
      })

      
      response = await manager.run_thread(
          thread_id=thread_id,
          system_message={
              "role": "system",
              "content": "You are a helpful assistant with calculation abilities."
          },
          model_name="anthropic/claude-3-5-sonnet-latest",
          stream=True,
          native_tool_calling=True,
          execute_tools=True,
          execute_tools_on_stream=True
      )

      
      if isinstance(response, AsyncGenerator):
          async for chunk in response:
              if hasattr(chunk.choices[0], 'delta'):
                  delta = chunk.choices[0].delta
                  if hasattr(delta, 'content') and delta.content:
                      print(delta.content, end='', flush=True)

  asyncio.run(main())
  ```

  5. View conversation threads in a web UI:
  ```bash
  streamlit run agentpress/thread_viewer_ui.py
  ```



  Each AI agent iteration follows a clear, modular flow:

  1. **Message & LLM Handling**
     - Messages are managed in threads via `ThreadManager`
     - LLM API calls are made through a unified interface (`llm.py`)
     - Supports streaming responses for real-time interaction

  2. **Response Processing**
     - LLM returns both content and tool calls
     - Content is streamed in real-time
     - Tool calls are parsed using either:
       - Standard OpenAPI function calling
       - XML-based tool definitions
       - Custom parsers (extend `ToolParserBase`)

  3. **Tool Execution**
     - Tools are executed either:
       - In real-time during streaming (`execute_tools_on_stream`)
       - After complete response
       - In parallel or sequential order
     - Supports both standard and XML tool formats
     - Extensible through `ToolExecutorBase`

  4. **Results Management**
     - Results from both content and tool executions are handled
     - Supports different result formats (standard/XML)
     - Customizable through `ResultsAdderBase`

  This modular architecture allows you to:
  - Use standard OpenAPI function calling
  - Switch to XML-based tool definitions
  - Create custom processors by extending base classes
  - Mix and match different approaches






  LLM API interface using LiteLLM. Supports 100+ LLMs with OpenAI-compatible format. Includes streaming, retry logic, and error handling.


  Manages conversation threads with support for:
  - Message history management
  - Tool registration and execution
  - Streaming responses
  - Both OpenAPI and XML tool calling patterns


  Base infrastructure for tools with:
  - OpenAPI schema decorator for standard function calling
  - XML schema decorator for XML-based tool calls
  - Standardized ToolResult responses


  Central registry for tool management:
  - Registers both OpenAPI and XML tools
  - Maintains tool schemas and implementations
  - Provides tool lookup and validation


  Thread-safe state persistence:
  - JSON-based key-value storage
  - Atomic operations with locking
  - Automatic file handling




  Handles LLM response processing with support for:
  - Streaming and complete responses
  - Tool call extraction and execution
  - Result formatting and message management


  - `standard_tool_parser.py`: Parses OpenAPI function calls
  - `standard_tool_executor.py`: Executes standard tool calls
  - `standard_results_adder.py`: Manages standard results


  - `xml_tool_parser.py`: Parses XML-formatted tool calls
  - `xml_tool_executor.py`: Executes XML tool calls
  - `xml_results_adder.py`: Manages XML results


  - **Plug & Play**: Start with our defaults, then customize to your needs.
  - **Agnostic**: Built on LiteLLM, supporting any LLM provider. Minimal opinions, maximum flexibility.
  - **Simplicity**: Clean, readable code that's easy to understand and modify.
  - **No Lock-in**: Take full ownership of the code. Copy what you need directly into your codebase.



  We welcome contributions! Feel free to:
  - Submit issues for bugs or suggestions
  - Fork the repository and send pull requests
  - Share how you've used AgentPress in your projects



  1. Clone:
  ```bash
  git clone https://github.com/kortix-ai/agentpress
  cd agentpress
  ```

  2. Install dependencies:
  ```bash
  pip install poetry
  poetry install
  ```

  3. For quick testing:
  ```bash
  pip install -e .
  ```



  [MIT License](LICENSE)

  Built with ❤️ by [Kortix AI Corp](https://kortix.ai)


pkgId: 200cd477a78021e99ecb20a5a241770e15dfcfe32b884793cdc5574f76954871
name: python-agentpy
arch: src
version: 0.1.5
epoch: 0
release: 1
summary: Agent-based modeling in Python
url: https://agentpy.readthedocs.io/
rpm_license: BSD 3-Clause
rpm_group: Unspecified
rpm_buildhost: localhost
location_href: Packages/python-agentpy-0.1.5-1.src.rpm
checksum_type: sha256
description:
  [![PyPI](https://img.shields.io/pypi/v/agentpy)](https://pypi.org/project/agentpy/)
  [![GitHub](https://img.shields.io/github/license/joelforamitti/agentpy)](https://github.com/JoelForamitti/agentpy/blob/master/LICENSE)
  [![Build Status](https://travis-ci.com/JoelForamitti/agentpy.svg?branch=master)](https://travis-ci.com/JoelForamitti/agentpy)
  [![Documentation Status](https://readthedocs.org/projects/agentpy/badge/?version=latest)](https://agentpy.readthedocs.io/en/latest/?badge=latest)
  [![codecov](https://codecov.io/gh/JoelForamitti/agentpy/branch/master/graph/badge.svg?token=NTW99HNGB0)](https://codecov.io/gh/JoelForamitti/agentpy)
  [![DOI](https://joss.theoj.org/papers/10.21105/joss.03065/status.svg)](https://doi.org/10.21105/joss.03065)

  AgentPy is an open-source library for the development and analysis of agent-based models in Python.
  The framework integrates the tasks of model design, interactive simulations, numerical experiments,
  and data analysis within a single environment. The package is optimized for interactive computing
  with [IPython](http://ipython.org/), [IPySimulate](https://github.com/JoelForamitti/ipysimulate), and [Jupyter](https://jupyter.org/).

  Please cite this software as follows:

      Foramitti, J., (2021). AgentPy: A package for agent-based modeling in Python.
      Journal of Open Source Software, 6(62), 3065, https://doi.org/10.21105/joss.03065

  **Installation:** `pip install agentpy`

  **Documentation:** https://agentpy.readthedocs.io

  **JOSS publication:** https://doi.org/10.21105/joss.03065

  **Discussion forum:** https://github.com/JoelForamitti/agentpy/discussions

  **Tutorials and examples:** https://agentpy.readthedocs.io/en/latest/model_library.html

  **Comparison with other frameworks**: https://agentpy.readthedocs.io/en/latest/comparison.html


pkgId: 95c7952929aa6f15e5193837e8a121b1306c80ab0e029ff44e6abaaa4c347d2b
name: python-agentrun
arch: src
version: 0.2.5
epoch: 0
release: 1
summary: The easiest way to run AI or user generated python code safely in a docker container
url: https://github.com/jonathan-adly/agentrun
rpm_license: Apache-2.0
rpm_group: Unspecified
rpm_buildhost: localhost
location_href: Packages/python-agentrun-0.2.5-1.src.rpm
checksum_type: sha256
description:
  Docker setup| You set it up             | Already setup for you |
  Installation| Pip                       | Git clone             |
  Ease of use | Easy                      | Super Easy            |
  Requirements| A running docker container| Docker installed      |
  Customize   | Fully                     | Partially             |

  Now, let's see AgentRun in action with something more complicated. We will take advantage of function calling and AgentRun, to have LLMs write and execute code on the fly to solve arbitrary tasks. You can find the full code under `docs/examples/`
  First, we will install the needed packages. We are using mixtral here via groq to keep things fast and with minimal depenencies, but AgentRun works with any LLM out of the box. All what's required is for the LLM to return a code snippet.
  > FYI: OpenAI assistant tool `code_interpreter` can execute code. AgentRun is a transparent, open-source version that can work with any LLM.
  ```bash
  !pip install groq
  !pip install requests
  ```
  Next, we will setup a function that executed the code and returns an output. We are using the API here, so make sure to have it running before trying this.
  Here is the steps to run the API:
  ```bash
  git clone https://github.com/Jonathan-Adly/agentrun
  cd agentrun/agentrun-api
  cp .env.example .env.dev
  docker-compose up -d --build
  ```
  ```python
  def execute_python_code(code: str) -> str:
      response = requests.post("http://localhost:8000/v1/run/", json={"code": code})
      output = response.json()["output"]
      return output
  ```
  Next, we will setup our LLM function calling skeleton code. We need:
  1. An LLM client such Groq or OpenAI or Anthropic (alternatively, you can use litellm as wrapper)
  2. The model you will use
  3. Our code execution tool - that encourages the LLM model to send us python code to execute reliably
  ```python
  from groq import Groq
  import json
  client = Groq(api_key ="Your API Key")
  MODEL = 'mixtral-8x7b-32768'
  tools = [
      {
          "type": "function",
          "function": {
              "name": "execute_python_code",
              "description": "Sends a python code snippet to the code execution environment and returns the output. The code execution environment can automatically import any library or package by importing.",
              "parameters": {
                  "type": "object",
                  "properties": {
                      "code": {
                          "type": "string",
                          "description": "The code snippet to execute. Must be a valid python code. Must use print() to output the result.",
                      },
                  },
                  "required": ["code"],
              },
          },
      },
  ]
  ```
  Next, we will setup a function to call our LLM of choice.
  ```python
  def chat_completion_request(messages, tools=None, tool_choice=None, model=GPT_MODEL):
      try:
          response = client.chat.completions.create(
              model=model,
              messages=messages,
              tools=tools,
              tool_choice=tool_choice,
          )
          return response
      except Exception as e:
          print("Unable to generate ChatCompletion response")
          print(f"Exception: {e}")
          return e
  ```
  Finally, we will set up a function that takes the user query and returns an answer. Using AgentRun to execute code when the LLM determines code execution is necesary to answer the question
  ```python
  def get_answer(query):
      messages = []
      messages.append(
          {
              "role": "system",
              "content": """Don't make assumptions about what values to plug into functions. Ask for clarification if a user request is ambiguous.\n
              Use the execute_python_code tool to run code if a question is better solved with code. You can use any package in the code snippet by simply importing. Like `import requests` would work fine.\n
              """,
          }
      )
      messages.append({"role": "user", "content": query})
      chat_response = chat_completion_request(messages, tools=tools)
      message = chat_response.choices[0].message
      
      if message.tool_calls:
          tool_call = message.tool_calls[0]
          arg = json.loads(tool_call.function.arguments)["code"]
          print(f"Executing code: {arg}")
          answer = execute_python_code(arg)
          
          query = "Help translate the code output to a human friendly response. This was the user query: " + query + " The code output is: " + answer
          answer = get_answer(query)
      else:
          answer = message.content
      return answer
  ```
  Now let's try it!
  `get_answer("what's the average daily move of Apple stock in the last 3 days?")`
  "The average daily movement of Apple's stock in the last 3 days is approximately $2.60."
  **How did get this answer?**
  First, the LLM generated the code to call the Yahoo stock API (via yf) as such:
  ```Python

  import yfinance as yf

  apple = yf.Ticker('AAPL')
  hist = apple.history(period="3d")

  moves = hist['Close'] - hist['Open']
  average_move = moves.mean()
  print(f'{average_move:.2f}')
  ```
  That code was sent to AgentRun, which outputted:
  `'\r[*********************100%**********************]  1 of 1 completed\n2.39'`
  Lastly, the output was sent to the LLM again to make human friendly. Giving us the final answer: $2.39

  AgentRun has sane defaults, but totally customizable. You can change:
  1. dependencies_whitelist - by default any thing that can be pip installed is allowable.
  2. cached_dependencies - these are dependencies that are installed on the image on initialization, and stay there until the image is brought down. `[]` by default.
  > It will take longer to initialize the image with cached_dependencies, however subsequent runs using those dependencies would be a lot faster.
  3. cpu_quota - the default is 50000. Here is GPT-4 explaining what does that mean.
  > In Docker SDK, the cpu_quota parameter is used to limit CPU usage for a container.
  > The value of cpu_quota specifies the amount of CPU time that the container is allowed to use in microseconds per scheduling period.
  > The default scheduling period for Docker is 100 milliseconds (100,000 microseconds).
  >
  > If you set cpu_quota to 50000, this means that the container is allowed to use 50,000 microseconds of CPU time every 100 milliseconds.
  > Essentially, this limits the container to 50% CPU usage of a single CPU core during each scheduling period.
  > If your system has multiple cores, the container could still potentially use more total CPU resources by spreading the load across multiple cores.
  3. default_timeout - how long is scripts allowed to run for. Default is 20 seconds.
  4. memory_limit - how much memory can execution take. Default is 100mb
  5. memswap_limit - the default is 512mb. Again, here is GPT-4 explaing what memory_mit and memswap do.
  > In Docker SDK, the memswap_limit parameter is used to control the memory and swap usage of a container.
  > This setting specifies the maximum amount of combined memory and swap space that the container can use. The value is given in bytes.
  >
  > Here’s how it works:
  > - Memory (RAM): This is the actual physical memory that the container can use.
  > - Swap: This is a portion of the hard drive that is used when the RAM is fully utilized.
  > Using swap allows the system to handle more memory allocation than the physical memory available, but accessing swap is significantly slower than accessing RAM.
  You can change any of the defauts when you initalize AgentRun as below.
  ```Python
  from agentrun import AgentRun

  runner = AgentRun(
  container_name="my_container",

  dependencies_whitelist = ["requests"], # [] = no dependencies
  cached_dependencies = ["requests"],

  default_timeout = 3 * 60,

  memory_limit = "512mb"

  memswap_limit= "1gb"
  )
  code_from_llm = get_code_from_llm(prompt) # "print('hello, world!')"
  result = runner.execute_code_in_container(code_from_llm)
  print(result)

  ```

  AgentRun Median execution time is <200ms without dependencies and ~400ms with 1 "average" dependency like requests. Dependency installing is usually the bottleneck and depends on the size of package and if the package has many dependencies as well as caching.
  ![benchmarks](<https://pbs.twimg.com/media/GabL6e0XgAA9Two?format=png>)

  To contribute to this library, first checkout the code. Then create a new virtual environment:
  ```bash
  cd agentrun
  python -m venv venv
  source venv/bin/activate
  ```
  Now install the dependencies and test dependencies:
  ```bash
  pip install -e '.[test]'
  ```
  To run the tests:
  ```bash
  pytest
  ```
  To run the test with coverage
  ```bash
  pytest --cov=agentrun tests/
  ```


pkgId: 7c19d9196ec390ac7f0f8846e0ff07bc567cef17ea8f26ae3de0d9bbd65e1c6d
name: python-agents-client
arch: src
version: 0.1.23
epoch: 0
release: 1
summary: A client library for interacting with the Agents API
url: https://github.com/Levangie-Laboratories/agents-client
rpm_license: None
rpm_group: Unspecified
rpm_buildhost: localhost
location_href: Packages/python-agents-client-0.1.23-1.src.rpm
checksum_type: sha256
description:
  The Agents Client Library provides a simple interface for interacting with the Agents API. It handles authentication, request management, and provides convenient methods for managing chatbots and agents.




  ```bash
  pip install agents-client
  ```


  ```bash
  git clone https://github.com/Levangie-Laboratories/agents-client.git
  cd agents-client
  pip install -r requirements.txt
  ```


  The client library uses a `config.json` file for API settings. You can either use the default configuration or provide your own:

  ```python
  from agents.client import AgentClient


  client = AgentClient()


  client = AgentClient(config_path='path/to/config.json')


  client = AgentClient(base_url='https://api.example.com', api_version='v2')
  ```


  - `base_url`: API base URL
  - `version`: API version
  - `timeout`: Request timeout in seconds
  - `retry_attempts`: Number of retry attempts
  - `retry_delay`: Delay between retries in seconds

  See `config.json` for all available options.




  ```python
  from client import ChatbotClient
  from client.base_client import ApiError, AuthenticationError


  base_url = "http://localhost:8000"
  chatbot = ChatbotClient(base_url)


  api_key = "your-api-key"
  chatbot.set_api_key(api_key)

  try:
      
      config = {
          "temperature": 0.7,
          "max_tokens": 4000,
          "behavior": "A helpful assistant that provides clear and concise answers."
      }

      
      response = chatbot.create_chatbot(
          name="BasicChat",
          model="gpt-4o-mini",
          config=config
      )

      
      chatbot_id = response.get('id')
      print(f"Created chatbot with ID: {chatbot_id}\n")

      
      message = "Hello! How are you?"
      chat_response = chatbot.chat(chatbot_id, message)
      print(f"Chatbot: {chat_response.get('response', 'No response')}\n")

  except AuthenticationError as e:
      print(f"Authentication error: {str(e)}")
  except ApiError as e:
      print(f"API error: {str(e)}")
  ```


  ```python
  from agents.client import AgentClient
  import asyncio

  async def main():
      
      async with AgentClient("http://localhost:8000") as client:
          client.set_api_key("your-api-key")

          
          config = {
              "behavior": "task-focused",
              "model": "gpt-4o-mini",
              "api_mode": True  # Enable API execution mode
          }
          agent = await client.create_agent_with_tools(
              name="FileManager",
              model="gpt-4o-mini",
              tools=FileTools(),  # Your tool class instance
              config=config
          )

          
          async for event in client.process_agent_request(agent["id"], "Update debug mode in config.json"):
              if event["type"] == "function_call":
                  print(f"Executing function: {event['data']['function']}")
                  
              elif event["type"] == "execution_status":
                  print(f"Execution result: {event['data']}")
              elif event["type"] == "completion":
                  print(f"Task completed: {event['data']}")
              elif event["type"] == "error":
                  print(f"Error: {event['data']}")


  asyncio.run(main())
  ```


  ```python
  async with AgentClient("http://localhost:8000") as client:
      
      async for event in client.process_agent_request(agent_id, message):
          if event["type"] == "state_update":
              print(f"Agent state updated: {event['data']}")
          elif event["type"] == "function_call":
              
              result = await client.execute_function(event["data"])
              
              await client.submit_result(agent_id, event["data"]["sequence_id"], result)
  ```




  ```python
  from client import ChatbotClient
  from client.base_client import ApiError, AuthenticationError


  base_url = "http://localhost:8000"
  chatbot_client = ChatbotClient(base_url)


  api_key = "your-api-key"
  chatbot_client.set_api_key(api_key)

  try:
      
      config = {
          "temperature": 0.7,
          "max_tokens": 4000,
          "behavior": "A helpful assistant that provides clear and concise answers."
      }

      
      response = chatbot_client.create_chatbot(
          name="BasicChat",
          model="gpt-4o-mini",
          config=config
      )

      
      chatbot_id = response.get('id')
      print(f"Created chatbot with ID: {chatbot_id}\n")

  except AuthenticationError as e:
      print(f"Authentication error: {str(e)}")
  except ApiError as e:
      print(f"API error: {str(e)}")
  ```


  ```python
  chatbots = client.list_chatbots()
  for bot in chatbots:
      print(f"Bot: {bot['name']} (ID: {bot['id']})")
  ```


  ```python
  try:
      
      print("=== Chatbot Interaction ===\n")
      chat_response = chatbot_client.chat(
          chatbot_id,
          "What's the weather like today?"
      )
      print(f"Chatbot: {chat_response['data']['response']}\n")

      
      print("=== Chatbot History ===\n")
      history = chatbot_client.get_history(chatbot_id)
      print(f"Chat history: {history}\n")

  except ApiError as e:
      print(f"API Error: {str(e)}\n")
  ```


  ```python
  updated_config = {
      "temperature": 0.8,
      "max_tokens": 1000
  }

  updated_bot = client.update_chatbot(
      chatbot_id=123,
      name="UpdatedBot",
      model="gpt-4o-mini",
      config=updated_config
  )
  ```


  ```python
  result = client.delete_chatbot(chatbot_id=123)
  ```




  ```python
  from client import AgentClient
  from client.base_client import ApiError, AuthenticationError


  base_url = "http://localhost:8000"
  agent_client = AgentClient(base_url)


  api_key = "your-api-key"
  agent_client.set_api_key(api_key)

  try:
      
      agent_tools = {
          "general": {
              "search": {
                  "name": "search",
                  "description": "Search for information",
                  "parameters": {}
              }
          }
      }

      agent_config = {
          "model": "gpt-4o-mini",
          "temperature": 0.7,
          "max_tokens": 4000
      }

      
      agent = agent_client.create_agent(
          name="ResearchAgent",
          agent_type="research",
          behavior="A research agent that helps find and analyze information.",
          tools=agent_tools,
          config=agent_config
      )
      print(f"Created agent with ID: {agent['id']}\n")

  except AuthenticationError as e:
      print(f"Authentication error: {str(e)}")
  except ApiError as e:
      print(f"API error: {str(e)}")
  ```


  ```python
  agents = client.list_agents()
  for agent in agents:
      print(f"Agent: {agent['name']} (ID: {agent['id']})")
  ```


  ```python
  try:
      
      print("=== Agent Interaction ===\n")
      agent_response = agent_client.interact(
          agent['id'],
          "Find information about Python programming."
      )
      print(f"Agent response: {agent_response['data']['response']}\n")

      
      print("=== Agent State ===\n")
      state = agent_client.get_state(agent['id'])
      print(f"Agent state: {state}\n")

      
      print("=== Error Handling ===\n")
      try:
          
          agent_client.interact("invalid-id", "Hello!")
      except ApiError as e:
          print(f"Handled API error: {str(e)}\n")

  except AuthenticationError as e:
      print(f"Authentication error: {str(e)}")
  except ApiError as e:
      print(f"API error: {str(e)}")
  except Exception as e:
      print(f"Unexpected error: {str(e)}")
  ```

  The new system simplifies command execution by:
  ```

  Key features of the new command system:
  - Automatic command execution and result handling
  - Built-in command validation and safety checks
  - Simplified tool registration using decorators
  - Automatic result mapping in responses
  - Support for both synchronous and asynchronous operations
  - Comprehensive error handling and reporting


  The client can execute various commands locally:

  ```python

  commands = [
      {"view_file": {"file_path": "config.json"}},
      {"smart_replace": {
          "file_path": "config.json",
          "old_text": "debug: false",
          "new_text": "debug: true"
      }},
      {"create_file": {
          "file_path": "new_file.txt",
          "content": "Hello, world!"
      }}
  ]


  results = client.execute_commands(commands, context={})
  ```


  - File path validation
  - Comprehensive error handling
  - Safe text replacement
  - Automatic retries for network issues

  ```python

  try:
      results = client.execute_commands(commands, context={})
      if any(r["status"] == "error" for r in results["command_results"]):
          print("Some commands failed to execute")
          for result in results["command_results"]:
              if result["status"] == "error":
                  print(f"Error: {result['error']}")
  except Exception as e:
      print(f"Execution failed: {str(e)}")
  ```




  ```python
  async with AgentClient("http://localhost:8000") as client:
      
      async for event in client.interact_stream(agent_id, message):
          if event["type"] == "function_call":
              
              result = await client.execute_function(event["data"])
              await client.submit_result(agent_id, event["data"]["sequence_id"], result)
          elif event["type"] == "completion":
              print(f"Completed: {event['data']}")
  ```


  ```python
  async def process_commands(client, commands, instance_id):
      
      results = await client.execute_commands(commands, instance_id)
      return results
  ```


  The client includes comprehensive error handling with streaming support:


  ```python
  async with AgentClient("http://localhost:8000") as client:
      try:
          async for event in client.interact_stream(agent_id, message):
              if event["type"] == "error":
                  print(f"Error occurred: {event['data']}")
                  break
              elif event["type"] == "function_call":
                  try:
                      result = await client.execute_function(event["data"])
                      await client.submit_result(
                          agent_id,
                          event["data"]["sequence_id"],
                          result
                      )
                  except Exception as e:
                      print(f"Function execution error: {e}")
      except Exception as e:
          print(f"Stream error: {e}")
  ```


  ```python
  try:
      results = client.execute_commands(commands, context)
      for result in results['command_results']:
          if result['status'] == 'error':
              print(f"Command {result['command']} failed: {result['error']}")
  except client.CommandExecutionError as e:
      print(f"Execution error: {str(e)}")
  ```


  ```python
  try:
      chatbot = client.get_chatbot(999)
  except Exception as e:
      print(f"API error: {str(e)}")
  ```


  1. Always handle API errors in production code
  2. Store API keys securely
  3. Use appropriate timeouts for API calls
  4. Monitor rate limits
  5. Implement proper error handling
  6. Validate file paths before operations
  7. Use context information for better error tracking
  8. Implement proper retry strategies


  ```python

  try:
      
      response = client.interact_with_agent(agent_id, message)

      if response['status'] == 'pending_execution':
          try:
              
              results = client.execute_commands(
                  response['commands'],
                  response.get('context', {})
              )

              
              failed_commands = [
                  r for r in results['command_results']
                  if r['status'] == 'error'
              ]

              if failed_commands:
                  print("Some commands failed:")
                  for cmd in failed_commands:
                      print(f"- {cmd['command']}: {cmd['error']}")

              
              final_response = client.interact_with_agent(
                  agent_id,
                  message,
                  execution_results=results
              )

          except client.CommandExecutionError as e:
              print(f"Command execution failed: {e}")
              

  except Exception as e:
      print(f"Interaction failed: {e}")
      
  ```




  ```python
  client = AgentClient(
      base_url="http://localhost:8000",
      headers={"Custom-Header": "value"}
  )
  ```


  ```python

  configs = [
      {"name": "Bot1", "model": "gpt-4o-mini", "config": {...}},
      {"name": "Bot2", "model": "gpt-4o-mini", "config": {...}}
  ]

  chatbots = []
  for config in configs:
      bot = client.create_chatbot(**config)
      chatbots.append(bot)
  ```


pkgId: f4b1b6ff1b0c112e2d156255dddb8d0881beb9ee43a1a23243799439f973f147
name: python-agents-client
arch: src
version: 0.1.25
epoch: 0
release: 1
summary: A client library for interacting with the Agents API
url: https://github.com/Levangie-Laboratories/agents-client
rpm_license: Apache Software License
rpm_group: Unspecified
rpm_buildhost: localhost
location_href: Packages/python-agents-client-0.1.25-1.src.rpm
checksum_type: sha256
description:
  The Agents Client Library provides a simple interface for interacting with the Agents API. It handles authentication, request management, and provides convenient methods for managing chatbots and agentcli.




  ```bash
  pip install agents-client
  ```


  The client library uses a `config.json` file for API settings. You can either use the default configuration or provide your own:

  ```python
  from agentcli.client import AgentClient


  client = AgentClient()


  client = AgentClient(config_path='path/to/config.json')


  client = AgentClient(base_url='https://api.example.com', api_version='v2')
  ```


  - `base_url`: API base URL
  - `version`: API version
  - `timeout`: Request timeout in seconds
  - `retry_attempts`: Number of retry attempts
  - `retry_delay`: Delay between retries in seconds

  See `config.json` for all available options.




  ```python
  from agentcli import ChatbotClient
  from agentcli.base_client import ApiError, AuthenticationError


  base_url = "http://localhost:8000"
  chatbot = ChatbotClient(base_url)


  api_key = "your-api-key"
  chatbot.set_api_key(api_key)

  try:
      
      config = {
          "temperature": 0.7,
          "max_tokens": 4000,
          "behavior": "A helpful assistant that provides clear and concise answers."
      }

      
      response = chatbot.create_chatbot(
          name="BasicChat",
          model="gpt-4o-mini",
          config=config
      )

      
      chatbot_id = response.get('id')
      print(f"Created chatbot with ID: {chatbot_id}\n")

      
      message = "Hello! How are you?"
      chat_response = chatbot.chat(chatbot_id, message)
      print(f"Chatbot: {chat_response.get('response', 'No response')}\n")

  except AuthenticationError as e:
      print(f"Authentication error: {str(e)}")
  except ApiError as e:
      print(f"API error: {str(e)}")
  ```


  ```python
  from agentcli.client import AgentClient
  import asyncio

  async def main():
      
      async with AgentClient("http://localhost:8000") as client:
          client.set_api_key("your-api-key")

          
          config = {
              "behavior": "task-focused",
              "model": "gpt-4o-mini",
              "api_mode": True  # Enable API execution mode
          }
          agent = await client.create_agent_with_tools(
              name="FileManager",
              model="gpt-4o-mini",
              tools=FileTools(),  # Your tool class instance
              config=config
          )

          
          async for event in client.process_agent_request(agent["id"], "Update debug mode in config.json"):
              if event["type"] == "function_call":
                  print(f"Executing function: {event['data']['function']}")
                  
              elif event["type"] == "execution_status":
                  print(f"Execution result: {event['data']}")
              elif event["type"] == "completion":
                  print(f"Task completed: {event['data']}")
              elif event["type"] == "error":
                  print(f"Error: {event['data']}")


  asyncio.run(main())
  ```


  ```python
  async with AgentClient("http://localhost:8000") as client:
      
      async for event in client.process_agent_request(agent_id, message):
          if event["type"] == "state_update":
              print(f"Agent state updated: {event['data']}")
          elif event["type"] == "function_call":
              
              result = await client.execute_function(event["data"])
              
              await client.submit_result(agent_id, event["data"]["sequence_id"], result)
  ```




  ```python
  from agentcli import ChatbotClient
  from agentcli.base_client import ApiError, AuthenticationError


  base_url = "http://localhost:8000"
  chatbot_client = ChatbotClient(base_url)


  api_key = "your-api-key"
  chatbot_client.set_api_key(api_key)

  try:
      
      config = {
          "temperature": 0.7,
          "max_tokens": 4000,
          "behavior": "A helpful assistant that provides clear and concise answers."
      }

      
      response = chatbot_client.create_chatbot(
          name="BasicChat",
          model="gpt-4o-mini",
          config=config
      )

      
      chatbot_id = response.get('id')
      print(f"Created chatbot with ID: {chatbot_id}\n")

  except AuthenticationError as e:
      print(f"Authentication error: {str(e)}")
  except ApiError as e:
      print(f"API error: {str(e)}")
  ```


  ```python
  chatbots = client.list_chatbots()
  for bot in chatbots:
      print(f"Bot: {bot['name']} (ID: {bot['id']})")
  ```


  ```python
  try:
      
      print("=== Chatbot Interaction ===\n")
      chat_response = chatbot_client.chat(
          chatbot_id,
          "What's the weather like today?"
      )
      print(f"Chatbot: {chat_response['data']['response']}\n")

      
      print("=== Chatbot History ===\n")
      history = chatbot_client.get_history(chatbot_id)
      print(f"Chat history: {history}\n")

  except ApiError as e:
      print(f"API Error: {str(e)}\n")
  ```


  ```python
  updated_config = {
      "temperature": 0.8,
      "max_tokens": 1000
  }

  updated_bot = client.update_chatbot(
      chatbot_id=123,
      name="UpdatedBot",
      model="gpt-4o-mini",
      config=updated_config
  )
  ```


  ```python
  result = client.delete_chatbot(chatbot_id=123)
  ```



  Both ChatbotClient and AgentClient support simplified image handling. You can use images in three ways:

  ```python

  chatbot.chat(
      chatbot_id='id',
      message='What's in this image?',
      image='https://example.com/image.jpg'
  )


  chatbot.chat(
      chatbot_id='id',
      message='What's in this image?',
      image='path/to/local/image.jpg'
  )


  chatbot.chat(
      chatbot_id='id',
      message='What's in this image?',
      image=base64_string
  )
  ```

  The system automatically detects the type of input and handles it appropriately. The same functionality is available for AgentClient:

  ```python
  agent.interact(
      agent_id='id',
      message='Analyze this image',
      image='path/to/image.jpg'  # Can be URL, file path, or base64
  )
  ```




  ```python
  from agentcli import AgentClient
  from agentcli.base_client import ApiError, AuthenticationError


  base_url = "http://localhost:8000"
  agent_client = AgentClient(base_url)


  api_key = "your-api-key"
  agent_client.set_api_key(api_key)

  try:
      
      agent_tools = {
          "general": {
              "search": {
                  "name": "search",
                  "description": "Search for information",
                  "parameters": {}
              }
          }
      }

      agent_config = {
          "model": "gpt-4o-mini",
          "temperature": 0.7,
          "max_tokens": 4000
      }

      
      agent = agent_client.create_agent(
          name="ResearchAgent",
          agent_type="research",
          behavior="A research agent that helps find and analyze information.",
          tools=agent_tools,
          config=agent_config
      )
      print(f"Created agent with ID: {agent['id']}\n")

  except AuthenticationError as e:
      print(f"Authentication error: {str(e)}")
  except ApiError as e:
      print(f"API error: {str(e)}")
  ```


  ```python
  agents = client.list_agents()
  for agent in agents:
      print(f"Agent: {agent['name']} (ID: {agent['id']})")
  ```


  ```python
  try:
      
      print("=== Agent Interaction ===\n")
      agent_response = agent_client.interact(
          agent['id'],
          "Find information about Python programming."
      )
      print(f"Agent response: {agent_response['data']['response']}\n")

      
      print("=== Agent State ===\n")
      state = agent_client.get_state(agent['id'])
      print(f"Agent state: {state}\n")

      
      print("=== Error Handling ===\n")
      try:
          
          agent_client.interact("invalid-id", "Hello!")
      except ApiError as e:
          print(f"Handled API error: {str(e)}\n")

  except AuthenticationError as e:
      print(f"Authentication error: {str(e)}")
  except ApiError as e:
      print(f"API error: {str(e)}")
  except Exception as e:
      print(f"Unexpected error: {str(e)}")
  ```

  The new system simplifies command execution by:
  ```

  Key features of the new command system:
  - Automatic command execution and result handling
  - Built-in command validation and safety checks
  - Simplified tool registration using decorators
  - Automatic result mapping in responses
  - Support for both synchronous and asynchronous operations
  - Comprehensive error handling and reporting


  The client can execute various commands locally:

  ```python

  commands = [
      {"view_file": {"file_path": "config.json"}},
      {"smart_replace": {
          "file_path": "config.json",
          "old_text": "debug: false",
          "new_text": "debug: true"
      }},
      {"create_file": {
          "file_path": "new_file.txt",
          "content": "Hello, world!"
      }}
  ]


  results = client.execute_commands(commands, context={})
  ```


  - File path validation
  - Comprehensive error handling
  - Safe text replacement
  - Automatic retries for network issues

  ```python

  try:
      results = client.execute_commands(commands, context={})
      if any(r["status"] == "error" for r in results["command_results"]):
          print("Some commands failed to execute")
          for result in results["command_results"]:
              if result["status"] == "error":
                  print(f"Error: {result['error']}")
  except Exception as e:
      print(f"Execution failed: {str(e)}")
  ```




  ```python
  async with AgentClient("http://localhost:8000") as client:
      
      async for event in client.interact_stream(agent_id, message):
          if event["type"] == "function_call":
              
              result = await client.execute_function(event["data"])
              await client.submit_result(agent_id, event["data"]["sequence_id"], result)
          elif event["type"] == "completion":
              print(f"Completed: {event['data']}")
  ```


  ```python
  async def process_commands(client, commands, instance_id):
      
      results = await client.execute_commands(commands, instance_id)
      return results
  ```


  The client includes comprehensive error handling with streaming support:


  ```python
  async with AgentClient("http://localhost:8000") as client:
      try:
          async for event in client.interact_stream(agent_id, message):
              if event["type"] == "error":
                  print(f"Error occurred: {event['data']}")
                  break
              elif event["type"] == "function_call":
                  try:
                      result = await client.execute_function(event["data"])
                      await client.submit_result(
                          agent_id,
                          event["data"]["sequence_id"],
                          result
                      )
                  except Exception as e:
                      print(f"Function execution error: {e}")
      except Exception as e:
          print(f"Stream error: {e}")
  ```


  ```python
  try:
      results = client.execute_commands(commands, context)
      for result in results['command_results']:
          if result['status'] == 'error':
              print(f"Command {result['command']} failed: {result['error']}")
  except client.CommandExecutionError as e:
      print(f"Execution error: {str(e)}")
  ```


  ```python
  try:
      chatbot = client.get_chatbot(999)
  except Exception as e:
      print(f"API error: {str(e)}")
  ```


  1. Always handle API errors in production code
  2. Store API keys securely
  3. Use appropriate timeouts for API calls
  4. Monitor rate limits
  5. Implement proper error handling
  6. Validate file paths before operations
  7. Use context information for better error tracking
  8. Implement proper retry strategies


  ```python

  try:
      
      response = client.interact_with_agent(agent_id, message)

      if response['status'] == 'pending_execution':
          try:
              
              results = client.execute_commands(
                  response['commands'],
                  response.get('context', {})
              )

              
              failed_commands = [
                  r for r in results['command_results']
                  if r['status'] == 'error'
              ]

              if failed_commands:
                  print("Some commands failed:")
                  for cmd in failed_commands:
                      print(f"- {cmd['command']}: {cmd['error']}")

              
              final_response = client.interact_with_agent(
                  agent_id,
                  message,
                  execution_results=results
              )

          except client.CommandExecutionError as e:
              print(f"Command execution failed: {e}")
              

  except Exception as e:
      print(f"Interaction failed: {e}")
      
  ```




  ```python
  client = AgentClient(
      base_url="http://localhost:8000",
      headers={"Custom-Header": "value"}
  )
  ```


  ```python

  configs = [
      {"name": "Bot1", "model": "gpt-4o-mini", "config": {...}},
      {"name": "Bot2", "model": "gpt-4o-mini", "config": {...}}
  ]

  chatbots = []
  for config in configs:
      bot = client.create_chatbot(**config)
      chatbots.append(bot)
  ```


pkgId: 4502b3122135117626db02b43dad330349969b3e990c4703757d4d81575facda
name: python-agentserve
arch: src
version: 0.2.10
epoch: 0
release: 1
summary: A framework for hosting and scaling AI agents.
url: https://github.com/PropsAI/agentserve
rpm_license: None
rpm_group: Unspecified
rpm_buildhost: localhost
location_href: Packages/python-agentserve-0.2.10-1.src.rpm
checksum_type: sha256
description:
  ```
     ___                __  ____
    / _ |___ ____ ___  / /_/ __/__ _____  _____
   / __ / _ `/ -_) _ \/ __/\ \/ -_) __/ |/ / -_)
  /_/ |_\_, /\__/_//_/\__/___/\__/_/  |___/\__/
       /___/
  ```



  [![Discord](https://img.shields.io/badge/Discord-Join_Discord-blue?style=flat&logo=Discord)](https://discord.gg/JkPrCnExSf)
  [![GitHub](https://img.shields.io/badge/GitHub-View_on_GitHub-blue?style=flat&logo=GitHub)](https://github.com/PropsAI/agentserve)
  ![License](https://img.shields.io/badge/License-MIT-blue.svg)
  ![PyPI Version](https://img.shields.io/pypi/v/agentserve.svg)
  ![GitHub Stars](https://img.shields.io/github/stars/PropsAI/agentserve?style=social)
  ![Beta](https://img.shields.io/badge/Status-Beta-yellow)

  AgentServe is a lightweight framework for hosting and scaling AI agents. It is designed to be easy to use and integrate with existing projects and agent / LLM frameworks. It wraps your agent in a REST API and supports optional task queuing for scalability.

  Join the [Discord](https://discord.gg/JkPrCnExSf) for support and discussion.



  The goal of AgentServe is to provide the easiest way to take an local agent to production and standardize the communication layer between multiple agents, humans, and other systems.



  - **Standardized:** AgentServe provides a standardized way to communicate with AI agents via a REST API.
  - **Framework Agnostic:** AgentServe supports multiple agent frameworks (OpenAI, LangChain, LlamaIndex, and Blank).
  - **Task Queuing:** AgentServe supports optional task queuing for scalability. Choose between local, Redis, or Celery task queues based on your needs.
  - **Configurable:** AgentServe is designed to be configurable via an `agentserve.yaml` file and overridable with environment variables.
  - **Easy to Use:** AgentServe aims to be easy to use and integrate with existing projects and make deployment as simple as possible.



  - Python 3.9+



  To install AgentServe, you can use pip:

  ```bash
  pip install -U agentserve
  ```



  AgentServe allows you to easily wrap your agent code in a FastAPI application and expose it via REST endpoints. Below are the steps to integrate AgentServe into your project.



  First, install the `agentserve` package using pip:

  ```bash
  pip install -U agentserve
  ```

  Make sure your virtual environment is activated if you're using one.



  Within your entry point file (e.g. `main.py`) we will import `agentserve` and create an app instance, then decorate an agent function with `@app.agent`. Finally, we will call `app.run()` to start the server.

  The agent function should take a single argument, `task_data`, which will be a dictionary of data prequired by your agent.

  **Example:**

  ```python

  import agentserve
  from openai import OpenAI

  app = agentserve.app()

  @app.agent
  def my_agent(task_data):
      
      client = OpenAI()
      response = client.chat.completions.create(
          model="gpt-4o-mini",
          messages=[{"role": "user", "content": task_data["prompt"]}]
      )
      return response.choices[0].message.content

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

  In this example:

  - We import agentserve and create an app instance using `agentserve.app()`.
  - We define our agent function `my_agent` and decorate it with `@app.agent`.
  - Within the agent function, we implement our agent's logic.
  - We call `app.run()` to start the server.



  To run the agent server, use the following command:

  ```bash
  python main.py
  ```



  By default, AgentServe uses a local task queue, which is suitable for development and testing. If you need more robust queue management for production, you can configure AgentServe to use Redis or Celery.

  **Using a Configuration File**
  Create a file named agentserve.yaml in your project directory:

  ```yaml


  task_queue: celery # Options: 'local', 'redis', 'celery'

  celery:
    broker_url: pyamqp://guest@localhost//
  ```

  **Using Environment Variables**

  Alternatively, you can set configuration options using environment variables:

  ```bash
  export AGENTSERVE_TASK_QUEUE=celery
  export AGENTSERVE_CELERY_BROKER_URL=pyamqp://guest@localhost//
  ```



  To start the worker, use the following command:

  ```bash
  agentserve startworker
  ```



  With the server and worker (if needed) running, you can test your agent using the available endpoints.

  **Synchronous Task Processing**

  `POST /task/sync`

  ```bash
  curl -X POST http://localhost:8000/task/sync \
       -H "Content-Type: application/json" \
         -d '{"input": "Test input"}'
  ```

  **Asynchronously process a task**

  `POST /task/async`

  ```bash
  curl -X POST http://localhost:8000/task/async \
       -H "Content-Type: application/json" \
         -d '{"input": "Test input"}'
  ```

  **Get the status of a task**

  `GET /task/status/:task_id`

  ```bash
  curl http://localhost:8000/task/status/1234567890
  ```

  **Get the result of a task**

  `GET /task/result/:task_id`

  ```bash
  curl http://localhost:8000/task/result/1234567890
  ```



  AgentServe allows you to configure various aspects of the application using a configuration file or environment variables.



  Place an `agentserve.yaml` file in your project directory with the desired configurations.

  **Example:**

  ```yaml


  task_queue: celery # Options: 'local', 'redis', 'celery'

  celery:
    broker_url: pyamqp://guest@localhost//

  redis:
    host: localhost
    port: 6379

  server:
    host: 0.0.0.0
    port: 8000

  queue: # if using local task queue
    max_workers: 10 # default
  ```




  Set the desired configuration options using environment variables.

  You can override configurations using environment variables without modifying the configuration file.

  - `AGENTSERVE_TASK_QUEUE`
  - `AGENTSERVE_CELERY_BROKER_URL`
  - `AGENTSERVE_REDIS_HOST`
  - `AGENTSERVE_REDIS_PORT`
  - `AGENTSERVE_SERVER_HOST`
  - `AGENTSERVE_SERVER_PORT`
  - `AGENTSERVE_QUEUE_MAX_WORKERS`

  **Example:**

  ```bash
  export AGENTSERVE_TASK_QUEUE=redis
  export AGENTSERVE_REDIS_HOST=redis-server-host
  export AGENTSERVE_REDIS_PORT=6379
  ```



  You can specify FastAPI settings, including CORS configuration, using the `fastapi` key in your `agentserve.yaml` configuration file.

  **Example:**

  ```yaml


  fastapi:
    cors:
      allow_origins:
        - "http://localhost:3000"
        - "https://yourdomain.com"
      allow_credentials: true
      allow_methods:
        - "*"
      allow_headers:
        - "*"
  ```


  Alternatively, you can set the desired configuration options using environment variables.

  **Example:**

  ```bash
  export AGENTSERVE_CORS_ORIGINS="http://localhost:3000,https://yourdomain.com"
  export AGENTSERVE_CORS_ALLOW_CREDENTIALS="true"
  export AGENTSERVE_CORS_ALLOW_METHODS="GET,POST"
  export AGENTSERVE_CORS_ALLOW_HEADERS="Content-Type,Authorization"
  ```





  You can integrate AgentServe into your existing projects by importing agentserve and defining your agent function.

  **Example:**

  ```python

  import agentserve

  app = agentserve.app()

  @app.agent
  def my_custom_agent(task_data):
      
      result = perform_complex_computation(task_data)
      return {"result": result}

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



  AgentServe allows you to validate the input to your agent function using Pydantic. Simply add an input schema to your agent function.

  **Example:**

  ```python

  import agentserve
  from pydantic import BaseModel

  class MyInputSchema(BaseModel):
      prompt: str

  @app.agent(input_schema=MyInputSchema)
  def my_custom_agent(task_data):
      
      return {"result": "Hello, world!"}

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



  INSTRUCTIONS COMING SOON



  - [ ] Add support for streaming responses
  - [ ] Add easy instructions for more hosting options (GCP, Azure, AWS, etc.)
  - [ ] Add support for external storage for task results
  - [ ] Add support for multi model agents
  - [ ] Add support for more agent frameworks



  This project is licensed under the MIT License.



  Join the [Discord](https://discord.gg/JkPrCnExSf) for support and discussion.

  For any questions or issues, please contact Peter at peter@getprops.ai.


pkgId: 3d8229e2e45ffba5f807a063757b6e8fcaa2fc9594d2ca5956f40836ac2f8745
name: python-agentserve
arch: src
version: 0.2.8
epoch: 0
release: 1
summary: A framework for hosting and scaling AI agents.
url: https://github.com/PropsAI/agentserve
rpm_license: None
rpm_group: Unspecified
rpm_buildhost: localhost
location_href: Packages/python-agentserve-0.2.8-1.src.rpm
checksum_type: sha256
description:
  ```
     ___                __  ____
    / _ |___ ____ ___  / /_/ __/__ _____  _____
   / __ / _ `/ -_) _ \/ __/\ \/ -_) __/ |/ / -_)
  /_/ |_\_, /\__/_//_/\__/___/\__/_/  |___/\__/
       /___/
  ```



  [![Discord](https://img.shields.io/badge/Discord-Join_Discord-blue?style=flat&logo=Discord)](https://discord.gg/JkPrCnExSf)
  [![GitHub](https://img.shields.io/badge/GitHub-View_on_GitHub-blue?style=flat&logo=GitHub)](https://github.com/PropsAI/agentserve)
  ![License](https://img.shields.io/badge/License-MIT-blue.svg)
  ![PyPI Version](https://img.shields.io/pypi/v/agentserve.svg)
  ![GitHub Stars](https://img.shields.io/github/stars/PropsAI/agentserve?style=social)
  ![Beta](https://img.shields.io/badge/Status-Beta-yellow)

  AgentServe is a lightweight framework for hosting and scaling AI agents. It is designed to be easy to use and integrate with existing projects and agent / LLM frameworks. It wraps your agent in a REST API and supports optional task queuing for scalability.

  Join the [Discord](https://discord.gg/JkPrCnExSf) for support and discussion.



  The goal of AgentServe is to provide the easiest way to take an local agent to production and standardize the communication layer between multiple agents, humans, and other systems.



  - **Standardized:** AgentServe provides a standardized way to communicate with AI agents via a REST API.
  - **Framework Agnostic:** AgentServe supports multiple agent frameworks (OpenAI, LangChain, LlamaIndex, and Blank).
  - **Task Queuing:** AgentServe supports optional task queuing for scalability. Choose between local, Redis, or Celery task queues based on your needs.
  - **Configurable:** AgentServe is designed to be configurable via an `agentserve.yaml` file and overridable with environment variables.
  - **Easy to Use:** AgentServe aims to be easy to use and integrate with existing projects and make deployment as simple as possible.



  - Python 3.9+



  To install AgentServe, you can use pip:

  ```bash
  pip install -U agentserve
  ```



  AgentServe allows you to easily wrap your agent code in a FastAPI application and expose it via REST endpoints. Below are the steps to integrate AgentServe into your project.



  First, install the `agentserve` package using pip:

  ```bash
  pip install -U agentserve
  ```

  Make sure your virtual environment is activated if you're using one.



  Within your entry point file (e.g. `main.py`) we will import `agentserve` and create an app instance, then decorate an agent function with `@app.agent`. Finally, we will call `app.run()` to start the server.

  The agent function should take a single argument, `task_data`, which will be a dictionary of data prequired by your agent.

  **Example:**

  ```python

  import agentserve
  from openai import OpenAI

  app = agentserve.app()

  @app.agent
  def my_agent(task_data):
      
      client = OpenAI()
      response = client.chat.completions.create(
          model="gpt-4o-mini",
          messages=[{"role": "user", "content": task_data["prompt"]}]
      )
      return response.choices[0].message.content

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

  In this example:

  - We import agentserve and create an app instance using `agentserve.app()`.
  - We define our agent function `my_agent` and decorate it with `@app.agent`.
  - Within the agent function, we implement our agent's logic.
  - We call `app.run()` to start the server.



  To run the agent server, use the following command:

  ```bash
  python main.py
  ```



  By default, AgentServe uses a local task queue, which is suitable for development and testing. If you need more robust queue management for production, you can configure AgentServe to use Redis or Celery.

  **Using a Configuration File**
  Create a file named agentserve.yaml in your project directory:

  ```yaml


  task_queue: celery # Options: 'local', 'redis', 'celery'

  celery:
    broker_url: pyamqp://guest@localhost//
  ```

  **Using Environment Variables**

  Alternatively, you can set configuration options using environment variables:

  ```bash
  export AGENTSERVE_TASK_QUEUE=celery
  export AGENTSERVE_CELERY_BROKER_URL=pyamqp://guest@localhost//
  ```



  To start the worker, use the following command:

  ```bash
  agentserve startworker
  ```



  With the server and worker (if needed) running, you can test your agent using the available endpoints.

  **Synchronous Task Processing**

  `POST /task/sync`

  ```bash
  curl -X POST http://localhost:8000/task/sync \
       -H "Content-Type: application/json" \
         -d '{"input": "Test input"}'
  ```

  **Asynchronously process a task**

  `POST /task/async`

  ```bash
  curl -X POST http://localhost:8000/task/async \
       -H "Content-Type: application/json" \
         -d '{"input": "Test input"}'
  ```

  **Get the status of a task**

  `GET /task/status/:task_id`

  ```bash
  curl http://localhost:8000/task/status/1234567890
  ```

  **Get the result of a task**

  `GET /task/result/:task_id`

  ```bash
  curl http://localhost:8000/task/result/1234567890
  ```



  AgentServe allows you to configure various aspects of the application using a configuration file or environment variables.



  Place an `agentserve.yaml` file in your project directory with the desired configurations.

  **Example:**

  ```yaml


  task_queue: celery # Options: 'local', 'redis', 'celery'

  celery:
    broker_url: pyamqp://guest@localhost//

  redis:
    host: localhost
    port: 6379

  server:
    host: 0.0.0.0
    port: 8000

  queue: # if using local task queue
    max_workers: 10 # default
  ```



  Set the desired configuration options using environment variables.

  You can override configurations using environment variables without modifying the configuration file.

  - `AGENTSERVE_TASK_QUEUE`
  - `AGENTSERVE_CELERY_BROKER_URL`
  - `AGENTSERVE_REDIS_HOST`
  - `AGENTSERVE_REDIS_PORT`
  - `AGENTSERVE_SERVER_HOST`
  - `AGENTSERVE_SERVER_PORT`

  **Example:**

  ```bash
  export AGENTSERVE_TASK_QUEUE=redis
  export AGENTSERVE_REDIS_HOST=redis-server-host
  export AGENTSERVE_REDIS_PORT=6379
  ```





  You can integrate AgentServe into your existing projects by importing agentserve and defining your agent function.

  **Example:**

  ```python

  import agentserve

  app = agentserve.app()

  @app.agent
  def my_custom_agent(task_data):
      
      result = perform_complex_computation(task_data)
      return {"result": result}

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



  AgentServe allows you to validate the input to your agent function using Pydantic. Simply add an input schema to your agent function.

  **Example:**

  ```python

  import agentserve
  from pydantic import BaseModel

  class MyInputSchema(BaseModel):
      prompt: str

  @app.agent(input_schema=MyInputSchema)
  def my_custom_agent(task_data):
      
      return {"result": "Hello, world!"}

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



  INSTRUCTIONS COMING SOON



  - [ ] Add support for streaming responses
  - [ ] Add easy instructions for more hosting options (GCP, Azure, AWS, etc.)
  - [ ] Add support for external storage for task results
  - [ ] Add support for multi model agents
  - [ ] Add support for more agent frameworks



  This project is licensed under the MIT License.



  Join the [Discord](https://discord.gg/JkPrCnExSf) for support and discussion.

  For any questions or issues, please contact Peter at peter@getprops.ai.


pkgId: f6ba3dfad7db91e0e2daa05cafedd7eedbfc3c2ecfb961cfde244207144f134d
name: python-agentsys
arch: src
version: 0.2.0
epoch: 0
release: 1
summary: A robust, asynchronous multi-agent development framework
url: https://github.com/lifsys/agentsys
rpm_group: Unspecified
rpm_buildhost: localhost
location_href: Packages/python-agentsys-0.2.0-1.src.rpm
checksum_type: sha256
description:
  A robust, asynchronous multi-agent development framework designed for building scalable agent-based systems.



  AgentSys is a Python framework that provides a flexible and powerful infrastructure for developing, testing, and deploying multi-agent systems. It focuses on:

  - **Asynchronous Execution**: Built from the ground up with async/await support
  - **Robust Error Handling**: Comprehensive error management and recovery
  - **Flexible Routing**: Multiple routing strategies for agent communication
  - **Persistent Storage**: Both in-memory and file-based storage options
  - **Comprehensive Testing**: Full test coverage with async support





  An agent in AgentSys is a self-contained unit that can:
  - Process tasks asynchronously
  - Maintain internal state
  - Communicate with other agents
  - Handle errors gracefully
  - Store and retrieve data

  Example of a basic agent:

  ```python
  from agentsys.plugins.router import Agent, Task, ExecutionResult, AgentState

  class DataProcessingAgent(Agent):
      def __init__(self, name: str, storage):
          super().__init__(name)
          self.storage = storage
          self.processed_count = 0

      async def process(self, task: Task) -> ExecutionResult:
          try:
              
              result = await self._transform_data(task.input)

              
              await self.storage.put(f"result_{task.id}", result)

              
              self.processed_count += 1

              return ExecutionResult(
                  status=AgentState.COMPLETED,
                  result=result
              )
          except Exception as e:
              return ExecutionResult(
                  status=AgentState.FAILED,
                  error=str(e)
              )

      async def _transform_data(self, data):
          
          return f"Processed: {data}"
  ```



  Tasks are the fundamental unit of work in AgentSys:

  ```python
  from agentsys.plugins.router import Task, TaskPriority


  task = Task(
      input="raw_data",
      id="unique_id",  # Optional, auto-generated if not provided
      metadata={"source": "sensor_1"}  # Optional metadata
  )


  priority_task = Task(
      input="urgent_data",
      priority=TaskPriority.HIGH
  )


  routed_task = Task(
      input="specialized_data",
      routing_key="data_processing"
  )
  ```



  The router orchestrates communication between agents:

  ```python
  from agentsys.plugins.router import AgentRouter, RoutingConfig, RoutingStrategy


  router = AgentRouter(
      routing_config=RoutingConfig(
          strategy=RoutingStrategy.ROUND_ROBIN,
          timeout=60,
          max_retries=3
      )
  )


  data_agent = DataProcessingAgent("data_processor", storage)
  await router.register_agent(data_agent)


  @router.route("process_data")
  async def process_data(task: Task):
      return await data_agent.process(task)


  router.add_route(
      route_key="backup_data",
      handler=data_agent.process
  )
  ```



  AgentSys provides flexible storage options:

  ```python
  from agentsys.plugins.storage import FileStorage, MemoryStorage, StorageConfig


  file_storage = FileStorage(
      config=StorageConfig(
          base_path="./data",
          backup_enabled=True,
          backup_interval=3600
      )
  )


  memory_storage = MemoryStorage()


  await storage.put("key", {"data": "value"})
  data = await storage.get("key")
  await storage.delete("key")


  keys = await storage.list(prefix="result_")


  await storage.backup()
  ```



  Here's how to build a complete agent system:

  ```python
  import asyncio
  from agentsys.plugins.router import (
      AgentRouter, Agent, Task, ExecutionResult,
      AgentState, RoutingConfig, RoutingStrategy
  )
  from agentsys.plugins.storage import FileStorage, StorageConfig


  class AnalyticsAgent(Agent):
      def __init__(self, name: str, storage):
          super().__init__(name)
          self.storage = storage

      async def process(self, task: Task) -> ExecutionResult:
          try:
              
              result = await self._analyze(task.input)

              
              await self.storage.put(
                  f"analytics_{task.id}",
                  result
              )

              return ExecutionResult(
                  status=AgentState.COMPLETED,
                  result=result
              )
          except Exception as e:
              return ExecutionResult(
                  status=AgentState.FAILED,
                  error=str(e)
              )

      async def _analyze(self, data):
          
          return {"analyzed": data}


  storage = FileStorage(
      config=StorageConfig(
          base_path="./data",
          backup_enabled=True
      )
  )


  router = AgentRouter(
      routing_config=RoutingConfig(
          strategy=RoutingStrategy.ROUND_ROBIN,
          timeout=60
      )
  )


  analytics_agent = AnalyticsAgent("analytics_1", storage)
  await router.register_agent(analytics_agent)


  @router.route("analyze_data")
  async def analyze_data(task: Task):
      return await analytics_agent.process(task)


  async def main():
      try:
          
          task = Task(
              input={"data": "sample"},
              metadata={"priority": "high"}
          )

          
          result = await router.submit_task(task)

          
          if result.status == AgentState.COMPLETED:
              print(f"Analysis complete: {result.result}")
          else:
              print(f"Analysis failed: {result.error}")
      finally:
          
          await router.stop()


  if __name__ == "__main__":
      asyncio.run(main())
  ```



  Comprehensive testing example:

  ```python
  import pytest
  from agentsys.plugins.router import AgentRouter, Task, AgentState

  @pytest.fixture
  async def router_instance():
      router = AgentRouter()
      try:
          yield router
      finally:
          await router.stop()

  @pytest.fixture
  async def analytics_agent(router_instance):
      agent = AnalyticsAgent("test_agent", MemoryStorage())
      await router_instance.register_agent(agent)
      return agent

  @pytest.mark.asyncio
  async def test_analytics_agent(router_instance, analytics_agent):
      
      test_data = {"test": "data"}

      
      task = Task(input=test_data)
      result = await router_instance.submit_task(task)

      
      assert result.status == AgentState.COMPLETED
      assert "analyzed" in result.result
      assert result.error is None
  ```



  Requires Python 3.11+

  ```bash
  pip install agentsys
  ```





  The router is the central component that manages agent communication and task execution:

  ```python
  from agentsys.plugins.router import AgentRouter, Route, Task, RoutingConfig


  router = AgentRouter(routing_config=RoutingConfig())


  @router.route("process_data")
  async def process_data(task: Task):
      result = await process(task.input)
      return ExecutionResult(
          status=AgentState.COMPLETED,
          result=result
      )


  task = Task(input="test_input")
  result = await router.submit_task(task)
  ```



  Flexible storage options for persisting agent state and data:

  ```python
  from agentsys.plugins.storage import FileStorage, MemoryStorage, StorageConfig


  storage = FileStorage(config=StorageConfig(
      base_path="./data",
      backup_enabled=True
  ))


  memory_storage = MemoryStorage()


  await storage.put("key", "value")
  value = await storage.get("key")
  ```



  Multiple routing strategies available:

  - **RoundRobin**: Distributes tasks evenly across agents
  - **LeastLoaded**: Routes to agents with lowest workload
  - **Priority**: Routes based on task priority
  - **Custom**: Implement your own routing logic

  ```python
  from agentsys.plugins.router import RoutingStrategy

  config = RoutingConfig(
      strategy=RoutingStrategy.ROUND_ROBIN
  )
  ```



  1. **Agent Design**
     - Keep agents focused on a single responsibility
     - Implement proper error handling
     - Use storage for persistence
     - Clean up resources properly

  2. **Task Management**
     - Include relevant metadata
     - Set appropriate priorities
     - Use routing keys for specific agents
     - Handle task timeouts

  3. **Resource Management**
     - Always use try/finally blocks
     - Stop routers explicitly
     - Clean up storage resources
     - Use async context managers

  4. **Error Handling**
     - Return proper ExecutionResult objects
     - Log errors with context
     - Implement retry mechanisms
     - Use timeouts for long operations

  5. **Testing**
     - Test both success and failure cases
     - Use proper async fixtures
     - Clean up resources in tests
     - Test with different routing strategies



  Example configuration for production:

  ```python
  router_config = RoutingConfig(
      strategy=RoutingStrategy.ROUND_ROBIN,
      timeout=60,
      max_retries=3,
      max_queue_size=1000,
      logging_enabled=True
  )

  storage_config = StorageConfig(
      base_path="./data",
      backup_enabled=True,
      backup_interval=3600,
      compression_enabled=True,
      max_size_mb=1024
  )
  ```



  1. Fork the repository
  2. Create a feature branch
  3. Submit a pull request



  MIT License



  - Python 3.11+
  - pytest-asyncio
  - pydantic

rpm_license:
  MIT License  Copyright (c) 2024 OpenAI  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:  The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


