🐫 CAMEL: The first and the best multi-agent framework. Finding the Scaling Law of Agents. https://www.camel-ai.org
Python agentai-societiesartificial-intelligencecommunicative-aicooperative-aideep-learninglarge-language-modelsmulti-agent-systemsnatural-language-processing
Improve `TextPrompt` and add docs (#127)
Guohao Li347dd6655da8
diff --git a/.github/workflows/documentation.yaml b/.github/workflows/documentation.yamlindex 0ce035ec4..613bafbb3 100644--- a/.github/workflows/documentation.yaml+++ b/.github/workflows/documentation.yaml@@ -10,7 +10,7 @@ jobs:- uses: actions/setup-python@v3- name: Install dependenciesrun: |- pip install sphinx sphinx_book_theme numpy openai tenacity tiktoken colorama+ pip install sphinx sphinx_book_theme recommonmark numpy openai tenacity tiktoken colorama- name: Sphinx buildrun: |sphinx-build docs docs/_builddiff --git a/camel/prompts/base.py b/camel/prompts/base.pyindex 255b6f301..49a377f9f 100644--- a/camel/prompts/base.py+++ b/camel/prompts/base.py@@ -1,12 +1,78 @@-from typing import Any, Dict, Set+import inspect+from typing import Any, Callable, Dict, Set, TypeVar, Unionfrom camel.utils import get_prompt_template_key_words+T = TypeVar('T')++def return_text_prompt(+ func: Callable) -> Callable[..., Union['TextPrompt', tuple]]:+ r"""Decorator that converts the return value of a function to a+ :obj:`TextPrompt` instance if it's a string.++ Args:+ func (Callable): The function to decorate.++ Returns:+ Callable[..., Union[TextPrompt, tuple]]: Decorated function that+ returns a :obj:`TextPrompt` instance if the return value is a+ string.+ """++ def wrapper(*args: Any, **kwargs: Any) -> Union['TextPrompt', tuple]:+ r"""Wrapper function that performs the conversion to :obj:`TextPrompt`+ instance.++ Args:+ *args (Any): Variable length argument list.+ **kwargs (Any): Arbitrary keyword arguments.++ Returns:+ Union[TextPrompt, tuple]: The converted return value.+ """+ result = func(*args, **kwargs)+ if isinstance(result, str) and not isinstance(result, TextPrompt):+ return TextPrompt(result)+ elif isinstance(result, tuple):+ new_result = tuple(+ TextPrompt(item) if isinstance(item, str)+ and not isinstance(item, TextPrompt) else item+ for item in result)+ return new_result+ return result++ # # Preserve the original function's attributes+ wrapper.__name__ = func.__name__+ wrapper.__doc__ = func.__doc__++ return wrapper+++def wrap_text_prompt_functions(cls: T) -> T:+ r"""Decorator that wraps functions of a class inherited from :obj:`str`+ with the :obj:`return_text_prompt` decorator.++ Args:+ cls (type): The class to decorate.++ Returns:+ type: Decorated class with wrapped functions.+ """+ excluded_attrs = {'__init__', '__new__', '__str__', '__repr__'}+ for attr_name in dir(cls):+ attr_value = getattr(cls, attr_name)+ if callable(attr_value) and attr_name not in excluded_attrs:+ if inspect.isroutine(attr_value):+ setattr(cls, attr_name, return_text_prompt(attr_value))+ return cls+++@wrap_text_prompt_functionsclass TextPrompt(str):- r"""A class that represents a text prompt. The TextPrompt class extends- the built-in str class to provide a property for retrieving the set of- key words in the prompt.+ r"""A class that represents a text prompt. The :obj:`TextPrompt` class+ extends the built-in :obj:`str` class to provide a property for retrieving+ the set of key words in the prompt.Attributes:key_words (set): A set of strings representing the key words in the@@ -29,8 +95,8 @@ class TextPrompt(str):**kwargs (Any): Arbitrary keyword arguments.Returns:- TextPrompt: A new TextPrompt object with the format string replaced- with the formatted string.+ TextPrompt: A new :obj:`TextPrompt` object with the format string+ replaced with the formatted string."""default_kwargs = {key: '{' + f'{key}' + '}' for key in self.key_words}default_kwargs.update(kwargs)diff --git a/docs/README.md b/docs/README.mdindex 2cf7c270f..2b781d12d 100644--- a/docs/README.md+++ b/docs/README.md@@ -6,3 +6,38 @@ sphinx-apidoc -o docs camel/```Helpful article [here](https://towardsdatascience.com/documenting-python-code-with-sphinx-554e1d6c4f6d).++# Building Documentation++To build the documentation:++1. [Install CAMEL](https://github.com/camel-ai/camel/blob/master/README.md) from source.++2. Install Sphinx, Sphinx theme and `recommonmark` (Sphinx extension that enables Markdown support) by running the following command in your terminal or command prompt:+```bash+pip install sphinx+pip install sphinx_book_theme+pip install recommonmark+```++3. Navigate to the `docs` directory, and run the `make` command:+```bash+cd docs+make html+```++4. Launch the HTML documentation from the terminal using a local HTTP server+```bash+cd _build+python -m http.server+```+This command starts a local HTTP server on port 8000 by default. Once the server is running, open your web browser and enter the following URL:+```bash+http://localhost:8000/html+```+This will load the HTML documentation in your web browser from the local server.++You can navigate through the documentation using the links and interact with it as you would with any other web page.++To stop the local server, go back to the terminal or command prompt where it is running and press `Ctrl+C` to terminate the server.+diff --git a/docs/camel.rst b/docs/camel.rstindex 72818d446..e1c507e83 100644--- a/docs/camel.rst+++ b/docs/camel.rst@@ -1,4 +1,4 @@-camel package+Camel Package=============Subpackagesdiff --git a/docs/conf.py b/docs/conf.pyindex dac50c5f2..0efe7b0d3 100644--- a/docs/conf.py+++ b/docs/conf.py@@ -11,17 +11,25 @@ import syssys.path.insert(0, os.path.abspath('..'))-project = 'Camel'-copyright = '2023, Camel AI team'-author = ('Guohao Li, Hasan Abed Al Kader Hammoud, Hani Itani, '- 'Dmitrii Khizbullin, Bernard Ghanem')+project = 'CAMEL'+copyright = '2023, CAMEL-AI.org'+author = 'CAMEL-AI.org'release = '0.1.0'+# -- General configuration ---------------------------------------------------# https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration+source_suffix = {+ '.rst': 'restructuredtext',+ '.md': 'markdown',+}+extensions = [- 'sphinx.ext.autodoc', 'sphinx.ext.viewcode', 'sphinx.ext.napoleon'+ 'sphinx.ext.autodoc',+ 'sphinx.ext.viewcode',+ 'sphinx.ext.napoleon',+ 'recommonmark',]templates_path = ['_templates']@@ -31,4 +39,3 @@ exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']# https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-outputhtml_theme = 'sphinx_book_theme'-html_static_path = ['_static']diff --git a/docs/get_started/prompts.md b/docs/get_started/prompts.mdnew file mode 100644index 000000000..0a1fa7978--- /dev/null+++ b/docs/get_started/prompts.md@@ -0,0 +1,112 @@+# Write Your Prompts with the `TextPrompt` Class++In this tutorial, we will explore the `TextPrompt` class and understand its functionalities. The `TextPrompt` class is a subclass of the built-in `str` class and provides additional features for working with text prompts. We will cover the following topics:++- Introduction to the `TextPrompt` class+- Using the `TextPrompt` class++## Introduction to the `TextPrompt` class++The `TextPrompt` class represents a text prompt and extends the functionality of the `str` class. It provides a property called `key_words`, which returns a set of strings representing the key words in the prompt.++Here's an example of how to use the `TextPrompt` class:++```python+from camel.prompts import TextPrompt++prompt = TextPrompt('Please enter your name and age: {name}, {age}')+print(prompt)+>>> 'Please enter your name and age: {name}, {age}'+```++In the above example, we create a `TextPrompt` instance with a format string containing key words for name and age. We can print `TextPrompt` like Python `str`.++## Using the `TextPrompt` class++Once we have created a `TextPrompt` instance, we can use various methods and properties provided by the class to manipulate and work with the text prompt.++### The `key_words` property++The `key_words` property returns a set of strings representing the key words in the prompt.++```python+from camel.prompts import TextPrompt++prompt = TextPrompt('Please enter your name and age: {name}, {age}')+print(prompt.key_words)+>>> {'name', 'age'}+```++In the above example, the `key_words` property returns a set of strings representing the key words in the prompt, which in this case are 'name' and 'age'.++### The `format` method++The `format` method overrides the built-in `str.format` method to allow for partial formatting values in the format string. It replaces the key words in the format string with the provided values.++```python+from camel.prompts import TextPrompt++prompt = TextPrompt('Your name and age are: {name}, {age}')++name, age = 'John', 30+formatted_prompt = prompt.format(name=name, age=age)+print(formatted_prompt)+>>> "Your name and age are: John, 30"+```++In the above example, we use the `format` method to replace the key words `{name}` and `{age}` with the values 'John' and 30, respectively.++We can also perform partial formatting by providing only some of the values:++```python+from camel.prompts import TextPrompt++prompt = TextPrompt('Your name and age are: {name}, {age}')++name = 'John'+partial_formatted_prompt = prompt.format(name=name)+print(partial_formatted_prompt)+>>> "Your name and age are: John, {age}"+```++In the above example, we provide only the value for the `name` key word, while the `age` key word remains as it is. This will be helpful when we want to format different key words of `TextPrompt` in different agents.++### Manipulating `TextPrompt` instances++We can perform various string manipulation operations on `TextPrompt` instances, such as concatenation, joining, and applying string methods like Python `str`.++```python+from camel.prompts import TextPrompt++prompt1 = TextPrompt('Hello, {name}!')+prompt2 = TextPrompt('Welcome, {name}!')++# Concatenation+prompt3 = prompt1 + ' ' + prompt2+print(prompt3)+print(isinstance(prompt3, TextPrompt))+print(prompt3.key_words)+>>> "Hello, {name}! Welcome, {name}!"+>>> True+>>> {'name'}++# Joining+prompt4 = TextPrompt(' ').join([prompt1, prompt2])+print(prompt4)+print(isinstance(prompt4, TextPrompt))+print(prompt4.key_words)+>>> "Hello, {name}! Welcome, {name}!"+>>> True+>>> {'name'}++# Applying string methods+prompt5 = prompt4.upper()+print(prompt5)+print(isinstance(prompt5, TextPrompt))+print(prompt5.key_words)+>>> "HELLO, {NAME}! WELCOME, {NAME}!"+>>> True+>>> {'NAME'}+```++In the above example, we demonstrate concatenation using the `+` operator, joining using the `join` method, and applying the `upper` method to a `TextPrompt` instance. The resulting prompts are also instances of `TextPrompt`.\ No newline at end of filediff --git a/docs/index.rst b/docs/index.rstindex 6c0a5bcfa..036c93c21 100644--- a/docs/index.rst+++ b/docs/index.rst@@ -1,14 +1,26 @@-.. Camel documentation master file, created by+.. CAMEL documentation master file, created bysphinx-quickstart on Sun May 14 13:51:36 2023.You can adapt this file completely to your liking, but it should at leastcontain the root `toctree` directive.-Welcome to Camel's documentation!+Welcome to CAMEL's documentation!=================================+| **CAMEL** is an open-source library designed for the study of autonomous and communicative agents.+ We believe that studying these agents on a large scale offers valuable insights into their behaviors, capabilities, and potential risks.+ To facilitate research in this field, we implement and support various types of agents, tasks, prompts, models, and simulated environments.+ Join us (`slack <https://join.slack.com/t/camel-kwr1314/shared_invite/zt-1vy8u9lbo-ZQmhIAyWSEfSwLCl2r2eKA>`_) in pushing the boundaries of simulating *AI Society* with **CAMEL**.++.. toctree::+ :maxdepth: 1+ :caption: Get Started:+ :name: getting_started++ get_started/prompts.md+.. toctree::- :maxdepth: 2- :caption: Contents:+ :maxdepth: 1+ :caption: Modules:modulesdiff --git a/test/prompts/test_base.py b/test/prompts/test_base.pyindex 58172bdcb..b5bfbf6d6 100644--- a/test/prompts/test_base.py+++ b/test/prompts/test_base.py@@ -1,11 +1,69 @@-from camel.prompts import TextPrompt, TextPromptDict+from camel.prompts.base import (+ TextPrompt,+ TextPromptDict,+ return_text_prompt,+ wrap_text_prompt_functions,+)+++def test_return_text_prompt_decorator():++ @return_text_prompt+ def my_function():+ return "Hello, world!"++ result = my_function()+ assert isinstance(result, TextPrompt)+ assert str(result) == "Hello, world!"+++def test_return_text_prompt_decorator_with_tuple():++ @return_text_prompt+ def my_function():+ return ("Hello, {name}!", "Welcome, {name}!")++ result = my_function()+ assert isinstance(result, tuple)+ assert all(isinstance(item, TextPrompt) for item in result)+ assert str(result[0]) == "Hello, {name}!"+ assert str(result[1]) == "Welcome, {name}!"+++def test_wrap_text_prompt_functions():+ # Example class for testing+ class MyClass:++ def __init__(self):+ pass++ def my_function(self):+ return "Hello, World!"++ def my_other_function(self):+ return "Goodbye, World!"++ # Decorate the class with the wrapper function+ @wrap_text_prompt_functions+ class MyDecoratedClass(MyClass):+ pass++ # Create an instance of the decorated class+ obj = MyDecoratedClass()++ # Check if the functions are wrapped correctly+ assert isinstance(obj.my_function(), TextPrompt)+ assert isinstance(obj.my_other_function(), TextPrompt)def test_text_prompt_key_words():prompt = TextPrompt('Please enter your name and age: {name}, {age}')assert prompt.key_words == {'name', 'age'}- prompt = TextPrompt('Please enter your email address')+ prompt = prompt.format(name='John')+ assert prompt.key_words == {'age'}++ prompt = prompt.format(age=30)assert prompt.key_words == set()@@ -16,9 +74,30 @@ def test_text_prompt_format():assert prompt.format(name=name,age=age) == 'Your name and age are: John, 30'+ # Partial formattingassert prompt.format(name=name) == 'Your name and age are: John, {age}'+def test_text_prompt_manipulate():+ prompt1 = TextPrompt('Hello, {name}!')+ prompt2 = TextPrompt('Welcome, {name}!')++ prompt3 = prompt1 + ' ' + prompt2+ assert prompt3 == 'Hello, {name}! Welcome, {name}!'+ assert isinstance(prompt3, TextPrompt)+ assert prompt3.key_words == {'name'}++ prompt4 = TextPrompt(' ').join([prompt1, prompt2])+ assert prompt4 == 'Hello, {name}! Welcome, {name}!'+ assert isinstance(prompt4, TextPrompt)+ assert prompt4.key_words == {'name'}++ prompt5 = prompt4.upper()+ assert prompt5 == 'HELLO, {NAME}! WELCOME, {NAME}!'+ assert isinstance(prompt5, TextPrompt)+ assert prompt5.key_words == {'NAME'}++def test_text_prompt_dict():prompt_dict = TextPromptDict()prompt_dict['test'] = TextPrompt('test')