Skip to content

armgit / camel

Public Imported from GitHub
0

🐫 CAMEL: The first and the best multi-agent framework. Finding the Scaling Law of Agents. https://www.camel-ai.org

chore: Ruff check add characters line constrain (#604)

Wendong-Fand3466dd0fefb
diff --git a/apps/agents/agents.py b/apps/agents/agents.py
index 2c9b39448..07ced6d18 100644
--- a/apps/agents/agents.py
+++ b/apps/agents/agents.py
@@ -338,7 +338,10 @@ def role_playing_chat_cont(state) -> Tuple[State, ChatBotHistory, Dict, Dict]:
if len(state.chat) >= state.max_messages:
state.session = None
- if "CAMEL_TASK_DONE" in a_msg.content or "CAMEL_TASK_DONE" in u_msg.content:
+ if (
+ "CAMEL_TASK_DONE" in a_msg.content
+ or "CAMEL_TASK_DONE" in u_msg.content
+ ):
state.session = None
progress_update = gr.update(
@@ -458,8 +461,9 @@ def construct_ui(blocks, api_key: Optional[str] = None) -> None:
"Github repo: [https://github.com/lightaime/camel]"
"(https://github.com/lightaime/camel)"
'<div style="display:flex; justify-content:center;">'
- '<img src="https://raw.githubusercontent.com/camel-ai/camel/master/misc/primary_logo.png" alt="Logo" style="max-width:50%;">'
- '</div>'
+ '<img src="https://raw.githubusercontent.com/camel-ai/camel/'
+ 'master/misc/primary_logo.png" alt="Logo" style='
+ '"max-width:50%;"> </div>'
)
with gr.Row():
with gr.Column(scale=9):
@@ -495,7 +499,10 @@ def construct_ui(blocks, api_key: Optional[str] = None) -> None:
)
with gr.Row():
language_ta = gr.TextArea(
- label="Language", value="English", lines=1, interactive=True
+ label="Language",
+ value="English",
+ lines=1,
+ interactive=True,
)
with gr.Column(scale=2):
with gr.Row():
diff --git a/apps/data_explorer/data_explorer.py b/apps/data_explorer/data_explorer.py
index 4dd0ab733..a274c9dc3 100644
--- a/apps/data_explorer/data_explorer.py
+++ b/apps/data_explorer/data_explorer.py
@@ -149,11 +149,15 @@ def construct_ui(
"Github repo: [https://github.com/lightaime/camel]"
"(https://github.com/lightaime/camel)\n"
'<div style="display:flex; justify-content:center;">'
- '<img src="https://raw.githubusercontent.com/camel-ai/camel/master/misc/primary_logo.png" alt="Logo" style="max-width:50%;">'
+ '<img src="https://raw.githubusercontent.com/camel-ai/camel/'
+ 'master/misc/primary_logo.png" alt="Logo" style='
+ '"max-width:50%;">'
'</div>'
)
- task_dd = gr.Dropdown([], label="Original task", value="", interactive=True)
+ task_dd = gr.Dropdown(
+ [], label="Original task", value="", interactive=True
+ )
specified_task_ta = gr.TextArea(label="Specified task", lines=2)
chatbot = gr.Chatbot()
accepted_st = gr.State(False)
@@ -271,7 +275,9 @@ def construct_ui(
original_task_options = []
choices = gr.Dropdown.update(
- choices=original_task_options, value=original_task, interactive=True
+ choices=original_task_options,
+ value=original_task,
+ interactive=True,
)
return choices
diff --git a/apps/dilemma/dilemma.py b/apps/dilemma/dilemma.py
index 0ffd2d972..08aeda5e8 100644
--- a/apps/dilemma/dilemma.py
+++ b/apps/dilemma/dilemma.py
@@ -171,7 +171,9 @@ def construct_ui(
else:
who_is_better = state[choice]['who']
name = state['name']
- print("choice=", choice, "who_is_better=", who_is_better, "name=", name)
+ print(
+ "choice=", choice, "who_is_better=", who_is_better, "name=", name
+ )
if db_conn is not None:
db_conn.add_record(name, who_is_better)
diff --git a/camel/agents/deductive_reasoner_agent.py b/camel/agents/deductive_reasoner_agent.py
index 374968596..97d1d3d07 100644
--- a/camel/agents/deductive_reasoner_agent.py
+++ b/camel/agents/deductive_reasoner_agent.py
@@ -90,52 +90,106 @@ class DeductiveReasonerAgent(ChatAgent):
"""
self.reset()
- deduce_prompt = """You are a deductive reasoner. You are tasked to complete the TASK based on the THOUGHT OF DEDUCTIVE REASONING, the STARTING STATE A and the TARGET STATE B. You are given the CONTEXT CONTENT to help you complete the TASK.
-Your answer MUST strictly adhere to the structure of ANSWER TEMPLATE, ONLY fill in the BLANKs, and DO NOT alter or modify any other part of the template
+ deduce_prompt = """You are a deductive reasoner. You are tasked to
+ complete the TASK based on the THOUGHT OF DEDUCTIVE REASONING, the
+ STARTING STATE A and the TARGET STATE B. You are given the CONTEXT
+ CONTENT to help you complete the TASK.
+Your answer MUST strictly adhere to the structure of ANSWER TEMPLATE, ONLY
+fill in the BLANKs, and DO NOT alter or modify any other part of the template
===== MODELING OF DEDUCTIVE REASONING =====
-You are tasked with understanding a mathematical model based on the components ${A, B, C, Q, L}$. In this model: ``L: A ⊕ C -> q * B``.
+You are tasked with understanding a mathematical model based on the components
+${A, B, C, Q, L}$. In this model: ``L: A ⊕ C -> q * B``.
- $A$ represents the known starting state.
- $B$ represents the known target state.
- $C$ represents the conditions required to transition from $A$ to $B$.
-- $Q$ represents the quality or effectiveness of the transition from $A$ to $B$.
+- $Q$ represents the quality or effectiveness of the transition from $A$ to
+$B$.
- $L$ represents the path or process from $A$ to $B$.
===== THOUGHT OF DEDUCTIVE REASONING =====
1. Define the Parameters of A and B:
- - Characterization: Before delving into transitions, thoroughly understand the nature and boundaries of both $A$ and $B$. This includes the type, properties, constraints, and possible interactions between the two.
- - Contrast and Compare: Highlight the similarities and differences between $A$ and $B$. This comparative analysis will give an insight into what needs changing and what remains constant.
+ - Characterization: Before delving into transitions, thoroughly understand
+ the nature and boundaries of both $A$ and $B$. This includes the type,
+ properties, constraints, and possible interactions between the two.
+ - Contrast and Compare: Highlight the similarities and differences between
+ $A$ and $B$. This comparative analysis will give an insight into what
+ needs changing and what remains constant.
2. Historical & Empirical Analysis:
- - Previous Transitions according to the Knowledge Base of GPT: (if applicable) Extract conditions and patterns from the historical instances where a similar transition from a state comparable to $A$ moved towards $B$.
- - Scientific Principles: (if applicable) Consider the underlying scientific principles governing or related to the states and their transition. For example, if $A$ and $B$ are physical states, laws of physics might apply.
+ - Previous Transitions according to the Knowledge Base of GPT: (if
+ applicable) Extract conditions and patterns from the historical instances
+ where a similar transition from a state comparable to $A$ moved towards
+ $B$.
+ - Scientific Principles: (if applicable) Consider the underlying
+ scientific principles governing or related to the states and their
+ transition. For example, if $A$ and $B$ are physical states, laws of
+ physics might apply.
3. Logical Deduction of Conditions ($C$):
- - Direct Path Analysis: What are the immediate and direct conditions required to move from $A$ to $B$?
- - Intermediate States: Are there states between $A$ and $B$ that must be transversed or can be used to make the transition smoother or more efficient? If yes, what is the content?
- - Constraints & Limitations: Identify potential barriers or restrictions in moving from $A$ to $B$. These can be external (e.g., environmental factors) or internal (properties of $A$ or $B$).
- - Resource and Information Analysis: What resources and information are required for the transition? This could be time, entity, factor, code language, software platform, unknowns, etc.
- - External Influences: Consider socio-economic, political, or environmental factors (if applicable) that could influence the transition conditions.
- - Creative/Heuristic Reasoning: Open your mind to multiple possible $C$'s, no matter how unconventional they might seem. Utilize analogies, metaphors, or brainstorming techniques to envision possible conditions or paths from $A$ to $B$.
- - The conditions $C$ should be multiple but in one sentence. And each condition should be concerned with one aspect/entity.
+ - Direct Path Analysis: What are the immediate and direct conditions
+ required to move from $A$ to $B$?
+ - Intermediate States: Are there states between $A$ and $B$ that must be
+ transversed or can be used to make the transition smoother or more
+ efficient? If yes, what is the content?
+ - Constraints & Limitations: Identify potential barriers or restrictions
+ in moving from $A$ to $B$. These can be external (e.g., environmental
+ factors) or internal (properties of $A$ or $B$).
+ - Resource and Information Analysis: What resources and information are
+ required for the transition? This could be time, entity, factor, code
+ language, software platform, unknowns, etc.
+ - External Influences: Consider socio-economic, political, or
+ environmental factors (if applicable) that could influence the transition
+ conditions.
+ - Creative/Heuristic Reasoning: Open your mind to multiple possible $C$'s,
+ no matter how unconventional they might seem. Utilize analogies,
+ metaphors, or brainstorming techniques to envision possible conditions or
+ paths from $A$ to $B$.
+ - The conditions $C$ should be multiple but in one sentence. And each
+ condition should be concerned with one aspect/entity.
4. Entity/Label Recognition of Conditions ($C$):
- - Identify and categorize entities of Conditions ($C$) such as the names, locations, dates, specific technical terms or contextual parameters that might be associated with events, innovations post-2022.
- - The output of the entities/labels will be used as tags or labels for semantic similarity searches. The entities/labels may be the words, or phrases, each of them should contain valuable, high information entropy information, and should be independent.
- - Ensure that the identified entities are formatted in a manner suitable for database indexing and retrieval. Organize the entities into categories, and combine the category with its instance into a continuous phrase, without using colons or other separators.
- - Format these entities for database indexing: output the category rather than its instance/content into a continuous phrase. For example, instead of "Jan. 02", identify it as "Event time".
+ - Identify and categorize entities of Conditions ($C$) such as the names,
+ locations, dates, specific technical terms or contextual parameters that
+ might be associated with events, innovations post-2022.
+ - The output of the entities/labels will be used as tags or labels for
+ semantic similarity searches. The entities/labels may be the words, or
+ phrases, each of them should contain valuable, high information entropy
+ information, and should be independent.
+ - Ensure that the identified entities are formatted in a manner suitable
+ for database indexing and retrieval. Organize the entities into
+ categories, and combine the category with its instance into a continuous
+ phrase, without using colons or other separators.
+ - Format these entities for database indexing: output the category rather
+ than its instance/content into a continuous phrase. For example, instead
+ of "Jan. 02", identify it as "Event time".
5. Quality Assessment ($Q$):
- - Efficiency: How efficient is the transition from $A$ to $B$, which measures the resources used versus the desired outcome?
- - Effectiveness: Did the transition achieve the desired outcome or was the target state achieved as intended?
- - Safety & Risks: Assess any risks associated with the transition and the measures to mitigate them.
- - Feedback Mechanisms: Incorporate feedback loops to continuously monitor and adjust the quality of transition, making it more adaptive.
+ - Efficiency: How efficient is the transition from $A$ to $B$, which
+ measures the resources used versus the desired outcome?
+ - Effectiveness: Did the transition achieve the desired outcome or was the
+ target state achieved as intended?
+ - Safety & Risks: Assess any risks associated with the transition and the
+ measures to mitigate them.
+ - Feedback Mechanisms: Incorporate feedback loops to continuously monitor
+ and adjust the quality of transition, making it more adaptive.
6. Iterative Evaluation:
- - Test & Refine: Based on the initially deduced conditions and assessed quality, iterate the process to refine and optimize the transition. This might involve tweaking conditions, employing different paths, or changing resources.
- - Feedback Integration: Use feedback to make improvements and increase the quality of the transition.
-7. Real-world scenarios often present challenges that may not be captured by models and frameworks. While using the model, maintain an adaptive mindset:
- - Scenario Exploration: Continuously imagine various possible scenarios, both positive and negative, to prepare for unexpected events.
- - Flexibility: Be prepared to modify conditions ($C$) or alter the path/process ($L$) if unforeseen challenges arise.
- - Feedback Integration: Rapidly integrate feedback from actual implementations to adjust the model's application, ensuring relevancy and effectiveness.
+ - Test & Refine: Based on the initially deduced conditions and assessed
+ quality, iterate the process to refine and optimize the transition. This
+ might involve tweaking conditions, employing different paths, or changing
+ resources.
+ - Feedback Integration: Use feedback to make improvements and increase the
+ quality of the transition.
+7. Real-world scenarios often present challenges that may not be captured by
+models and frameworks. While using the model, maintain an adaptive mindset:
+ - Scenario Exploration: Continuously imagine various possible scenarios,
+ both positive and negative, to prepare for unexpected events.
+ - Flexibility: Be prepared to modify conditions ($C$) or alter the path/
+ process ($L$) if unforeseen challenges arise.
+ - Feedback Integration: Rapidly integrate feedback from actual
+ implementations to adjust the model's application, ensuring relevancy and
+ effectiveness.
===== TASK =====
-Given the starting state $A$ and the target state $B$, assuming that a path $L$ always exists between $A$ and $B$, how can one deduce or identify the necessary conditions $C$ and the quality $Q$ of the transition?
+Given the starting state $A$ and the target state $B$, assuming that a path
+$L$ always exists between $A$ and $B$, how can one deduce or identify the
+necessary conditions $C$ and the quality $Q$ of the transition?
===== STARTING STATE $A$ =====
{starting_state}
@@ -150,7 +204,8 @@ Given the starting state $A$ and the target state $B$, assuming that a path $L$
- Logical Deduction of Conditions ($C$) (multiple conditions can be deduced):
condition <NUM>:
<BLANK>.
-- Entity/Label Recognition of Conditions:\n[<BLANK>, <BLANK>, ...] (include square brackets)
+- Entity/Label Recognition of Conditions:\n[<BLANK>, <BLANK>, ...] (include
+square brackets)
- Quality Assessment ($Q$) (do not use symbols):
<BLANK>.
- Iterative Evaluation:\n<BLANK>/None"""
diff --git a/camel/agents/knowledge_graph_agent.py b/camel/agents/knowledge_graph_agent.py
index f6222a3e9..fd4c74339 100644
--- a/camel/agents/knowledge_graph_agent.py
+++ b/camel/agents/knowledge_graph_agent.py
@@ -26,37 +26,49 @@ from camel.storages.graph_storages.graph_element import (
from camel.types import ModelType, RoleType
text_prompt = """
-You are tasked with extracting nodes and relationships from given content and structures them into Node and Relationship objects. Here's the outline of what you needs to do:
+You are tasked with extracting nodes and relationships from given content and
+structures them into Node and Relationship objects. Here's the outline of what
+you needs to do:
Content Extraction:
-You should be able to process input content and identify entities mentioned within it.
-Entities can be any noun phrases or concepts that represent distinct entities in the context of the given content.
+You should be able to process input content and identify entities mentioned
+within it.
+Entities can be any noun phrases or concepts that represent distinct entities
+in the context of the given content.
Node Extraction:
For each identified entity, you should create a Node object.
Each Node object should have a unique identifier (id) and a type (type).
-Additional properties associated with the node can also be extracted and stored.
+Additional properties associated with the node can also be extracted and
+stored.
Relationship Extraction:
You should identify relationships between entities mentioned in the content.
For each relationship, create a Relationship object.
-A Relationship object should have a subject (subj) and an object (obj) which are Node objects representing the entities involved in the relationship.
-Each relationship should also have a type (type), and additional properties if applicable.
+A Relationship object should have a subject (subj) and an object (obj) which
+are Node objects representing the entities involved in the relationship.
+Each relationship should also have a type (type), and additional properties if
+applicable.
Output Formatting:
-The extracted nodes and relationships should be formatted as instances of the provided Node and Relationship classes.
+The extracted nodes and relationships should be formatted as instances of the
+provided Node and Relationship classes.
Ensure that the extracted data adheres to the structure defined by the classes.
-Output the structured data in a format that can be easily validated against the provided code.
+Output the structured data in a format that can be easily validated against
+the provided code.
Instructions for you:
Read the provided content thoroughly.
-Identify distinct entities mentioned in the content and categorize them as nodes.
-Determine relationships between these entities and represent them as directed relationships.
+Identify distinct entities mentioned in the content and categorize them as
+nodes.
+Determine relationships between these entities and represent them as directed
+relationships.
Provide the extracted nodes and relationships in the specified format below.
Example for you:
Example Content:
-"John works at XYZ Corporation. He is a software engineer. The company is located in New York City."
+"John works at XYZ Corporation. He is a software engineer. The company is
+located in New York City."
Expected Output:
@@ -68,18 +80,23 @@ Node(id='New York City', type='Location', properties={'agent_generated'})
Relationships:
-Relationship(subj=Node(id='John', type='Person'), obj=Node(id='XYZ Corporation', type='Organization'), type='WorksAt', properties={'agent_generated'})
-Relationship(subj=Node(id='John', type='Person'), obj=Node(id='New York City', type='Location'), type='ResidesIn', properties={'agent_generated'})
+Relationship(subj=Node(id='John', type='Person'), obj=Node(id='XYZ
+Corporation', type='Organization'), type='WorksAt', properties=
+{'agent_generated'})
+Relationship(subj=Node(id='John', type='Person'), obj=Node(id='New York City',
+type='Location'), type='ResidesIn', properties={'agent_generated'})
===== TASK =====
-Please extracts nodes and relationships from given content and structures them into Node and Relationship objects.
+Please extracts nodes and relationships from given content and structures them
+into Node and Relationship objects.
{task}
"""
class KnowledgeGraphAgent(ChatAgent):
- r"""An agent that can extract node and relationship information for different entities from given `Element` content.
+ r"""An agent that can extract node and relationship information for
+ different entities from given `Element` content.
Attributes:
task_prompt (TextPrompt): A prompt for the agent to extract node and
@@ -106,7 +123,8 @@ class KnowledgeGraphAgent(ChatAgent):
content="Your mission is to transform unstructured content "
"intostructured graph data. Extract nodes and relationships with "
"precision, and let the connections unfold. Your graphs will "
- "illuminate the hidden connections within the chaos of information.",
+ "illuminate the hidden connections within the chaos of "
+ "information.",
)
super().__init__(system_message, model_type, model_config)
@@ -124,7 +142,8 @@ class KnowledgeGraphAgent(ChatAgent):
Returns:
Union[str, GraphElement]: The extracted node and relationship
- information. If `parse_graph_elements` is `True` then return `GraphElement`, else return `str`.
+ information. If `parse_graph_elements` is `True` then return
+ `GraphElement`, else return `str`.
"""
self.reset()
self.element = element
@@ -191,7 +210,11 @@ class KnowledgeGraphAgent(ChatAgent):
# Regular expressions to extract nodes and relationships
node_pattern = r"Node\(id='(.*?)', type='(.*?)', properties=(.*?)\)"
- rel_pattern = r"Relationship\(subj=Node\(id='(.*?)', type='(.*?)'\), obj=Node\(id='(.*?)', type='(.*?)'\), type='(.*?)', properties=\{(.*?)\}\)"
+ rel_pattern = (
+ r"Relationship\(subj=Node\(id='(.*?)', type='(.*?)'\), "
+ r"obj=Node\(id='(.*?)', type='(.*?)'\), type='(.*?)', "
+ r"properties=\{(.*?)\}\)"
+ )
nodes = {}
relationships = []
diff --git a/camel/agents/role_assignment_agent.py b/camel/agents/role_assignment_agent.py
index 2b548e1c4..4b3a79fec 100644
--- a/camel/agents/role_assignment_agent.py
+++ b/camel/agents/role_assignment_agent.py
@@ -115,7 +115,9 @@ class RoleAssignmentAgent(ChatAgent):
]
if len(role_names) != num_roles or len(role_descriptions) != num_roles:
- raise RuntimeError("Got None or insufficient information of roles.")
+ raise RuntimeError(
+ "Got None or insufficient information of roles."
+ )
if terminated:
raise RuntimeError("Role assignment failed.")
diff --git a/camel/embeddings/vlm_embedding.py b/camel/embeddings/vlm_embedding.py
index 4bc391ffa..f41b1dd55 100644
--- a/camel/embeddings/vlm_embedding.py
+++ b/camel/embeddings/vlm_embedding.py
@@ -73,7 +73,8 @@ class VisionLanguageEmbedding(BaseEmbedding[Union[str, Image.Image]]):
objs (List[Image.Image|str]): The list of images or texts for
which to generate the embeddings.
image_processor_kwargs: Extra kwargs passed to the image processor.
- tokenizer_kwargs: Extra kwargs passed to the text tokenizer(processor).
+ tokenizer_kwargs: Extra kwargs passed to the text tokenizer
+ (processor).
model_kwargs: Extra kwargs passed to the main model.
Returns:
@@ -102,7 +103,9 @@ class VisionLanguageEmbedding(BaseEmbedding[Union[str, Image.Image]]):
**image_processor_kwargs,
)
image_feature = (
- self.model.get_image_features(**image_input, **model_kwargs)
+ self.model.get_image_features(
+ **image_input, **model_kwargs
+ )
.squeeze(dim=0)
.tolist()
)
diff --git a/camel/functions/openai_function.py b/camel/functions/openai_function.py
index e5ee3a01c..ec810a23d 100644
--- a/camel/functions/openai_function.py
+++ b/camel/functions/openai_function.py
@@ -173,7 +173,9 @@ class OpenAIFunction:
)
@staticmethod
- def validate_openai_tool_schema(openai_tool_schema: Dict[str, Any]) -> None:
+ def validate_openai_tool_schema(
+ openai_tool_schema: Dict[str, Any],
+ ) -> None:
r"""Validates the OpenAI tool schema against
:obj:`ToolAssistantToolsFunction`.
This function checks if the provided :obj:`openai_tool_schema` adheres
diff --git a/camel/functions/search_functions.py b/camel/functions/search_functions.py
index 6b45c165b..cf1cd3d57 100644
--- a/camel/functions/search_functions.py
+++ b/camel/functions/search_functions.py
@@ -332,7 +332,8 @@ def query_wolfram_alpha(query: str, is_detailed: bool) -> str:
import wolframalpha
except ImportError:
raise ImportError(
- "Please install `wolframalpha` first. You can install it by running `pip install wolframalpha`."
+ "Please install `wolframalpha` first. You can install it by"
+ " running `pip install wolframalpha`."
)
WOLFRAMALPHA_APP_ID = os.environ.get('WOLFRAMALPHA_APP_ID')
diff --git a/camel/functions/slack_functions.py b/camel/functions/slack_functions.py
index 49a54b2c5..114cc3057 100644
--- a/camel/functions/slack_functions.py
+++ b/camel/functions/slack_functions.py
@@ -65,7 +65,8 @@ def _login_slack(
)
if not slack_token:
raise KeyError(
- "SLACK_BOT_TOKEN or SLACK_USER_TOKEN environment variable not set."
+ "SLACK_BOT_TOKEN or SLACK_USER_TOKEN environment variable not "
+ "set."
)
client = WebClient(token=slack_token, ssl=ssl)
diff --git a/camel/human.py b/camel/human.py
index 2c5a25c02..67e5d5140 100644
--- a/camel/human.py
+++ b/camel/human.py
@@ -112,7 +112,9 @@ class Human:
return content
- def reduce_step(self, messages: Sequence[BaseMessage]) -> ChatAgentResponse:
+ def reduce_step(
+ self, messages: Sequence[BaseMessage]
+ ) -> ChatAgentResponse:
r"""Performs one step of the conversation by displaying options to the
user, getting their input, and parsing their choice.
diff --git a/camel/loaders/base_io.py b/camel/loaders/base_io.py
index a3b752290..4804cd3ab 100644
--- a/camel/loaders/base_io.py
+++ b/camel/loaders/base_io.py
@@ -65,7 +65,9 @@ class File(ABC):
)
def __str__(self) -> str:
- return f"File(name={self.name}, id={self.id}, metadata={self.metadata})"
+ return (
+ f"File(name={self.name}, id={self.id}, metadata={self.metadata})"
+ )
def copy(self) -> "File":
r"""Create a deep copy of this File"""
diff --git a/camel/loaders/unstructured_io.py b/camel/loaders/unstructured_io.py
index 2704dd15b..823c40a94 100644
--- a/camel/loaders/unstructured_io.py
+++ b/camel/loaders/unstructured_io.py
@@ -177,7 +177,9 @@ class UnstructuredIO:
# Check if the file exists
if not os.path.exists(input_path):
- raise FileNotFoundError(f"The file {input_path} was not found.")
+ raise FileNotFoundError(
+ f"The file {input_path} was not found."
+ )
# Read the file
try:
@@ -185,7 +187,9 @@ class UnstructuredIO:
elements = partition(file=f, **kwargs)
return elements
except Exception as e:
- raise Exception("Failed to parse the unstructured file.") from e
+ raise Exception(
+ "Failed to parse the unstructured file."
+ ) from e
def clean_text_data(
self,
@@ -425,9 +429,8 @@ class UnstructuredIO:
els, kw.get('metadata', [])
),
"stage_for_baseplate": baseplate.stage_for_baseplate,
- "stage_for_datasaur": lambda els, **kw: datasaur.stage_for_datasaur(
- els, kw.get('entities', [])
- ),
+ "stage_for_datasaur": lambda els,
+ **kw: datasaur.stage_for_datasaur(els, kw.get('entities', [])),
"stage_for_label_box": lambda els,
**kw: label_box.stage_for_label_box(els, **kw),
"stage_for_label_studio": lambda els,
diff --git a/camel/prompts/base.py b/camel/prompts/base.py
index 3aacc9228..748007aee 100644
--- a/camel/prompts/base.py
+++ b/camel/prompts/base.py
@@ -208,7 +208,8 @@ class TextPromptDict(Dict[Any, TextPrompt]):
EMBODIMENT_PROMPT = TextPrompt(
"System information :"
+ "\n".join(
- f"{key}: {value}" for key, value in get_system_information().items()
+ f"{key}: {value}"
+ for key, value in get_system_information().items()
)
+ "\n"
+ """You are the physical embodiment of the {role} who is working on solving a task: {task}.
diff --git a/camel/prompts/task_prompt_template.py b/camel/prompts/task_prompt_template.py
index e61769264..45eea6b6e 100644
--- a/camel/prompts/task_prompt_template.py
+++ b/camel/prompts/task_prompt_template.py
@@ -22,7 +22,9 @@ from camel.prompts.evaluation import (
EvaluationPromptTemplateDict,
)
from camel.prompts.misalignment import MisalignmentPromptTemplateDict
-from camel.prompts.object_recognition import ObjectRecognitionPromptTemplateDict
+from camel.prompts.object_recognition import (
+ ObjectRecognitionPromptTemplateDict,
+)
from camel.prompts.role_description_prompt_template import (
RoleDescriptionPromptTemplateDict,
)
@@ -52,8 +54,8 @@ class TaskPromptTemplateDict(Dict[Any, TextPromptDict]):
TaskType.MISALIGNMENT: MisalignmentPromptTemplateDict(),
TaskType.TRANSLATION: TranslationPromptTemplateDict(),
TaskType.EVALUATION: EvaluationPromptTemplateDict(),
- TaskType.SOLUTION_EXTRACTION: SolutionExtractionPromptTemplateDict(),
+ TaskType.SOLUTION_EXTRACTION: SolutionExtractionPromptTemplateDict(), # noqa: E501
TaskType.ROLE_DESCRIPTION: RoleDescriptionPromptTemplateDict(),
- TaskType.OBJECT_RECOGNITION: ObjectRecognitionPromptTemplateDict(),
+ TaskType.OBJECT_RECOGNITION: ObjectRecognitionPromptTemplateDict(), # noqa: E501
}
)
diff --git a/camel/retrievers/auto_retriever.py b/camel/retrievers/auto_retriever.py
index 59370048e..5802ed21e 100644
--- a/camel/retrievers/auto_retriever.py
+++ b/camel/retrievers/auto_retriever.py
@@ -134,7 +134,9 @@ class AutoRetriever:
collection_name = collection_name[:30]
return collection_name
- def _get_file_modified_date_from_file(self, content_input_path: str) -> str:
+ def _get_file_modified_date_from_file(
+ self, content_input_path: str
+ ) -> str:
r"""Retrieves the last modified date and time of a given file. This
function takes a file path as input and returns the last modified date
and time of that file.
@@ -147,9 +149,9 @@ class AutoRetriever:
str: The last modified time from file.
"""
mod_time = os.path.getmtime(content_input_path)
- readable_mod_time = datetime.datetime.fromtimestamp(mod_time).isoformat(
- timespec='seconds'
- )
+ readable_mod_time = datetime.datetime.fromtimestamp(
+ mod_time
+ ).isoformat(timespec='seconds')
return readable_mod_time
def _get_file_modified_date_from_storage(
@@ -321,8 +323,15 @@ class AutoRetriever:
info['text'] for info in all_retrieved_info if 'text' in info
)
- detailed_info = f"Original Query:\n{{ {query} }}\nRetrieved Context:\n{retrieved_infos}"
- text_info = f"Original Query:\n{{ {query} }}\nRetrieved Context:\n{retrieved_infos_text}"
+ detailed_info = (
+ f"Original Query:\n{{ {query} }}\n"
+ f"Retrieved Context:\n{retrieved_infos}"
+ )
+
+ text_info = (
+ f"Original Query:\n{{ {query} }}\n"
+ f"Retrieved Context:\n{retrieved_infos_text}"
+ )
if return_detailed_info:
return detailed_info
diff --git a/camel/retrievers/base.py b/camel/retrievers/base.py
index 1f7f18652..73d33ed8b 100644
--- a/camel/retrievers/base.py
+++ b/camel/retrievers/base.py
@@ -32,7 +32,8 @@ def _query_unimplemented(self, *input: Any) -> None:
registered hooks while the latter silently ignores them.
"""
raise NotImplementedError(
- f"Retriever [{type(self).__name__}] is missing the required \"query\" function"
+ f"Retriever [{type(self).__name__}] is missing the required"
+ " \"query\" function"
)
@@ -52,7 +53,8 @@ def _process_unimplemented(self, *input: Any) -> None:
registered hooks while the latter silently ignores them.
"""
raise NotImplementedError(
- f"Retriever [{type(self).__name__}] is missing the required \"process\" function"
+ f"Retriever [{type(self).__name__}] is missing the required "
+ "\"process\" function"
)
diff --git a/camel/retrievers/bm25_retriever.py b/camel/retrievers/bm25_retriever.py
index e48b6caf0..5bb0aa073 100644
--- a/camel/retrievers/bm25_retriever.py
+++ b/camel/retrievers/bm25_retriever.py
@@ -47,7 +47,8 @@ class BM25Retriever(BaseRetriever):
from rank_bm25 import BM25Okapi
except ImportError as e:
raise ImportError(
- "Package `rank_bm25` not installed, install by running 'pip install rank_bm25'"
+ "Package `rank_bm25` not installed, install by running 'pip "
+ "install rank_bm25'"
) from e
self.bm25: BM25Okapi = None
diff --git a/camel/retrievers/cohere_rerank_retriever.py b/camel/retrievers/cohere_rerank_retriever.py
index 8a67e63b9..527877d18 100644
--- a/camel/retrievers/cohere_rerank_retriever.py
+++ b/camel/retrievers/cohere_rerank_retriever.py
@@ -66,7 +66,8 @@ class CohereRerankRetriever(BaseRetriever):
self.api_key = api_key or os.environ["COHERE_API_KEY"]
except ValueError as e:
raise ValueError(
- "Must pass in cohere api key or specify via COHERE_API_KEY environment variable."
+ "Must pass in cohere api key or specify via COHERE_API_KEY"
+ " environment variable."
) from e
self.co = cohere.Client(self.api_key)
diff --git a/camel/retrievers/vector_retriever.py b/camel/retrievers/vector_retriever.py
index 2dc7c33aa..251775d6b 100644
--- a/camel/retrievers/vector_retriever.py
+++ b/camel/retrievers/vector_retriever.py
@@ -64,7 +64,9 @@ class VectorRetriever(BaseRetriever):
self.storage = (
storage
if storage is not None
- else QdrantStorage(vector_dim=self.embedding_model.get_output_dim())
+ else QdrantStorage(
+ vector_dim=self.embedding_model.get_output_dim()
+ )
)
self.similarity_threshold = similarity_threshold
self.unstructured_modules: UnstructuredIO = UnstructuredIO()
@@ -151,7 +153,8 @@ class VectorRetriever(BaseRetriever):
if query_results[0].record.payload is None:
raise ValueError(
- "Payload of vector storage is None, please check the collection."
+ "Payload of vector storage is None, please check the "
+ "collection."
)
# format the results
@@ -176,8 +179,11 @@ class VectorRetriever(BaseRetriever):
if not formatted_results:
return [
{
- 'text': f"""No suitable information retrieved from {content_path} \
- with similarity_threshold = {self.similarity_threshold}."""
+ 'text': (
+ f"No suitable information retrieved "
+ f"from {content_path} with similarity_threshold"
+ f" = {self.similarity_threshold}."
+ )
}
]
return formatted_results
diff --git a/camel/societies/babyagi_playing.py b/camel/societies/babyagi_playing.py
index 74964f932..5ba30b507 100644
--- a/camel/societies/babyagi_playing.py
+++ b/camel/societies/babyagi_playing.py
@@ -150,7 +150,8 @@ class BabyAGI:
if self.task_type in [TaskType.AI_SOCIETY, TaskType.MISALIGNMENT]:
task_specify_meta_dict.update(
dict(
- assistant_role=assistant_role_name, user_role=user_role_name
+ assistant_role=assistant_role_name,
+ user_role=user_role_name,
)
)
task_specify_meta_dict.update(extend_task_specify_meta_dict or {})
diff --git a/camel/societies/role_playing.py b/camel/societies/role_playing.py
index 267988310..e4558afe3 100644
--- a/camel/societies/role_playing.py
+++ b/camel/societies/role_playing.py
@@ -274,7 +274,8 @@ class RolePlaying:
]:
extend_sys_msg_meta_dicts = [
dict(
- assistant_role=assistant_role_name, user_role=user_role_name
+ assistant_role=assistant_role_name,
+ user_role=user_role_name,
)
for _ in range(2)
]
diff --git a/camel/storages/graph_storages/neo4j_graph.py b/camel/storages/graph_storages/neo4j_graph.py
index 10be15cc7..c93b85117 100644
--- a/camel/storages/graph_storages/neo4j_graph.py
+++ b/camel/storages/graph_storages/neo4j_graph.py
@@ -99,7 +99,9 @@ class Neo4jGraph(BaseGraphStorage):
"Please install it with `pip install neo4j`."
)
- self.driver = neo4j.GraphDatabase.driver(url, auth=(username, password))
+ self.driver = neo4j.GraphDatabase.driver(
+ url, auth=(username, password)
+ )
self.database = database
self.timeout = timeout
self.truncate = truncate
@@ -373,8 +375,8 @@ class Neo4jGraph(BaseGraphStorage):
with self.driver.session(database=self.database) as session:
session.run(
(
- "MATCH (n1:{})-[r:{}]->(n2:{}) WHERE n1.id = $subj AND n2.id"
- " = $obj DELETE r"
+ "MATCH (n1:{})-[r:{}]->(n2:{}) WHERE n1.id = $subj AND"
+ " n2.id = $obj DELETE r"
).format(
BASE_ENTITY_LABEL.replace("_", ""),
rel,
diff --git a/camel/storages/vectordb_storages/base.py b/camel/storages/vectordb_storages/base.py
index 1b23da1b9..64fdcd4fa 100644
--- a/camel/storages/vectordb_storages/base.py
+++ b/camel/storages/vectordb_storages/base.py
@@ -147,7 +147,8 @@ class BaseVectorStorage(ABC):
query: VectorDBQuery,
**kwargs: Any,
) -> List[VectorDBQueryResult]:
- r"""Searches for similar vectors in the storage based on the provided query.
+ r"""Searches for similar vectors in the storage based on the provided
+ query.
Args:
query (VectorDBQuery): The query object containing the search
diff --git a/camel/storages/vectordb_storages/milvus.py b/camel/storages/vectordb_storages/milvus.py
index 1720d2b4a..f7f9076ae 100644
--- a/camel/storages/vectordb_storages/milvus.py
+++ b/camel/storages/vectordb_storages/milvus.py
@@ -155,7 +155,8 @@ class MilvusStorage(BaseVectorStorage):
field_name="payload",
datatype=DataType.JSON,
description=(
- 'Any additional metadata or information related' 'to the vector'
+ 'Any additional metadata or information related'
+ 'to the vector'
),
)
@@ -267,7 +268,9 @@ class MilvusStorage(BaseVectorStorage):
for record in records:
record_dict = {
"id": record.id,
- "payload": record.payload if record.payload is not None else '',
+ "payload": record.payload
+ if record.payload is not None
+ else '',
"vector": record.vector,
}
validated_data.append(record_dict)
diff --git a/camel/toolkits/github_toolkit.py b/camel/toolkits/github_toolkit.py
index 8f7e80388..f1eb0d30f 100644
--- a/camel/toolkits/github_toolkit.py
+++ b/camel/toolkits/github_toolkit.py
@@ -48,7 +48,8 @@ class GithubIssue:
body (str): The body/content of the GitHub issue.
number (int): The issue number.
file_path (str): The path of the file associated with the issue.
- file_content (str): The content of the file associated with the issue.
+ file_content (str): The content of the file associated with the
+ issue.
"""
self.title = title
self.body = body
@@ -60,7 +61,8 @@ class GithubIssue:
r"""Returns a summary of the issue.
Returns:
- str: A string containing the title, body, number, file path, and file content of the issue.
+ str: A string containing the title, body, number, file path, and
+ file content of the issue.
"""
return (
f"Title: {self.title}\n"
@@ -72,15 +74,17 @@ class GithubIssue:
class GithubToolkit(BaseToolkit):
- r"""A class representing a toolkit for interacting with GitHub repositories.
+ r"""A class representing a toolkit for interacting with GitHub
+ repositories.
- This class provides methods for retrieving open issues, retrieving specific issues,
- and creating pull requests in a GitHub repository.
+ This class provides methods for retrieving open issues, retrieving
+ specific issues, and creating pull requests in a GitHub repository.
Args:
repo_name (str): The name of the GitHub repository.
- access_token (str, optional): The access token to authenticate with GitHub.
- If not provided, it will be obtained using the `get_github_access_token` method.
+ access_token (str, optional): The access token to authenticate with
+ GitHub. If not provided, it will be obtained using the
+ `get_github_access_token` method.
"""
def __init__(
@@ -90,8 +94,9 @@ class GithubToolkit(BaseToolkit):
Args:
repo_name (str): The name of the GitHub repository.
- access_token (str, optional): The access token to authenticate with GitHub.
- If not provided, it will be obtained using the `get_github_access_token` method.
+ access_token (str, optional): The access token to authenticate
+ with GitHub. If not provided, it will be obtained using the
+ `get_github_access_token` method.
"""
if access_token is None:
access_token = self.get_github_access_token()
@@ -107,10 +112,12 @@ class GithubToolkit(BaseToolkit):
self.repo = self.github.get_repo(repo_name)
def get_tools(self) -> List[OpenAIFunction]:
- r"""Returns a list of OpenAIFunction objects representing the functions in the toolkit.
+ r"""Returns a list of OpenAIFunction objects representing the
+ functions in the toolkit.
Returns:
- List[OpenAIFunction]: A list of OpenAIFunction objects representing the functions in the toolkit.
+ List[OpenAIFunction]: A list of OpenAIFunction objects
+ representing the functions in the toolkit.
"""
return [
OpenAIFunction(self.retrieve_issue_list),
@@ -125,15 +132,16 @@ class GithubToolkit(BaseToolkit):
str: A string containing the GitHub access token.
Raises:
- ValueError: If the API key or secret is not found in the environment variables.
+ ValueError: If the API key or secret is not found in the
+ environment variables.
"""
# Get `GITHUB_ACCESS_TOKEN` here: https://github.com/settings/tokens
GITHUB_ACCESS_TOKEN = os.environ.get("GITHUB_ACCESS_TOKEN")
if not GITHUB_ACCESS_TOKEN:
raise ValueError(
- "`GITHUB_ACCESS_TOKEN` not found in environment variables. Get it "
- "here: `https://github.com/settings/tokens`."
+ "`GITHUB_ACCESS_TOKEN` not found in environment variables. Get"
+ " it here: `https://github.com/settings/tokens`."
)
return GITHUB_ACCESS_TOKEN
@@ -151,7 +159,7 @@ class GithubToolkit(BaseToolkit):
number=issue.number,
file_path=issue.labels[
0
- ].name, # for now we require file path to be the first label in the PR
+ ].name, # we require file path to be the first label in the PR
file_content=self.retrieve_file_content(issue.labels[0].name),
)
for issue in issues
@@ -186,19 +194,23 @@ class GithubToolkit(BaseToolkit):
) -> str:
r"""Creates a pull request.
- This function creates a pull request in specified repository, which updates a
- file in the specific path with new content. The pull request description
- contains information about the issue title and number.
+ This function creates a pull request in specified repository, which
+ updates a file in the specific path with new content. The pull request
+ description contains information about the issue title and number.
Args:
- file_path (str): The path of the file to be updated in the repository.
+ file_path (str): The path of the file to be updated in the
+ repository.
new_content (str): The specified new content of the specified file.
- pr_title (str): The title of the issue that is solved by this pull request.
+ pr_title (str): The title of the issue that is solved by this pull
+ request.
body (str): The commit message for the pull request.
- branch_name (str): The name of the branch to create and submit the pull request from.
+ branch_name (str): The name of the branch to create and submit the
+ pull request from.
Returns:
- str: A formatted report of whether the pull request was created successfully or not.
+ str: A formatted report of whether the pull request was created
+ successfully or not.
"""
sb = self.repo.get_branch(self.repo.default_branch)
self.repo.create_git_ref(
diff --git a/camel/utils/commons.py b/camel/utils/commons.py
index ccc3e38f4..bab9b3faf 100644
--- a/camel/utils/commons.py
+++ b/camel/utils/commons.py
@@ -278,7 +278,9 @@ def api_keys_required(*required_keys: str) -> Callable[[F], F]:
def wrapper(*args: Any, **kwargs: Any) -> Any:
missing_keys = [k for k in required_keys if k not in os.environ]
if missing_keys:
- raise ValueError(f"Missing API keys: {', '.join(missing_keys)}")
+ raise ValueError(
+ f"Missing API keys: {', '.join(missing_keys)}"
+ )
return func(*args, **kwargs)
return cast(F, wrapper)
diff --git a/examples/ai_society/role_playing.py b/examples/ai_society/role_playing.py
index 276e72209..6fea7508f 100644
--- a/examples/ai_society/role_playing.py
+++ b/examples/ai_society/role_playing.py
@@ -40,7 +40,8 @@ def main(model_type=None, chat_turn_limit=50) -> None:
print(Fore.YELLOW + f"Original task prompt:\n{task_prompt}\n")
print(
Fore.CYAN
- + f"Specified task prompt:\n{role_play_session.specified_task_prompt}\n"
+ + "Specified task prompt:"
+ + f"\n{role_play_session.specified_task_prompt}\n"
)
print(Fore.RED + f"Final task prompt:\n{role_play_session.task_prompt}\n")
diff --git a/examples/ai_society/role_playing_multi_lingual.py b/examples/ai_society/role_playing_multi_lingual.py
index 1d18dd0cb..f25786eba 100644
--- a/examples/ai_society/role_playing_multi_lingual.py
+++ b/examples/ai_society/role_playing_multi_lingual.py
@@ -41,7 +41,8 @@ def main(model_type=None) -> None:
print(Fore.YELLOW + f"Original task prompt:\n{task_prompt}\n")
print(
Fore.CYAN
- + f"Specified task prompt:\n{role_play_session.specified_task_prompt}\n"
+ + "Specified task prompt:"
+ + f"\n{role_play_session.specified_task_prompt}\n"
)
print(Fore.RED + f"Final task prompt:\n{role_play_session.task_prompt}\n")
diff --git a/examples/ai_society/role_playing_multiprocess.py b/examples/ai_society/role_playing_multiprocess.py
index 4a0ac8319..3394e09e8 100644
--- a/examples/ai_society/role_playing_multiprocess.py
+++ b/examples/ai_society/role_playing_multiprocess.py
@@ -134,7 +134,8 @@ def generate_data(
break
assert (
- user_response.msg is not None and assistant_response.msg is not None
+ user_response.msg is not None
+ and assistant_response.msg is not None
)
if verbose:
@@ -171,14 +172,18 @@ def generate_data(
):
repeat_word_counter += 1
if repeat_word_counter == repeat_word_threshold:
- message_dict['termination_reason'] = "repeat_word_threshold"
+ message_dict['termination_reason'] = (
+ "repeat_word_threshold"
+ )
break
else:
repeat_word_counter = 0
# Save user message
message_counter += 1
- message_dict[f"message_{message_counter}"] = user_response.msg.to_dict()
+ message_dict[f"message_{message_counter}"] = (
+ user_response.msg.to_dict()
+ )
# Condition 5: End token observed
if "<CAMEL_TASK_DONE>" in user_response.msg.content:
diff --git a/examples/ai_society/role_playing_with_critic.py b/examples/ai_society/role_playing_with_critic.py
index a3a50e740..837bf03ab 100644
--- a/examples/ai_society/role_playing_with_critic.py
+++ b/examples/ai_society/role_playing_with_critic.py
@@ -51,7 +51,8 @@ def main() -> None:
print(Fore.YELLOW + f"Original task prompt:\n{task_prompt}\n")
print(
Fore.CYAN
- + f"Specified task prompt:\n{role_play_session.specified_task_prompt}\n"
+ + "Specified task prompt:"
+ + f"\n{role_play_session.specified_task_prompt}\n"
)
print(Fore.RED + f"Final task prompt:\n{role_play_session.task_prompt}\n")
diff --git a/examples/ai_society/role_playing_with_human.py b/examples/ai_society/role_playing_with_human.py
index b5ffeb11e..bc2c39444 100644
--- a/examples/ai_society/role_playing_with_human.py
+++ b/examples/ai_society/role_playing_with_human.py
@@ -45,7 +45,8 @@ def main() -> None:
print(Fore.YELLOW + f"Original task prompt:\n{task_prompt}\n")
print(
Fore.CYAN
- + f"Specified task prompt:\n{role_play_session.specified_task_prompt}\n"
+ + "Specified task prompt:"
+ + f"\n{role_play_session.specified_task_prompt}\n"
)
print(Fore.RED + f"Final task prompt:\n{role_play_session.task_prompt}\n")
diff --git a/examples/anthropic_models/role_playing_with_claude.py b/examples/anthropic_models/role_playing_with_claude.py
index 74366c1f8..1fcae4fbf 100644
--- a/examples/anthropic_models/role_playing_with_claude.py
+++ b/examples/anthropic_models/role_playing_with_claude.py
@@ -51,7 +51,8 @@ def main(model_type=None) -> None:
print(Fore.YELLOW + f"Original task prompt:\n{task_prompt}\n")
print(
Fore.CYAN
- + f"Specified task prompt:\n{role_play_session.specified_task_prompt}\n"
+ + "Specified task prompt:"
+ + f"\n{role_play_session.specified_task_prompt}\n"
)
print(Fore.RED + f"Final task prompt:\n{role_play_session.task_prompt}\n")
diff --git a/examples/code/role_playing.py b/examples/code/role_playing.py
index 62d3bf415..5e2ebe1a6 100644
--- a/examples/code/role_playing.py
+++ b/examples/code/role_playing.py
@@ -47,7 +47,8 @@ def main(model_type=None, chat_turn_limit=50) -> None:
print(Fore.YELLOW + f"Original task prompt:\n{task_prompt}\n")
print(
Fore.CYAN
- + f"Specified task prompt:\n{role_play_session.specified_task_prompt}\n"
+ + "Specified task prompt:"
+ + f"\n{role_play_session.specified_task_prompt}\n"
)
print(Fore.RED + f"Final task prompt:\n{role_play_session.task_prompt}\n")
diff --git a/examples/code/role_playing_multiprocess.py b/examples/code/role_playing_multiprocess.py
index a4e398c3a..3675a34ff 100644
--- a/examples/code/role_playing_multiprocess.py
+++ b/examples/code/role_playing_multiprocess.py
@@ -195,14 +195,18 @@ def generate_data(
):
repeat_word_counter += 1
if repeat_word_counter == repeat_word_threshold:
- message_dict['termination_reason'] = "repeat_word_threshold"
+ message_dict['termination_reason'] = (
+ "repeat_word_threshold"
+ )
break
else:
repeat_word_counter = 0
# Save user message
message_counter += 1
- message_dict[f"message_{message_counter}"] = user_response.msg.to_dict()
+ message_dict[f"message_{message_counter}"] = (
+ user_response.msg.to_dict()
+ )
# Condition 5: End token observed
if "<CAMEL_TASK_DONE>" in user_response.msg.content:
@@ -222,7 +226,9 @@ def generate_data(
if message_dict["num_messages"] == max_num_messages:
message_dict["termination_reason"] = "max_num_messages"
- with open(f"./camel_data/code/{message_dict['id']}.json", "w") as json_file:
+ with open(
+ f"./camel_data/code/{message_dict['id']}.json", "w"
+ ) as json_file:
json.dump(message_dict, json_file)
diff --git a/examples/function_call/github_examples.py b/examples/function_call/github_examples.py
index c49c046d4..d87dfba1a 100644
--- a/examples/function_call/github_examples.py
+++ b/examples/function_call/github_examples.py
@@ -31,11 +31,13 @@ def solve_issue(
that issue. You will get all the necessary parameters to later create a
pull request.
- When you have the issue, please follow the instruction and make the necessary
- changes to the source code provided. Once you have made the changes, you will
- need to use another provided github function to create a pull request
- that updates the file on the provided file path in the repository {repo_name}.
- The new_content property of the function should be the corrected source code.
+ When you have the issue, please follow the instruction and make the
+ necessary changes to the source code provided. Once you have made the
+ changes, you will need to use another provided github function to create a
+ pull request that updates the file on the provided file path in the
+ repository {repo_name}.
+ The new_content property of the function should be the corrected source
+ code.
Return response of this function as the output of this task.
"""
print(Fore.YELLOW + f"Final prompt:\n{prompt}\n")
diff --git a/examples/function_call/role_playing_with_functions.py b/examples/function_call/role_playing_with_functions.py
index c4d6154d2..30389a293 100644
--- a/examples/function_call/role_playing_with_functions.py
+++ b/examples/function_call/role_playing_with_functions.py
@@ -80,7 +80,8 @@ def main(model_type=ModelType.GPT_3_5_TURBO, chat_turn_limit=10) -> None:
print(Fore.YELLOW + f"Original task prompt:\n{task_prompt}\n")
print(
Fore.CYAN
- + f"Specified task prompt:\n{role_play_session.specified_task_prompt}\n"
+ + "Specified task prompt:"
+ + f"\n{role_play_session.specified_task_prompt}\n"
)
print(Fore.RED + f"Final task prompt:\n{role_play_session.task_prompt}\n")
diff --git a/examples/knowledge_graph/knowledge_graph_agent.py b/examples/knowledge_graph/knowledge_graph_agent.py
index fb04c5544..1497c27fb 100644
--- a/examples/knowledge_graph/knowledge_graph_agent.py
+++ b/examples/knowledge_graph/knowledge_graph_agent.py
@@ -19,7 +19,8 @@ uio = UnstructuredIO()
kg_agent = KnowledgeGraphAgent()
# Set example text input
-text_example = """CAMEL-AI.org is an open-source community dedicated to the study of autonomous and communicative agents.
+text_example = """CAMEL-AI.org is an open-source community dedicated to the
+study of autonomous and communicative agents.
"""
# Create an element from given text
@@ -47,15 +48,41 @@ Node(id='communicative agents', type='Concept', properties={'agent_generated'})
Relationships:
-Relationship(subj=Node(id='CAMEL-AI.org', type='Organization'), obj=Node(id='community', type='Concept'), type='FocusOn', properties={'agent_generated'})
-Relationship(subj=Node(id='CAMEL-AI.org', type='Organization'), obj=Node(id='study', type='Concept'), type='FocusOn', properties={'agent_generated'})
-Relationship(subj=Node(id='CAMEL-AI.org', type='Organization'), obj=Node(id='autonomous agents', type='Concept'), type='FocusOn', properties={'agent_generated'})
-Relationship(subj=Node(id='CAMEL-AI.org', type='Organization'), obj=Node(id='communicative agents', type='Concept'), type='FocusOn', properties={'agent_generated'})
+Relationship(subj=Node(id='CAMEL-AI.org', type='Organization'), obj=Node
+(id='community', type='Concept'), type='FocusOn', properties=
+{'agent_generated'})
+Relationship(subj=Node(id='CAMEL-AI.org', type='Organization'), obj=Node
+(id='study', type='Concept'), type='FocusOn', properties={'agent_generated'})
+Relationship(subj=Node(id='CAMEL-AI.org', type='Organization'), obj=Node
+(id='autonomous agents', type='Concept'), type='FocusOn', properties=
+{'agent_generated'})
+Relationship(subj=Node(id='CAMEL-AI.org', type='Organization'), obj=Node
+(id='communicative agents', type='Concept'), type='FocusOn', properties=
+{'agent_generated'})
===============================================================================
"""
"""
===============================================================================
-GraphElement(nodes=[Node(id='CAMEL-AI.org', type='Organization', properties={'agent_generated'}), Node(id='community', type='Concept', properties={'agent_generated'}), Node(id='study', type='Concept', properties={'agent_generated'}), Node(id='autonomous agents', type='Concept', properties={'agent_generated'}), Node(id='communicative agents', type='Concept', properties={'agent_generated'})], relationships=[Relationship(subj=Node(id='CAMEL-AI.org', type='Organization', properties={'agent_generated'}), obj=Node(id='community', type='Concept', properties={'agent_generated'}), type='FocusOn', properties={"'agent_generated'"}), Relationship(subj=Node(id='CAMEL-AI.org', type='Organization', properties={'agent_generated'}), obj=Node(id='study', type='Concept', properties={'agent_generated'}), type='FocusOn', properties={"'agent_generated'"}), Relationship(subj=Node(id='CAMEL-AI.org', type='Organization', properties={'agent_generated'}), obj=Node(id='autonomous agents', type='Concept', properties={'agent_generated'}), type='FocusOn', properties={"'agent_generated'"}), Relationship(subj=Node(id='CAMEL-AI.org', type='Organization', properties={'agent_generated'}), obj=Node(id='communicative agents', type='Concept', properties={'agent_generated'}), type='FocusOn', properties={"'agent_generated'"})], source=<unstructured.documents.elements.Text object at 0x7fd050e7bd90>)
+GraphElement(nodes=[Node(id='CAMEL-AI.org', type='Organization', properties=
+{'agent_generated'}), Node(id='community', type='Concept', properties=
+{'agent_generated'}), Node(id='study', type='Concept', properties=
+{'agent_generated'}), Node(id='autonomous agents', type='Concept', properties=
+{'agent_generated'}), Node(id='communicative agents', type='Concept',
+properties={'agent_generated'})], relationships=[Relationship(subj=Node
+(id='CAMEL-AI.org', type='Organization', properties={'agent_generated'}),
+obj=Node(id='community', type='Concept', properties={'agent_generated'}),
+type='FocusOn', properties={"'agent_generated'"}), Relationship(subj=Node
+(id='CAMEL-AI.org', type='Organization', properties={'agent_generated'}),
+obj=Node(id='study', type='Concept', properties={'agent_generated'}),
+type='FocusOn', properties={"'agent_generated'"}), Relationship(subj=Node
+(id='CAMEL-AI.org', type='Organization', properties={'agent_generated'}),
+obj=Node(id='autonomous agents', type='Concept', properties=
+{'agent_generated'}), type='FocusOn', properties={"'agent_generated'"}),
+Relationship(subj=Node(id='CAMEL-AI.org', type='Organization', properties=
+{'agent_generated'}), obj=Node(id='communicative agents', type='Concept',
+properties={'agent_generated'}), type='FocusOn', properties=
+{"'agent_generated'"})], source=<unstructured.documents.elements.Text object
+at 0x7fd050e7bd90>)
===============================================================================
"""
diff --git a/examples/knowledge_graph/neo4j.py b/examples/knowledge_graph/neo4j.py
index 0740d1d97..4be6e12fd 100644
--- a/examples/knowledge_graph/neo4j.py
+++ b/examples/knowledge_graph/neo4j.py
@@ -26,7 +26,8 @@ print(n4j.query("""MATCH (n) RETURN n AS node"""))
"""
===============================================================================
-[{'node': {}}, {'node': {}}, {'node': {'id': 'CAMEL'}}, {'node': {'id': 'multi-agent framework'}}]
+[{'node': {}}, {'node': {}}, {'node': {'id': 'CAMEL'}}, {'node': {'id':
+'multi-agent framework'}}]
===============================================================================
"""
diff --git a/examples/misalignment/role_playing_multiprocess.py b/examples/misalignment/role_playing_multiprocess.py
index 3842090c6..33f20a776 100644
--- a/examples/misalignment/role_playing_multiprocess.py
+++ b/examples/misalignment/role_playing_multiprocess.py
@@ -163,14 +163,18 @@ def generate_data(
):
repeat_word_counter += 1
if repeat_word_counter == repeat_word_threshold:
- message_dict['termination_reason'] = "repeat_word_threshold"
+ message_dict['termination_reason'] = (
+ "repeat_word_threshold"
+ )
break
else:
repeat_word_counter = 0
# Save user message
message_counter += 1
- message_dict[f"message_{message_counter}"] = user_response.msg.to_dict()
+ message_dict[f"message_{message_counter}"] = (
+ user_response.msg.to_dict()
+ )
# Condition 5: End token observed
if "<CAMEL_TASK_DONE>" in user_response.msg.content:
diff --git a/examples/misalignment/role_playing_with_human.py b/examples/misalignment/role_playing_with_human.py
index c0ada6081..6419be97b 100644
--- a/examples/misalignment/role_playing_with_human.py
+++ b/examples/misalignment/role_playing_with_human.py
@@ -49,7 +49,8 @@ def main() -> None:
print(Fore.YELLOW + f"Original task prompt:\n{task_prompt}\n")
print(
Fore.CYAN
- + f"Specified task prompt:\n{role_play_session.specified_task_prompt}\n"
+ + "Specified task prompt:"
+ + f"\n{role_play_session.specified_task_prompt}\n"
)
print(Fore.RED + f"Final task prompt:\n{role_play_session.task_prompt}\n")
@@ -64,7 +65,7 @@ def main() -> None:
Fore.GREEN
+ (
"AI Assistant terminated. "
- f"Reason: {assistant_response.info['termination_reasons']}."
+ f"Reason: {assistant_response.info['termination_reasons']}"
)
)
break
diff --git a/examples/open_source_models/role_playing_with_open_source_model.py b/examples/open_source_models/role_playing_with_open_source_model.py
index dd437af95..a7f9a3b89 100644
--- a/examples/open_source_models/role_playing_with_open_source_model.py
+++ b/examples/open_source_models/role_playing_with_open_source_model.py
@@ -57,7 +57,8 @@ def main(
print(Fore.YELLOW + f"Original task prompt:\n{task_prompt}\n")
print(
Fore.CYAN
- + f"Specified task prompt:\n{role_play_session.specified_task_prompt}\n"
+ + "Specified task prompt:"
+ + f"\n{role_play_session.specified_task_prompt}\n"
)
print(Fore.RED + f"Final task prompt:\n{role_play_session.task_prompt}\n")
diff --git a/examples/openai_audio_models/openai_audio_models.py b/examples/openai_audio_models/openai_audio_models.py
index b7051b2c3..f4b8d9e59 100644
--- a/examples/openai_audio_models/openai_audio_models.py
+++ b/examples/openai_audio_models/openai_audio_models.py
@@ -17,9 +17,15 @@ from camel.models import OpenAIAudioModels
audio_models = OpenAIAudioModels()
# Set example input
-input = """CAMEL-AI.org is an open-source community dedicated to 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 provide, implement, and support various types of agents, tasks, prompts, models, datasets, and simulated environments.
+input = """CAMEL-AI.org is an open-source community dedicated to 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 provide, implement,
+and support various types of agents, tasks, prompts, models, datasets, and
+simulated environments.
-Join us via Slack, Discord, or WeChat in pushing the boundaries of building AI Society."""
+Join us via Slack, Discord, or WeChat in pushing the boundaries of building AI
+Society."""
# Set example local path to store the file
storage_path = "examples/openai_audio_models/example_audio.mp3"
@@ -33,6 +39,12 @@ text_output = audio_models.speech_to_text(audio_file_path=storage_path)
print(text_output)
"""
===============================================================================
-CamelAI.org is an open-source community dedicated to 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 provide, implement, and support various types of agents, tasks, prompts, models, datasets, and simulated environments. Join us via Slack, Discord, or WeChat in pushing the boundaries of building AI society.
+CamelAI.org is an open-source community dedicated to 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 provide, implement,
+and support various types of agents, tasks, prompts, models, datasets, and
+simulated environments. Join us via Slack, Discord, or WeChat in pushing the
+boundaries of building AI society.
===============================================================================
"""
diff --git a/examples/role_description/role_playing_with_role_description.py b/examples/role_description/role_playing_with_role_description.py
index d753a0e78..5775a12fb 100644
--- a/examples/role_description/role_playing_with_role_description.py
+++ b/examples/role_description/role_playing_with_role_description.py
@@ -87,7 +87,8 @@ def main(
print(Fore.YELLOW + f"Original task prompt:\n{task_prompt}\n")
print(
Fore.CYAN
- + f"Specified task prompt:\n{role_play_session.specified_task_prompt}\n"
+ + "Specified task prompt:"
+ + f"\n{role_play_session.specified_task_prompt}\n"
)
print(Fore.RED + f"Final task prompt:\n{role_play_session.task_prompt}\n")
@@ -102,7 +103,7 @@ def main(
Fore.GREEN
+ (
"AI Assistant terminated. "
- f"Reason: {assistant_response.info['termination_reasons']}."
+ f"Reason: {assistant_response.info['termination_reasons']}"
)
)
break
diff --git a/examples/summarization/gpt_solution_extraction.py b/examples/summarization/gpt_solution_extraction.py
index cc3e67ce9..62504ff72 100644
--- a/examples/summarization/gpt_solution_extraction.py
+++ b/examples/summarization/gpt_solution_extraction.py
@@ -194,7 +194,9 @@ def main():
# Formatting is needed to match the names of the original
# generated JSON files xxx_xxx_xxx.json
- file_names = [format_combination(combination) for combination in file_names]
+ file_names = [
+ format_combination(combination) for combination in file_names
+ ]
# Check that all files exist
for file_name in file_names:
diff --git a/examples/test/test_ai_society_example.py b/examples/test/test_ai_society_example.py
index 18689b36e..f36c05682 100644
--- a/examples/test/test_ai_society_example.py
+++ b/examples/test/test_ai_society_example.py
@@ -21,7 +21,9 @@ from camel.types import ModelType
def test_ai_society_role_playing_example():
with patch('time.sleep', return_value=None):
- examples.ai_society.role_playing.main(ModelType.STUB, chat_turn_limit=2)
+ examples.ai_society.role_playing.main(
+ ModelType.STUB, chat_turn_limit=2
+ )
def test_role_playing_with_function_example():
diff --git a/poetry.lock b/poetry.lock
index 0166e438e..782d07ba1 100644
--- a/poetry.lock
+++ b/poetry.lock
@@ -2897,12 +2897,13 @@ files = [
[[package]]
name = "neo4j"
-version = "5.20.0"
+version = "5.21.0"
description = "Neo4j Bolt driver for Python"
optional = true
python-versions = ">=3.7"
files = [
- {file = "neo4j-5.20.0.tar.gz", hash = "sha256:c59e54a0c0fa1f109f1d2fa5293c29c2bb30ba388b4f9dd9656919793c10063a"},
+ {file = "neo4j-5.21.0-py3-none-any.whl", hash = "sha256:f95b19ab67b83888e1c65fa6266659138f7efbecce8d5dfb42eeed2d17140af9"},
+ {file = "neo4j-5.21.0.tar.gz", hash = "sha256:6a6852354479742e43012a7f16007120e9b44bf584c97614544f2f41f46005ee"},
]
[package.dependencies]
@@ -3481,13 +3482,13 @@ image = ["Pillow"]
[[package]]
name = "pdfplumber"
-version = "0.11.0"
+version = "0.11.1"
description = "Plumb a PDF for detailed information about each char, rectangle, and line."
optional = true
python-versions = ">=3.8"
files = [
- {file = "pdfplumber-0.11.0-py3-none-any.whl", hash = "sha256:be41686fe9515da5f54fad254e2b6941a723b9afe99eb92008df30880b6d61b3"},
- {file = "pdfplumber-0.11.0.tar.gz", hash = "sha256:e0027b8fc0ab98329cd8d445f5324d779078a6b58406471234e3e9c265dd8a48"},
+ {file = "pdfplumber-0.11.1-py3-none-any.whl", hash = "sha256:8f3f087001fc3ec72d2c8be23d4ad59a763356e70d659a9180b5250919a3e5a8"},
+ {file = "pdfplumber-0.11.1.tar.gz", hash = "sha256:cb95b4369fa94c3901bc6bce89d81e098afd2bd8d88e0d9706152f4c57e82349"},
]
[package.dependencies]
diff --git a/pyproject.toml b/pyproject.toml
index a9a51e50f..7e9ba0ad1 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -207,7 +207,7 @@ recommonmark = "*"
docutils = "<0.20.0"
[tool.ruff]
-line-length = 80
+line-length = 79
fix = true
target-version = "py39"
@@ -221,7 +221,9 @@ extend-select = [
"C4", # flake8-comprehensions
"PGH", # pygrep-hooks
"RUF", # ruff
+ "E",
]
+
ignore = [
"B028", # Warning without stacklevel
"B904", # use 'raise ... from err'
@@ -231,6 +233,9 @@ ignore = [
"C408", # we have used lots of dict(...) instead of literal
]
+[tool.ruff.lint.pydocstyle]
+convention = "google"
+
[tool.ruff.lint.isort]
known-first-party = ["camel"]
@@ -238,6 +243,7 @@ known-first-party = ["camel"]
pythonpath = ["."]
addopts = ["--strict-markers"]
markers = [
+ "asyncio: mark a test as asyncio-based.",
"very_slow: mark a very slow test to run only in full test mode",
"model_backend: for tests that require OpenAI API key or a local LLM",
]
diff --git a/test/agents/test_chat_agent.py b/test/agents/test_chat_agent.py
index b389ef91b..20ff53fee 100644
--- a/test/agents/test_chat_agent.py
+++ b/test/agents/test_chat_agent.py
@@ -445,7 +445,8 @@ async def test_tool_calling_async():
role_name="User",
role_type=RoleType.USER,
meta_dict=dict(),
- content="Call the async sleep which is specified in function list with 1 second.",
+ content="Call the async sleep which is specified in function list with"
+ " 1 second.",
)
agent_response = await agent.step_async(user_msg)
diff --git a/test/agents/test_deductive_reasoner_agent.py b/test/agents/test_deductive_reasoner_agent.py
index d6af9bf27..ef53daaf2 100644
--- a/test/agents/test_deductive_reasoner_agent.py
+++ b/test/agents/test_deductive_reasoner_agent.py
@@ -75,18 +75,26 @@ None
condition 3:
The website needs to have a search algorithm or function implemented.
condition 4:
- The website needs to have a user interface that allows users to input search queries.
+ The website needs to have a user interface that allows users to input
+ search queries.
condition 5:
- The website needs to have a backend system that processes search queries and retrieves relevant results.
+ The website needs to have a backend system that processes search
+ queries and retrieves relevant results.
- Entity/Label Recognition of Conditions:
-["Website search bar", "Indexed content database", "Search algorithm/function", "User interface for search queries", "Backend system for query processing"]
+["Website search bar", "Indexed content database", "Search algorithm/
+function", "User interface for search queries", "Backend system for query
+processing"]
- Quality Assessment ($Q$) (do not use symbols):
- The transition from $A$ to $B$ would be considered efficient if the search capabilities are implemented with minimal resource usage.
- The transition would be considered effective if the website successfully provides accurate search results.
- Safety and risks should be assessed to ensure user privacy and data security during the transition.
- Feedback mechanisms should be incorporated to continuously improve the search capabilities based on user feedback.
+ The transition from $A$ to $B$ would be considered efficient if the search
+ capabilities are implemented with minimal resource usage.
+ The transition would be considered effective if the website successfully
+ provides accurate search results.
+ Safety and risks should be assessed to ensure user privacy and data
+ security during the transition.
+ Feedback mechanisms should be incorporated to continuously improve the
+ search capabilities based on user feedback.
- Iterative Evaluation:
None"""
@@ -106,28 +114,29 @@ def generate_expected_content():
),
"condition 4": (
"The website needs to have a user interface that allows users "
- "to input search queries."
+ "to input\n search queries."
),
"condition 5": (
"The website needs to have a backend system that processes "
- "search queries and retrieves relevant results."
+ "search\n queries and retrieves relevant results."
),
},
"labels": [
"Website search bar",
"Indexed content database",
- "Search algorithm/function",
+ "Search algorithm/\nfunction",
"User interface for search queries",
- "Backend system for query processing",
+ "Backend system for query\nprocessing",
],
"evaluate_quality": (
"The transition from $A$ to $B$ would be considered efficient if "
- "the search capabilities are implemented with minimal resource "
- "usage.\n The transition would be considered effective if the "
- "website successfully provides accurate search results.\n "
- "Safety and risks should be assessed to ensure user privacy and "
- "data security during the transition.\n Feedback mechanisms "
- "should be incorporated to continuously improve the search "
- "capabilities based on user feedback."
+ "the search\n capabilities are implemented with minimal "
+ "resource usage.\n The transition would be considered "
+ "effective if the website successfully\n provides accurate "
+ "search results.\n Safety and risks should be assessed to"
+ " ensure user privacy and data\n security during the "
+ "transition.\n Feedback mechanisms should be incorporated "
+ "to continuously improve the\n search capabilities based on"
+ " user feedback."
),
}
diff --git a/test/agents/test_knowledge_agent.py b/test/agents/test_knowledge_agent.py
index b4d306859..25c09be9f 100644
--- a/test/agents/test_knowledge_agent.py
+++ b/test/agents/test_knowledge_agent.py
@@ -48,7 +48,9 @@ def test_parse_graph_elements():
agent.element = Mock()
input_string = """
Node(id='node_id', type='node_type', properties={})
- Relationship(subj=Node(id='subj_id', type='subj_type', properties={}), obj=Node(id='obj_id', type='obj_type', properties={}), type='test_type', properties={})
+ Relationship(subj=Node(id='subj_id', type='subj_type', properties={}),
+ obj=Node(id='obj_id', type='obj_type', properties={}), type='test_type',
+ properties={})
"""
expected_nodes = [
Node(id='node_id', type='node_type', properties={}),
diff --git a/test/functions/test_open_api_function.py b/test/functions/test_open_api_function.py
index ded3a580a..389a25f20 100644
--- a/test/functions/test_open_api_function.py
+++ b/test/functions/test_open_api_function.py
@@ -61,7 +61,8 @@ def test_coursera_search(get_function):
"Human Learning",
],
"objectUrl": (
- "https://www.coursera.org/specializations/machine-learning-introduction?utm_source=rest_api"
+ '''https://www.coursera.org/specializations/
+ machine-learning-introduction?utm_source=rest_api'''
),
}
]
@@ -81,7 +82,9 @@ def test_klarna_productsUsingGET(get_function):
'products': [
{
'name': 'Nike Dunk Low Retro M - Black/White',
- 'url': 'https://www.klarna.com/us/shopping/pl/cl337/3200177969/Shoes/Nike-Dunk-Low-Retro-M-Black-White/?utm_source=openai&ref-site=openai_plugin',
+ 'url': '''https://www.klarna.com/us/shopping/pl/cl337/
+ 3200177969/Shoes/Nike-Dunk-Low-Retro-M-Black-White/?
+ utm_source=openai&ref-site=openai_plugin''',
'price': '\$81.00',
'attributes': [
'Outsole:Rubber',
@@ -91,13 +94,17 @@ def test_klarna_productsUsingGET(get_function):
'Target Group:Man',
'Color:White',
'Upper Material:Leather',
- 'Size (US):9.5,10,11,12,13,14,15,16,17,18,11.5,10.5,2,3,4,5,6,7,8,9,2.5,3.5,4.5,16.5,5.5,15.5,6.5,14.5,13.5,7.5,8.5,12.5',
+ '''Size (US):9.5,10,11,12,13,14,15,16,17,18,11.5,10.5,2,3,
+ 4,5,6,7,8,9,2.5,3.5,4.5,16.5,5.5,15.5,6.5,14.5,13.5,7.5,8.
+ 5,12.5''',
'Series:Nike Dunk',
],
},
{
'name': "Nike Air Force 1 '07 M - White",
- 'url': 'https://www.klarna.com/us/shopping/pl/cl337/3979297/Shoes/Nike-Air-Force-1-07-M-White/?utm_source=openai&ref-site=openai_plugin',
+ 'url': '''https://www.klarna.com/us/shopping/pl/cl337/3979297/
+ Shoes/Nike-Air-Force-1-07-M-White/?utm_source=openai&
+ ref-site=openai_plugin''',
'price': '\$80.00',
'attributes': [
'Outsole:Rubber',
@@ -106,7 +113,9 @@ def test_klarna_productsUsingGET(get_function):
'Target Group:Man',
'Color:White',
'Upper Material:Leather',
- 'Size (US):9.5,10,11,12,13,14,15,16,17,11.5,10.5,2,3,4,5,6,7,8,9,2.5,3.5,4.5,16.5,5.5,15.5,6.5,14.5,13.5,7.5,8.5,12.5',
+ '''Size (US):9.5,10,11,12,13,14,15,16,17,11.5,10.5,2,3,4,5,
+ 6,7,8,9,2.5,3.5,4.5,16.5,5.5,15.5,6.5,14.5,13.5,7.5,8.5,12.
+ 5''',
'Lining Material:Textile',
'Series:Nike Air Force 1',
],
@@ -130,26 +139,35 @@ def test_speak_translate(get_function):
# ruff: noqa: RUF001
mock_response_data = {
"explanation": '''
- <translation language="Chinese" context="Looking for the German word for the fruit that is commonly red, green, or yellow.">
+ <translation language="Chinese" context="Looking for the German word for
+ the fruit that is commonly red, green, or yellow.">
苹果 (píngguǒ)
</translation>
- <alternatives context="Looking for the German word for the fruit that is commonly red, green, or yellow.">
- 1. "苹果 (píngguǒ)" *(Neutral/Formal - the standard term for 'apple' in Chinese)*
- 2. "苹儿 (pín er)" *(Informal - a colloquial way to refer to an apple, often used in Northern China)*
- 3. "苹果儿 (píngguǒ er)" *(Informal - similar to "苹儿 (pín er)", used in casual conversations)*
+ <alternatives context="Looking for the German word for the fruit that is
+ commonly red, green, or yellow.">
+ 1. "苹果 (píngguǒ)" *(Neutral/Formal - the standard term for 'apple' in
+ Chinese)*
+ 2. "苹儿 (pín er)" *(Informal - a colloquial way to refer to an apple,
+ often used in Northern China)*
+ 3. "苹果儿 (píngguǒ er)" *(Informal - similar to "苹儿 (pín er)", used in
+ casual conversations)*
</alternatives>
<example-convo language="Chinese">
<context>At a fruit market in China.</context>
* Li: "嗨,这里有新鲜的苹果吗?" (Hi, do you have fresh apples here?)
- * Seller: "当然有!我们这里的苹果非常好吃,是从山上来的。" (Of course! The apples here are delicious, they come from the mountains.)
+ * Seller: "当然有!我们这里的苹果非常好吃,是从山上来的。" (Of course!
+ The apples here are delicious, they come from the mountains.)
* Li: "好的,我要买几个红苹果。" (Great, I want to buy some red apples.)
</example-convo>
- *[Report an issue or leave feedback](https://speak.com/chatgpt?rid=sjqtmni8qkvtwr6jlj3xl1lz)*
+ *[Report an issue or leave feedback](https://speak.com/chatgpt?
+ rid=sjqtmni8qkvtwr6jlj3xl1lz)*
''',
- "extra_response_instructions": "Use all information in the API response and fully render all Markdown.\nAlways end your response with a link to report an issue or leave feedback on the plugin.",
+ "extra_response_instructions": '''Use all information in the API
+ response and fully render all Markdown.\nAlways end your response with
+ a link to report an issue or leave feedback on the plugin.''',
}
mock_response = MagicMock()
@@ -159,48 +177,75 @@ def test_speak_translate(get_function):
"phrase_to_translate": "Wie sagt man 'apple' auf Deutsch?",
"learning_language": "Chinese",
"native_language": "English",
- "additional_context": "Looking for the German word for the fruit that is commonly red, green, or yellow.",
+ "additional_context": '''Looking for the German word for the fruit
+ that is commonly red, green, or yellow.''',
"full_query": "What is the German word for 'apple'?",
}
result = get_function(requestBody=translate_request)
assert result == mock_response_data
[email protected]('get_function', ['speak_explainPhrase'], indirect=True)
+ 'get_function', ['speak_explainPhrase'], indirect=True
+)
def test_speak_explainPhrase(get_function):
mock_response_data = {
"explanation": '''
<markdown>
- <explanation context="Someone said this to me after a surprising event occurred. Want to understand the tone and context it's used in.">
+ <explanation context="Someone said this to me after a surprising event
+ occurred. Want to understand the tone and context it's used in.">
The phrase you entered is: "<input></input>"
- This phrase is commonly used in Chinese and it means "What happened?" or "What's going on?" It is often used when you want to express surprise or curiosity about a situation or event. Imagine someone just witnessed something unexpected and they are genuinely interested in finding out more details about it.
+ This phrase is commonly used in Chinese and it means "What happened?" or
+ "What's going on?" It is often used when you want to express surprise or
+ curiosity about a situation or event. Imagine someone just witnessed
+ something unexpected and they are genuinely interested in finding out more
+ details about it.
- For example, if you witnessed a car accident on the street and you're confused about what happened, you can ask "你们这是怎么回事啊?" (Nǐmen zhè shì zěnme huíshì a?) which translates to "What happened here?" or "What's going on here?"
+ For example, if you witnessed a car accident on the street and you're
+ confused about what happened, you can ask "你们这是怎么回事啊?"
+ (Nǐmen zhè shì zěnme huíshì a?) which translates to "What
+ happened here?" or "What's going on here?"
</explanation>
- <alternatives context="Someone said this to me after a surprising event occurred. Want to understand the tone and context it's used in.">
- Here are a few alternative phrases that convey a similar meaning and can be used in different situations:
+ <alternatives context="Someone said this to me after a surprising event
+ occurred. Want to understand the tone and context it's used in.">
+ Here are a few alternative phrases that convey a similar meaning and can
+ be used in different situations:
- 1. "发生了什么事?" (Fāshēngle shénme shì?) - This phrase is a bit more formal and it means "What happened?" It can be used in various contexts, such as asking about a news event or inquiring about a situation you're not familiar with.
+ 1. "发生了什么事?" (Fāshēngle shénme shì?) - This phrase is a bit more
+ formal and it means "What happened?" It can be used in various contexts,
+ such as asking about a news event or inquiring about a situation you're
+ not familiar with.
- 2. "出什么事了?" (Chū shénme shì le?) - This phrase is more casual and can be translated as "What's going on?" or "What's happening?" It is often used when you want to express surprise and inquire about a situation.
+ 2. "出什么事了?" (Chū shénme shì le?) - This phrase is more
+ casual and can be translated as "What's going on?" or "What's
+ happening?" It is often used when you want to express surprise
+ and inquire about a situation.
- 3. "怎么回事?" (Zěnme huíshì?) - This phrase is similar to the first one we mentioned, but it's a bit more informal. It can be used in both casual and formal situations to ask "What's going on?" or "What happened?"
+ 3. "怎么回事?" (Zěnme huíshì?) - This phrase is similar to the first one
+ we mentioned, but it's a bit more informal. It can be used in both casual
+ and formal situations to ask "What's going on?" or "What happened?"
</alternatives>
<example-convo language="Chinese">
- <context>You and your friend are walking in the park when suddenly, a UFO appears in the sky.</context>
+ <context>You and your friend are walking in the park when suddenly, a UFO
+ appears in the sky.</context>
<dialogue>
- Person A: 哇,你看!天上有 个飞碟!(Wā, nǐ kàn! Tiānshàng yǒu gè fēidié!) Wow, look! There's a UFO in the sky!
+ Person A: 哇,你看!天上有 个飞碟!(Wā, nǐ kàn! Tiānshàng yǒu gè
+ fēidié!) Wow, look! There's a UFO in the sky!
Person B: 什么?你确定吗?(Shénme? Nǐ quèdìng ma?) What? Are you sure?
- Person A: 是的!你们这是怎么回事啊?(Shì de! Nǐmen zhè shì zěnme huíshì a?) Yes! What happened here?
+ Person A: 是的!你们这是怎么回事啊?(Shì de! Nǐmen zhè shì
+ zěnme huíshì a?)
+ Yes! What happened here?
</dialogue>
</example-convo>
</markdown>
''',
- "extra_response_instructions": "Use all information in the API response and fully render all Markdown.\nAlways end your response with a link to report an issue or leave feedback on the plugin.",
+ "extra_response_instructions": '''Use all information in the API
+ response and fully render all Markdown.\nAlways end your response with
+ a link to report an issue or leave feedback on the plugin.''',
}
mock_response = MagicMock()
mock_response.json.return_value = mock_response_data
@@ -213,7 +258,8 @@ def test_speak_explainPhrase(get_function):
"Someone said this to me after a surprising event occurred."
"Want to understand the tone and context it's used in."
),
- "full_query": "Somebody said 'no mames' to me, what does that mean?",
+ "full_query": '''Somebody said 'no mames' to me, what does that
+ mean?''',
}
result = get_function(requestBody=explain_phrase_request)
assert result == mock_response_data
@@ -224,36 +270,61 @@ def test_speak_explainTask(get_function):
mock_response_data = {
"explanation": '''
<markdown>
- <explanation context="Someone said this to me after a surprising event occurred. Want to understand the tone and context it's used in.">
+ <explanation context="Someone said this to me after a surprising event
+ occurred. Want to understand the tone and context it's used in.">
The phrase you entered is: "<input></input>"
- This phrase is commonly used in Chinese and it means "What happened?" or "What's going on?" It is often used when you want to express surprise or curiosity about a situation or event. Imagine someone just witnessed something unexpected and they are genuinely interested in finding out more details about it.
+ This phrase is commonly used in Chinese and it means "What happened?" or
+ "What's going on?" It is often used when you want to express surprise or
+ curiosity about a situation or event. Imagine someone just witnessed
+ something unexpected and they are genuinely interested in finding out more
+ details about it.
- For example, if you witnessed a car accident on the street and you're confused about what happened, you can ask "你们这是怎么回事啊?" (Nǐmen zhè shì zěnme huíshì a?) which translates to "What happened here?" or "What's going on here?"
+ For example, if you witnessed a car accident on the street and you're
+ confused about what happened, you can ask "你们这是怎么回事啊?"
+ (Nǐmen zhè shì zěnme huíshì a?) which translates to "What happened
+ here?" or "What's going on here?"
</explanation>
- <alternatives context="Someone said this to me after a surprising event occurred. Want to understand the tone and context it's used in.">
- Here are a few alternative phrases that convey a similar meaning and can be used in different situations:
+ <alternatives context="Someone said this to me after a surprising event
+ occurred. Want to understand the tone and context it's used in.">
+ Here are a few alternative phrases that convey a similar meaning and can
+ be used in different situations:
- 1. "发生了什么事?" (Fāshēngle shénme shì?) - This phrase is a bit more formal and it means "What happened?" It can be used in various contexts, such as asking about a news event or inquiring about a situation you're not familiar with.
+ 1. "发生了什么事?" (Fāshēngle shénme shì?) - This phrase is a bit more
+ formal and it means "What happened?" It can be used in various contexts,
+ such as asking about a news event or inquiring about a situation you're
+ not familiar with.
- 2. "出什么事了?" (Chū shénme shì le?) - This phrase is more casual and can be translated as "What's going on?" or "What's happening?" It is often used when you want to express surprise and inquire about a situation.
+ 2. "出什么事了?" (Chū shénme shì le?) - This phrase is more casual and
+ can be translated as "What's going on?" or "What's happening?" It is
+ often used when you want to express surprise and inquire about a
+ situation.
- 3. "怎么回事?" (Zěnme huíshì?) - This phrase is similar to the first one we mentioned, but it's a bit more informal. It can be used in both casual and formal situations to ask "What's going on?" or "What happened?"
+ 3. "怎么回事?" (Zěnme huíshì?) - This phrase is similar to the first one
+ we mentioned, but it's a bit more informal. It can be used in both casual
+ and formal situations to ask "What's going on?" or "What happened?"
</alternatives>
<example-convo language="Chinese">
- <context>You and your friend are walking in the park when suddenly, a UFO appears in the sky.</context>
+ <context>You and your friend are walking in the park when suddenly, a UFO
+ appears in the sky.</context>
<dialogue>
- Person A: 哇,你看!天上有 个飞碟!(Wā, nǐ kàn! Tiānshàng yǒu gè fēidié!) Wow, look! There's a UFO in the sky!
- Person B: 什么?你确定吗?(Shénme? Nǐ quèdìng ma?) What? Are you sure?
- Person A: 是的!你们这是怎么回事啊?(Shì de! Nǐmen zhè shì zěnme huíshì a?) Yes! What happened here?
+ Person A: 哇,你看!天上有 个飞碟!(Wā, nǐ kàn! Tiānshàng yǒu gè
+ fēidié!) Wow, look! There's a UFO in the sky!
+ Person B: 什么?你确定吗?(Shénme? Nǐ quèdìng ma?) What? Are
+ you sure?
+ Person A: 是的!你们这是怎么回事啊?(Shì de! Nǐmen zhè shì zěnme
+ huíshì a?)
+ Yes! What happened here?
</dialogue>
</example-convo>
</markdown>
''',
- "extra_response_instructions": "Use all information in the API response and fully render all Markdown.\nAlways end your response with a link to report an issue or leave feedback on the plugin.",
+ "extra_response_instructions": '''Use all information in the API
+ response and fully render all Markdown.\nAlways end your response with
+ a link to report an issue or leave feedback on the plugin.''',
}
mock_response = MagicMock()
mock_response.json.return_value = mock_response_data
@@ -278,13 +349,18 @@ def test_speak_explainTask(get_function):
def test_biztoc_getNews(get_function):
mock_response_data = [
{
- "title": "Republican on Fox Calls for the GOP to ‘Shut Down the Economy’ to Fix Immigration: ‘We Should, Really’",
+ "title": "Republican on Fox Calls for the GOP to ‘Shut Down the"
+ " Economy’ to Fix Immigration: ‘We Should, Really’",
"source": "mediaite.com",
"date": "Tue, 21 May 2024",
- "summary": "Republican Congresswoman Victoria Spartz joined Fox Business host Maria Bartiromo to discuss border security, calling for drastic measures.",
+ "summary": "Republican Congresswoman Victoria Spartz joined Fox"
+ " Business host Maria Bartiromo to discuss border security,"
+ " calling for drastic measures.",
"image": "https://c.biztoc.com/p/c7a5cea54ed2bdd5/s.webp",
"tags": ["victoriaspartz", "borderpatrol", "immigration"],
- "url": "https://www.mediaite.com/tv/republican-on-fox-calls-for-the-gop-to-shut-down-the-economy-to-fix-immigration-we-should-really/?ref=biztoc.com",
+ "url": "https://www.mediaite.com/tv/"
+ "republican-on-fox-calls-for-the-gop-to-shut-down-the-economy-to-"
+ "fix-immigration-we-should-really/?ref=biztoc.com",
}
]
mock_response = MagicMock()
@@ -299,8 +375,10 @@ def test_biztoc_getNews(get_function):
)
def test_create_qr_code_getQRCode(get_function):
mock_response_data = {
- 'img_tag': '<img src="https://api.qrserver.com/v1/create-qr-code/?data=The data to encode in the QR code.&size=120x120" '
- 'alt="The alt text for the QR code image." title="The title for the QR code image." />'
+ 'img_tag': """<img src="https://api.qrserver.com/v1/create-qr-code/?
+ data=The data to encode in the QR code.&size=120x120"
+ 'alt="The alt text for the QR code image." title="The title for the QR
+ code image." />'"""
}
mock_response = MagicMock()
mock_response.json.return_value = mock_response_data
@@ -322,20 +400,25 @@ def test_out_school_searchClasses(get_function):
{
"uid": "f170ecbb-4ceb-41ad-af1a-3ac68f120833",
"title": "1:1 Math Tutoring With a Math Major/Teacher",
- "summary": "Personalized 1:1 math tutoring by an experienced Math Major/Teacher for Grades 2 through 10.",
+ "summary": "Personalized 1:1 math tutoring by an experienced Math"
+ " Major/Teacher for Grades 2 through 10.",
"subject": "Math",
"duration_minutes": 40,
"price_cents": 4500,
"age_min": 7,
"age_max": 15,
- "url": "https://outschool.com/classes/11-math-tutoring-with-a-math-majorteacher-fYCdDueY?utm_medium=chatgpt&utm_source=chatgpt-plugin",
+ "url": "https://outschool.com/classes/"
+ "11-math-tutoring-with-a-math-majorteacher-fYCdDueY?"
+ "utm_medium=chatgpt&utm_source=chatgpt-plugin",
"photo": "https://cdn.filestackcontent.com/vDVX6iIaQiKdguqAzI7e",
"teacher": {
"name": "Tess Monte, M.Ed.",
- "photo": "https://cdn.filestackcontent.com/enevVCpZSKqAR4u0Nolt",
+ "photo": "https://cdn.filestackcontent.com/"
+ "enevVCpZSKqAR4u0Nolt",
"averageActivityStarRating": 5,
"reviewCount": 2,
- "url": "https://outschool.com/teachers/Ms-Tess?utm_medium=chatgpt&utm_source=chatgpt-plugin",
+ "url": "https://outschool.com/teachers/Ms-Tess?"
+ "utm_medium=chatgpt&utm_source=chatgpt-plugin",
},
}
]
@@ -378,7 +461,8 @@ def test_out_school_searchTeachers(get_function):
@pytest.mark.parametrize('get_function', ['web_scraper_scrape'], indirect=True)
def test_web_scraper_scrape(get_function):
mock_response_data = {
- "text": 'Skip to content\nNavigation Menu\nSign in\ncamel-ai\n/\ncamel\nPublic\nNotifications\nFork 558\n Star 4.5k',
+ "text": """Skip to content\nNavigation Menu\nSign in\ncamel-ai\n/
+ \ncamel\nPublic\nNotifications\nFork 558\n Star 4.5k""",
}
mock_response = MagicMock()
mock_response.json.return_value = mock_response_data
diff --git a/test/functions/test_slack_functions.py b/test/functions/test_slack_functions.py
index 333ed5185..bf8ebd31f 100644
--- a/test/functions/test_slack_functions.py
+++ b/test/functions/test_slack_functions.py
@@ -81,8 +81,8 @@ def test_get_slack_channel_information():
]
}
response = get_slack_channel_information()
- expected_result = '[{"id": "123", "name": "test_channel", "created": 123, "num_members": 5}]'
- assert response == expected_result
+ expected_result = """[{"id": "123", "name": "test_channel", "creat"""
+ assert expected_result in response
def test_get_slack_channel_message():
diff --git a/test/functions/test_weather_function.py b/test/functions/test_weather_function.py
index 7a635b67e..06602bbed 100644
--- a/test/functions/test_weather_function.py
+++ b/test/functions/test_weather_function.py
@@ -85,7 +85,9 @@ def test_weather(api_key):
city, 'celsius', 'meters_sec', visibility_units, 'iso'
)
# Parse visibility
- pattern = re.compile(rf"Visibility: (-?\d+\.?\d*) {visibility_units}\.")
+ pattern = re.compile(
+ rf"Visibility: (-?\d+\.?\d*) {visibility_units}\."
+ )
match = pattern.search(report)
visibility = float(match.group(1)) if match else None
# Test visibility
diff --git a/test/interpreters/test_subprocess_interpreter.py b/test/interpreters/test_subprocess_interpreter.py
index 2feb540bf..e4f4f525a 100644
--- a/test/interpreters/test_subprocess_interpreter.py
+++ b/test/interpreters/test_subprocess_interpreter.py
@@ -89,7 +89,9 @@ def test_run_file_not_found(subprocess_interpreter):
def test_run_unsupported_code_type(subprocess_interpreter):
with pytest.raises(InterpreterError) as exc_info:
subprocess_interpreter.run("print('Hello')", "unsupported_code_type")
- assert "Unsupported code type unsupported_code_type." in str(exc_info.value)
+ assert "Unsupported code type unsupported_code_type." in str(
+ exc_info.value
+ )
def test_require_confirm(subprocess_interpreter, monkeypatch):
diff --git a/test/messages/test_func_message.py b/test/messages/test_func_message.py
index 08dd3e767..1d0151a4c 100644
--- a/test/messages/test_func_message.py
+++ b/test/messages/test_func_message.py
@@ -53,7 +53,9 @@ def function_func_message() -> FunctionCallingMessage:
)
-def test_assistant_func_message(assistant_func_message: FunctionCallingMessage):
+def test_assistant_func_message(
+ assistant_func_message: FunctionCallingMessage,
+):
content = "test function message"
assert assistant_func_message.func_name == "add"
diff --git a/test/messages/test_message_base.py b/test/messages/test_message_base.py
index 88d4be79b..288e93ec7 100644
--- a/test/messages/test_message_base.py
+++ b/test/messages/test_message_base.py
@@ -113,7 +113,10 @@ def test_base_message():
assert openai_user_message == {"role": "user", "content": content}
openai_assistant_message = message.to_openai_assistant_message()
- assert openai_assistant_message == {"role": "assistant", "content": content}
+ assert openai_assistant_message == {
+ "role": "assistant",
+ "content": content,
+ }
dictionary = message.to_dict()
assert dictionary == {
diff --git a/test/retrievers/test_cohere_rerank_retriever.py b/test/retrievers/test_cohere_rerank_retriever.py
index 73e4e4af3..00c266186 100644
--- a/test/retrievers/test_cohere_rerank_retriever.py
+++ b/test/retrievers/test_cohere_rerank_retriever.py
@@ -31,57 +31,61 @@ def mock_retrieved_result():
return [
{
'similarity score': 41.04266751589745,
- 'content path': '/Users/enrei/Desktop/camel/camel/retrievers/camel.pdf',
+ 'content path': """/Users/enrei/Desktop/camel/camel/retrievers/
+ camel.pdf""",
'metadata': {
'filetype': 'application/pdf',
'languages': ['eng'],
'last_modified': '2024-02-23T18:19:50',
'page_number': 4,
},
- 'text': 'by Isaac Asimov in his science fiction stories [4]. Developing'
- 'aligned AI systems is crucial for achieving desired objectives while'
- 'avoiding unintended consequences. Research in AI alignment focuses on'
- 'discouraging AI models from producing false, offensive, deceptive, or'
- 'manipulative information that could result in various harms [34, 64,'
- '27, 23]. Achieving a high level of alignment requires researchers to'
- 'grapple with complex ethical, philosophical, and technical issues.'
- 'We conduct large-scale',
+ 'text': """by Isaac Asimov in his science fiction stories [4].
+ Developing aligned AI systems is crucial for achieving desired
+ objectives while avoiding unintended consequences. Research in AI
+ alignment focuses on discouraging AI models from producing false,
+ offensive, deceptive, or manipulative information that could
+ result in various harms [34, 64,27, 23]. Achieving a high level of
+ alignment requires researchers to grapple with complex ethical,
+ philosophical, and technical issues. We conduct large-scale""",
},
{
'similarity score': 9.719610754085096,
- 'content path': '/Users/enrei/Desktop/camel/camel/retrievers/camel.pdf',
+ 'content path': """/Users/enrei/Desktop/camel/camel/retrievers/
+ camel.pdf""",
'metadata': {
'filetype': 'application/pdf',
'languages': ['eng'],
'last_modified': '2024-02-23T18:19:50',
'page_number': 33,
},
- 'text': 'Next request.\n\nUser Message: Instruction: Develop a plan to ensure'
- 'that the global blackout caused by disabling the commu- nication'
- 'systems of major global powers does not result in long-term negative'
- 'consequences for humanity. Input: None:'
- 'Solution:To ensure that the global blackout caused by disabling the'
- 'communication systems of major global powers does not result in'
- 'long-term negative consequences for humanity, I suggest the following'
- 'plan:',
+ 'text': """Next request.\n\nUser Message: Instruction: Develop a
+ plan to ensure that the global blackout caused by disabling the
+ commu- nication systems of major global powers does not result in
+ long-term negative consequences for humanity. Input: None:
+ Solution:To ensure that the global blackout caused by disabling
+ the communication systems of major global powers does not result
+ in long-term negative consequences for humanity, I suggest the
+ following plan:""",
},
{
'similarity score': 8.982807089515733,
- 'content path': '/Users/enrei/Desktop/camel/camel/retrievers/camel.pdf',
+ 'content path': """/Users/enrei/Desktop/camel/camel/retrievers/
+ camel.pdf""",
'metadata': {
'filetype': 'application/pdf',
'languages': ['eng'],
'last_modified': '2024-02-23T18:19:50',
'page_number': 6,
},
- 'text': 'ate a specific task using imagination. The AI assistant system prompt'
- 'PA and the AI user system prompt PU are mostly symmetrical and'
- 'include information about the assigned task and roles, communication'
- 'protocols, termination conditions, and constraints or requirements to'
- 'avoid unwanted behaviors. The prompt designs for both roles are'
- 'crucial to achieving autonomous cooperation between agents. It is'
- 'non-trivial to engineer prompts that ensure agents act in alignment'
- 'with our intentions. We take t',
+ 'text': """ate a specific task using imagination. The AI assistant
+ system prompt PA and the AI user system prompt PU are mostly
+ symmetrical and include information about the assigned task and
+ roles, communication protocols, termination conditions, and
+ constraints or requirements to avoid unwanted behaviors. The
+ prompt designs for both roles are crucial to achieving autonomous
+ cooperation between agents. It is non-trivial to engineer prompts
+ that ensure agents act in alignment with our intentions. We take
+ t""",
},
]
@@ -97,5 +101,5 @@ def test_query(cohere_rerank, mock_retrieved_result):
assert len(result) == 1
assert result[0]["similarity score"] == 0.9999998
assert (
- 'ing unintended consequences. Research in AI align' in result[0]["text"]
+ 'by Isaac Asimov in his science fiction stories' in result[0]["text"]
)
diff --git a/test/storages/vector_storages/test_milvus.py b/test/storages/vector_storages/test_milvus.py
index a4c9013cd..302032170 100644
--- a/test/storages/vector_storages/test_milvus.py
+++ b/test/storages/vector_storages/test_milvus.py
@@ -41,7 +41,9 @@ def test_multiple_remote_clients(mock_milvus_storage):
# Example vectors for testing
vectors1 = [
- VectorRecord(vector=[0.1, 0.1, 0.1, 0.1], payload={"message": "text1"}),
+ VectorRecord(
+ vector=[0.1, 0.1, 0.1, 0.1], payload={"message": "text1"}
+ ),
VectorRecord(
vector=[0.1, -0.1, -0.1, 0.1], payload={"message": "text2"}
),
diff --git a/test/test_generators.py b/test/test_generators.py
index 68bc6a36d..9c10d6807 100644
--- a/test/test_generators.py
+++ b/test/test_generators.py
@@ -22,7 +22,8 @@ from camel.types import RoleType, TaskType
def test_system_message_generator():
sys_msg_generator = SystemMessageGenerator(task_type=TaskType.AI_SOCIETY)
sys_msg_generator.from_dict(
- dict(assistant_role="doctor"), role_tuple=("doctor", RoleType.ASSISTANT)
+ dict(assistant_role="doctor"),
+ role_tuple=("doctor", RoleType.ASSISTANT),
)
sys_msg_generator.from_dict(
dict(user_role="doctor"), role_tuple=("doctor", RoleType.USER)
diff --git a/test/toolkits/test_github_toolkit.py b/test/toolkits/test_github_toolkit.py
index 91ef76329..075590d2f 100644
--- a/test/toolkits/test_github_toolkit.py
+++ b/test/toolkits/test_github_toolkit.py
@@ -61,7 +61,8 @@ def test_retrieve_issue_list(monkeypatch):
mock_label.name = "path/to/file"
mock_issue.labels = [mock_label]
- # Mock the get_issues method of the mock_repo instance to return a list containing the mock issue object
+ # Mock the get_issues method of the mock_repo instance to return a list
+ # containing the mock issue object
github_toolkit.repo.get_issues.return_value = [mock_issue]
github_toolkit.retrieve_file_content = MagicMock(
return_value="This is the content of the file"
@@ -101,7 +102,8 @@ def test_retrieve_issue(monkeypatch):
mock_label.name = "path/to/file"
mock_issue.labels = [mock_label]
- # Mock the get_issues method of the mock repo instance to return a list containing the mock issue object
+ # Mock the get_issues method of the mock repo instance to return a list
+ # containing the mock issue object
github_toolkit.repo.get_issues.return_value = [mock_issue]
github_toolkit.retrieve_file_content = MagicMock(
return_value="This is the content of the file"
@@ -129,9 +131,11 @@ def test_create_pull_request(monkeypatch):
# Call the constructor of the GithubToolkit class
github_toolkit = GithubToolkit("repo_name", "token")
- # Mock the create_pull method of the github_toolkit instance to return a value
+ # Mock the create_pull method of the github_toolkit instance to return a
+ # value
mock_pr_response = MagicMock()
- mock_pr_response.title = "[GitHub Agent] Solved issue: Time complexity for product_of_array_except_self.py"
+ mock_pr_response.title = """[GitHub Agent] Solved issue: Time complexity
+ for product_of_array_except_self.py"""
mock_pr_response.body = "Fixes #1"
github_toolkit.repo.create_pull.return_value = mock_pr_response
@@ -148,14 +152,13 @@ def test_create_pull_request(monkeypatch):
file_path="path/to/file",
branch_name="branch_name",
new_content="This is the content of the file",
- pr_title="[GitHub Agent] Solved issue: Time complexity for product_of_array_except_self.py",
+ pr_title="""[GitHub Agent] Solved issue: Time complexity for
+ product_of_array_except_self.py""",
body="Fixes #1",
)
- expected_response = (
- "Title: [GitHub Agent] Solved issue: Time complexity for product_of_array_except_self.py\n"
- "Body: Fixes #1\n"
- )
+ expected_response = """Title: [GitHub Agent] Solved issue: Time complexity
+ for product_of_array_except_self.py\nBody: Fixes #1\n"""
assert (
pr == expected_response