diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..b8b8480 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,10 @@ +version: 2 +updates: + - package-ecosystem: "pip" + directory: "/" + schedule: + interval: "monthly" + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "monthly" diff --git a/.github/pr-labeler.yml b/.github/pr-labeler.yml new file mode 100644 index 0000000..a3f3d98 --- /dev/null +++ b/.github/pr-labeler.yml @@ -0,0 +1,4 @@ +feature: ['features/*', 'feature/*', 'feat/*', 'features-*', 'feature-*', 'feat-*'] +fix: ['fixes/*', 'fix/*'] +chore: ['chore/*'] +dependencies: ['update/*'] diff --git a/.github/release-drafter.yml b/.github/release-drafter.yml new file mode 100644 index 0000000..66e8be2 --- /dev/null +++ b/.github/release-drafter.yml @@ -0,0 +1,40 @@ +name-template: "v$RESOLVED_VERSION" +tag-template: "v$RESOLVED_VERSION" +categories: + - title: "๐Ÿš€ Features" + labels: + - "feature" + - "enhancement" + - title: "๐Ÿ› Bug Fixes" + labels: + - "fix" + - "bugfix" + - "bug" + - title: "๐Ÿงน Maintenance" + labels: + - "maintenance" + - "dependencies" + - "refactoring" + - "cosmetic" + - "chore" + - title: "๐Ÿ“๏ธ Documentation" + labels: + - "documentation" + - "docs" +change-template: "- $TITLE (#$NUMBER)" +change-title-escapes: '\<*_&' # You can add # and @ to disable mentions +version-resolver: + major: + labels: + - "major" + minor: + labels: + - "minor" + patch: + labels: + - "patch" + default: patch +template: | + ## Changes + + $CHANGES diff --git a/.github/workflows/draft.yml b/.github/workflows/draft.yml new file mode 100644 index 0000000..f5659bf --- /dev/null +++ b/.github/workflows/draft.yml @@ -0,0 +1,20 @@ +# Drafts the next Release notes as Pull Requests are merged (or commits are pushed) into "main" or "master" +name: Draft next release + +on: + push: + branches: [main, "master"] + +permissions: + contents: read + +jobs: + update-release-draft: + permissions: + contents: write + pull-requests: write + runs-on: ubuntu-latest + steps: + - uses: release-drafter/release-drafter@v5 + env: + GITHUB_TOKEN: ${{ github.token }} diff --git a/.github/workflows/pr_labeler.yml b/.github/workflows/pr_labeler.yml new file mode 100644 index 0000000..d020aa4 --- /dev/null +++ b/.github/workflows/pr_labeler.yml @@ -0,0 +1,17 @@ +# This workflow will apply the corresponding label on a pull request +name: PR Labeler + +on: + pull_request_target: + +permissions: + contents: read + pull-requests: write + +jobs: + pr-labeler: + runs-on: ubuntu-latest + steps: + - uses: TimonVS/pr-labeler-action@v4 + with: + repo-token: ${{ github.token }} diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..45007cf --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,128 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +We as members, contributors, and leaders pledge to make participation in our +community a harassment-free experience for everyone, regardless of age, body +size, visible or invisible disability, ethnicity, sex characteristics, gender +identity and expression, level of experience, education, socio-economic status, +nationality, personal appearance, race, religion, or sexual identity +and orientation. + +We pledge to act and interact in ways that contribute to an open, welcoming, +diverse, inclusive, and healthy community. + +## Our Standards + +Examples of behavior that contributes to a positive environment for our +community include: + +* Demonstrating empathy and kindness toward other people +* Being respectful of differing opinions, viewpoints, and experiences +* Giving and gracefully accepting constructive feedback +* Accepting responsibility and apologizing to those affected by our mistakes, + and learning from the experience +* Focusing on what is best not just for us as individuals, but for the + overall community + +Examples of unacceptable behavior include: + +* The use of sexualized language or imagery, and sexual attention or + advances of any kind +* Trolling, insulting or derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or email + address, without their explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Enforcement Responsibilities + +Community leaders are responsible for clarifying and enforcing our standards of +acceptable behavior and will take appropriate and fair corrective action in +response to any behavior that they deem inappropriate, threatening, offensive, +or harmful. + +Community leaders have the right and responsibility to remove, edit, or reject +comments, commits, code, wiki edits, issues, and other contributions that are +not aligned to this Code of Conduct, and will communicate reasons for moderation +decisions when appropriate. + +## Scope + +This Code of Conduct applies within all community spaces, and also applies when +an individual is officially representing the community in public spaces. +Examples of representing our community include using an official e-mail address, +posting via an official social media account, or acting as an appointed +representative at an online or offline event. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported to the community leaders responsible for enforcement at +https://www.linkedin.com/in/iryna-kondrashchenko-673800155/. +All complaints will be reviewed and investigated promptly and fairly. + +All community leaders are obligated to respect the privacy and security of the +reporter of any incident. + +## Enforcement Guidelines + +Community leaders will follow these Community Impact Guidelines in determining +the consequences for any action they deem in violation of this Code of Conduct: + +### 1. Correction + +**Community Impact**: Use of inappropriate language or other behavior deemed +unprofessional or unwelcome in the community. + +**Consequence**: A private, written warning from community leaders, providing +clarity around the nature of the violation and an explanation of why the +behavior was inappropriate. A public apology may be requested. + +### 2. Warning + +**Community Impact**: A violation through a single incident or series +of actions. + +**Consequence**: A warning with consequences for continued behavior. No +interaction with the people involved, including unsolicited interaction with +those enforcing the Code of Conduct, for a specified period of time. This +includes avoiding interactions in community spaces as well as external channels +like social media. Violating these terms may lead to a temporary or +permanent ban. + +### 3. Temporary Ban + +**Community Impact**: A serious violation of community standards, including +sustained inappropriate behavior. + +**Consequence**: A temporary ban from any sort of interaction or public +communication with the community for a specified period of time. No public or +private interaction with the people involved, including unsolicited interaction +with those enforcing the Code of Conduct, is allowed during this period. +Violating these terms may lead to a permanent ban. + +### 4. Permanent Ban + +**Community Impact**: Demonstrating a pattern of violation of community +standards, including sustained inappropriate behavior, harassment of an +individual, or aggression toward or disparagement of classes of individuals. + +**Consequence**: A permanent ban from any sort of public interaction within +the community. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], +version 2.0, available at +https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. + +Community Impact Guidelines were inspired by [Mozilla's code of conduct +enforcement ladder](https://github.com/mozilla/diversity). + +[homepage]: https://www.contributor-covenant.org + +For answers to common questions about this code of conduct, see the FAQ at +https://www.contributor-covenant.org/faq. Translations are available at +https://www.contributor-covenant.org/translations. \ No newline at end of file diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..11cdf70 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,20 @@ +# Contributing to agent_dingo + +Welcome! We appreciate your interest in contributing to `agent_dingo`. Whether you're a developer, designer, writer, or simply passionate about open source, there are several ways you can help improve this project. This document will guide you through the process of contributing to our Python repository. + +## How Can I Contribute? + +There are several ways you can contribute to this project: + +- Bug Fixes: Help us identify and fix issues in the codebase. +- Feature Implementation: Implement new features and enhancements. +- Documentation: Improve the project's documentation, including code comments and README files. +- Testing: Write and improve test cases to ensure the project's quality and reliability. +- Translations: Provide translations for the project's documentation or user interface. +- Bug Reports and Feature Requests: Submit bug reports or suggest new features and improvements. + +**Important:** before contributing, we recommend that you open an issue to discuss your planned changes. This allows us to align our goals, provide guidance, and potentially find other contributors interested in collaborating on the same feature or bug fix. + +> ### Legal Notice +> +> When contributing to this project, you must agree that you have authored 100% of the content, that you have the necessary rights to the content and that the content you contribute may be provided under the project license. \ No newline at end of file diff --git a/README.md b/README.md index 766b2e0..962e1c5 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,248 @@ -# agent_dingo -A microframework for creating simple AI agents. +

+
+ AgentDingo +
+ Agent Dingo +
+

+ +

A microframework for buildling simple conversational AI agents.

+ +

+ + + + + + + + + + + + +

+ +_Dingo_ allows you to easily integrate any function into ChatGPT by adding a single line of code. With _Dingo_, you no longer have to worry about manually integrating the functions or dealing with intermediate function calls. The framework is crafted to automate these tasks, allowing you to focus on writing the core functionality. + +## Quick Start โšก๏ธ + +Step 1: Install `agent-dingo` + +```bash +pip install agent-dingo +``` + +Step 2: Configure your OpenAI API key + +```bash +export OPENAI_API_KEY= +``` + +Step 3: Instantiate the agent + +```python +from agent_dingo import AgentDingo + +agent = AgentDingo() +``` + +Step 4: Add `agent.function` decorator to the function you wish to integrate + +```python +@agent.function +def get_current_weather(city: str): + ... +``` + +Step 5: Run the conversation + +```python +agent.chat("What is the current weather in Linz?") +``` + +## Support us ๐Ÿค + +You can support the project in the following ways: + +โญ Star _Dingo_ on GitHub (click the star button in the top right corner) + +๐Ÿ’ก Provide your feedback or propose ideas in the issues section or Discord + +๐Ÿ“ฐ Post about _Dingo_ on LinkedIn or other platforms + +## Our Related Projects ๐Ÿ”— + +
+ + +## Documentation ๐Ÿ“š + +### OpenAI API Key + +_Dingo_ is built around function calling feature of newer generation OpenAI chat models that were explicitly fine-tuned for these tasks. +Hence, an OpenAI key is required. + +You can either set the `OPENAI_API_KEY` env variable or register the key using the `openai` python package. + +```bash +export OPENAI_API_KEY= +``` + +```python +import openai + +openai.api_key = "" +``` + +### Agent + +`AgentDingo` is a central part of the framework which allows you to register the functions to use with ChatGPT. The intermediate function calling is also handled by the agent directly. + +```python +from agent_dingo import AgentDingo + +agent = AgentDingo() +``` + +### Registering the functions + +**Option 1** (Recommended): Registering the function with a docstring + +By default, the agent uses the information from the docstring to generate a function descriptor that is passed to the model. It is advised to always use the functions with docstrings as this way you can describe the purpose of the function (and its arguments) more accurately. The library was explicitly tested with `google` and `numpy` docstring styles. + +Example: + +```python +@agent.function +def get_temperature(city: str) -> str: + """Retrieves the current temperature in a city. + + Parameters + ---------- + city : str + The city to get the temperature for. + + Returns + ------- + str + String representation of the json response from the weather api. + """ + base_url = "https://api.openweathermap.org/data/2.5/weather" + params = { + "q": city, + "appid": "", + "units": "metric" + } + response = requests.get(base_url, params=params) + data = response.json() + return str(data) +``` + +**Option 2**: Registering the function without a docstring + +If the function does not have a docstring, it can still be registered. In that case, the docstring will be generated automatically by ChatGPT. +However, there are several drawbacks of this approach: + +- The source code of your function is passed to the model; +- The generated docstring might be inaccurate (especially for complex functions); +- The generated docstrings are not persistant (i.e. they are not saved to disk) and will have to be re-generated every time the function is registered. + +If you wish to disable the automatic docstring generation, you can set the `allow_codegen` parameter to `False` when instantiating the agent. + +Example: + +```python +agent = AgentDingo(allow_codegen=False) +``` + +By default the `allow_codegen` parameter is set to `"env"` which means that the value is read from the `DINGO_ALLOW_CODEGEN` environment variable. If the variable is not set, it is assumed to be `True`. + +It is also possible to change the model used for the code generation by setting the `DINGO_CODEGEN_MODEL` environment variable. By default, the `gpt-3.5-turbo-0613` model is used. + +```bash +export DINGO_CODEGEN_MODEL="gpt-4-0613" +``` + +### Registering of external functions + +If you wish to register a function that is not defined in the current file, you can use the `register_function` method of the agent. + +```python +from my_module import get_temperature + +agent.register_function(get_temperature) +``` + +### Running the conversation + +Once the functions are registered, you can run the conversation using the `chat` method of the agent. + +```python +agent.chat("What is the current temperature in Linz?") +``` + +The chat method accepts the following parameters: + +- `messages` - the message to start the conversation with; it can either be a string or a list of messages (conversation history); +- `chat_context` - the global context of the conversation (more details are provided in the next section); by default, it is set to `None`; +- `model` - the model to use for the conversation; by default, the `gpt-3.5-turbo-0613` model is used; +- `temperature` - the randomness parameter of the model; by default, it is set to `1.0`; +- `max_function_calls` - the maximum number of function calls allowed during the conversation; by default, it is set to `10`; +- `before_function_call` - an interceptor that is called before the function is called (mode details are provided in the next section); by default, it is set to `None`. + +All of the parameters except `messages` are optional. + +The method returns a tuple which contains the last message of the conversation (as string) and the full conversation history (including function calls). + +### Chat context + +In some cases the function might require to access the global context of the conversation. For example, the function might need to access some user-specific information (e.g. user id). In this case, the `chat_context` parameter can be used. It is a special dictionary that is passed to the function and can contain any information that is required. Unlike other arguments, the content of the chat_context is not generated by the model and is passed directly to the function. + +```python +from agent_dingo.context import ChatContext + +@agent.function +def get_user_name(greeting_msg: str, chat_context: ChatContext) -> str: + """Returns a greeting message with the user's name. + + Parameters + ---------- + greeting_msg : str + Message to greet the user with. + chat_context : ChatContext + The chat context. + + Returns + ------- + str + The greeting message with the user's name. + """ + user_name = chat_context["user_name"] + return f"{greeting_msg}, {user_name}!" + +r = agent.chat( + "Say hi.", chat_context=ChatContext(user_name="John"), temperature=0.0 +) + +# > Hi, John! How can I assist you today? +``` + +Note: the `chat_context` parameter is not passed to the model and is not used for the generation of the function descriptor. + +### Before function call interceptor + +In some cases, it might be required to perform some actions before the function is called. For example, you might want to log the function call or perform some checks. This is especially handy since the function arguments generated by the model are not guaranteed to be correct/valid, hence, it is advised to add some additional validators. The `before_function_call` parameter can be used to register an interceptor that is called before the function. The interceptor receives the following parameters: `function_name`, `function_callable`, `function_kwargs` and should return a tuple with the updated `function_callable` and `function_kwargs`. + +Example: intercepting the function call and logging the function name and arguments. + +```python +def before_function_call(function_name: str, function_callable: Callable, function_kwargs: dict): + print(f"Calling function {function_name} with arguments {function_kwargs}") + return function_callable, function_kwargs + +agent.chat( + "What is the current temperature in Linz?", + before_function_call=before_function_call, +) +``` diff --git a/agent_dingo/__init__.py b/agent_dingo/__init__.py index e7716d6..722d62b 100644 --- a/agent_dingo/__init__.py +++ b/agent_dingo/__init__.py @@ -1 +1,4 @@ -from agent_dingo.agent import AgentDingo \ No newline at end of file +from agent_dingo.agent import AgentDingo + +__version__ = '0.1.0rc1' +__author__ = 'Oleh Kostromin, Iryna Kondrashchenko' \ No newline at end of file diff --git a/agent_dingo/chat.py b/agent_dingo/chat.py index 5071e43..62c6e60 100644 --- a/agent_dingo/chat.py +++ b/agent_dingo/chat.py @@ -33,5 +33,7 @@ def send_message( if functions is not None: f["functions"] = functions f["function_call"] = "auto" - response = openai.ChatCompletion.create(model=model, messages=messages, **f) + response = openai.ChatCompletion.create( + model=model, messages=messages, temperature=temperature, **f + ) return response["choices"][0]["message"] diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..cf609e1 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,25 @@ +[build-system] +requires = ["setuptools>=61.0"] +build-backend = "setuptools.build_meta" + +[project] +dependencies = [ + "openai>=0.27.0", + "docstring_parser>=0.15.0", + "tenacity>=8.2.0", +] +name = "agent_dingo" +version = "0.1.0rc1" +authors = [ + { name="Oleh Kostromin", email="kostromin97@gmail.com" }, + { name="Iryna Kondrashchenko", email="iryna230520@gmail.com" }, +] +description = "A microframework for creating simple AI agents." +readme = "README.md" +license = {text = "MIT"} +requires-python = ">=3.8" +classifiers = [ + "Programming Language :: Python :: 3", + "License :: OSI Approved :: MIT License", + "Operating System :: OS Independent", +] \ No newline at end of file