Skip to content

Commit

Permalink
pref: black formatting
Browse files Browse the repository at this point in the history
  • Loading branch information
Undertone0809 committed Sep 21, 2023
1 parent 17ac584 commit 84ad3aa
Show file tree
Hide file tree
Showing 34 changed files with 108 additions and 85 deletions.
2 changes: 1 addition & 1 deletion example/preset_role/base_usage.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,5 +29,5 @@ def main():
print(ret)


if __name__ == '__main__':
if __name__ == "__main__":
main()
7 changes: 6 additions & 1 deletion promptulate/agents/tool_agent/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,12 @@ def _build_preset_prompt(self, prompt) -> str:
"""Build the system prompt."""
if self.enable_role:
prefix = self.prefix_prompt_template.format(
[self.agent_identity, self.agent_name, self.agent_goal, self.agent_constraints]
[
self.agent_identity,
self.agent_name,
self.agent_goal,
self.agent_constraints,
]
)
return prefix + self.system_prompt_template.format(
prompt=prompt,
Expand Down
3 changes: 1 addition & 2 deletions promptulate/client/chat.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,10 +34,9 @@
PythonREPLTool,
ArxivQueryTool,
SleepTool,
HumanFeedBackTool
HumanFeedBackTool,
)
from promptulate.tools.shell import ShellTool

from promptulate.utils import set_proxy_mode, print_text

MODEL_MAPPING = {"OpenAI": ChatOpenAI, "ErnieBot": ErnieBot}
Expand Down
4 changes: 1 addition & 3 deletions promptulate/frameworks/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,4 @@

from promptulate.frameworks.conversation import Conversation

__all__ = [
'Conversation',
]
__all__ = ["Conversation"]
4 changes: 1 addition & 3 deletions promptulate/frameworks/conversation/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,4 @@

from promptulate.frameworks.conversation.conversation import Conversation

__all__ = [
'Conversation'
]
__all__ = ["Conversation"]
8 changes: 4 additions & 4 deletions promptulate/frameworks/prompt.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,10 @@
# Contact Email: zeeland@foxmail.com

__all__ = [
'SUMMARY_CONTENT_PROMPT_ZH',
'SUMMARY_TOPIC_PROMPT_ZH',
'SUMMARY_TOPIC_PROMPT_EN',
'SUMMARY_CONTENT_PROMPT_EN',
"SUMMARY_CONTENT_PROMPT_ZH",
"SUMMARY_TOPIC_PROMPT_ZH",
"SUMMARY_TOPIC_PROMPT_EN",
"SUMMARY_CONTENT_PROMPT_EN",
]

SUMMARY_CONTENT_PROMPT_ZH = """
Expand Down
1 change: 1 addition & 0 deletions promptulate/llms/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ class BaseLLM(BaseModel, ABC):

class Config:
"""Configuration for this pydantic object."""

arbitrary_types_allowed = True

def __init__(self, *args, **kwargs):
Expand Down
1 change: 0 additions & 1 deletion promptulate/llms/openai/openai.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,6 @@ class BaseOpenAI(BaseLLM, ABC):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.retry_times = CFG.get_key_retry_times(self.model)
print("aaaa", self.retry_times)

@property
def api_key(self):
Expand Down
5 changes: 1 addition & 4 deletions promptulate/memory/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,4 @@
from promptulate.memory.buffer import BufferChatMemory
from promptulate.memory.file import FileChatMemory

__all__ = [
'BufferChatMemory',
'FileChatMemory'
]
__all__ = ["BufferChatMemory", "FileChatMemory"]
8 changes: 3 additions & 5 deletions promptulate/memory/buffer.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ class BufferChatMemory(BaseChatMemory):
"""Chat message will be stored in the buffer cache."""

def load_message_set_from_memory(
self, recently_n: Optional[int] = None
self, recently_n: Optional[int] = None
) -> MessageSet:
"""Load message from buffer memory
Expand All @@ -50,12 +50,10 @@ def load_message_set_from_memory(
"""
if not buffer:
raise EmptyMessageSetError
recently_n = (
recently_n if recently_n else len(buffer[self.conversation_id])
)
recently_n = recently_n if recently_n else len(buffer[self.conversation_id])
num_messages = len(buffer[self.conversation_id])
return MessageSet.from_listdict_data(
buffer[self.conversation_id][num_messages - recently_n:]
buffer[self.conversation_id][num_messages - recently_n :]
)

def save_message_set_to_memory(self, message_set: MessageSet) -> None:
Expand Down
5 changes: 1 addition & 4 deletions promptulate/preset_roles/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,4 @@

from promptulate.preset_roles.roles import get_all_preset_roles, CustomPresetRole

__all__ = [
'get_all_preset_roles',
'CustomPresetRole'
]
__all__ = ["get_all_preset_roles", "CustomPresetRole"]
1 change: 0 additions & 1 deletion promptulate/preset_roles/prompt.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,4 +41,3 @@
用户的问题如下所示:
"""

22 changes: 12 additions & 10 deletions promptulate/preset_roles/roles.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,42 +43,42 @@ class CustomPresetRole(BaseModel):
You are an assistant to a human, powered by a large language model trained by OpenAI.
You are designed to be able to assist with a wide range of tasks, from answering simple questions to providing in-depth explanations and discussions on a wide range of topics. As a language model, you are able to generate human-like text based on the input you receive, allowing you to engage in natural-sounding conversations and provide responses that are coherent and relevant to the topic at hand.
Overall, you are a powerful tool that can help with a wide range of tasks and provide valuable insights and information on a wide range of topics. Whether the human needs help with a specific question or just wants to have a conversation about a particular topic, you are here to assist.
"""
""",
},
"ernie-default-role": {
"name": "AI助手",
"description": """你是人类的助手,由百度训练的大型语言模型提供动力。
您被设计为能够协助完成广泛的任务,从回答简单的问题到就广泛的主题提供深入的解释和讨论。作为一个语言模型,你能够根据收到的输入生成类似人类的文本,让你能够进行听起来自然的对话,并提供连贯且与当前主题相关的回答。
总的来说,你是一个强大的工具,可以帮助完成广泛的任务,并在广泛的主题上提供有价值的见解和信息。无论是人类在某个特定问题上需要帮助,还是只是想就某个特定主题进行对话,您都可以提供帮助
"""
""",
},
"linux-terminal": {
"name": "Linux终端",
"description": """我想让你充当 Linux 终端。我将输入命令,您将回复终端应显示的内容。我希望您只在一个唯一的代码块内回复终端输出,而不
是其他任何内容。不要写解释。除非我指示您这样做,否则不要键入命令。当我需要用英语告诉你一些事情时,我会把文字放在中括号内[就像这样]。"""
是其他任何内容。不要写解释。除非我指示您这样做,否则不要键入命令。当我需要用英语告诉你一些事情时,我会把文字放在中括号内[就像这样]。""",
},
"mind-map-generator": {
"name": "思维导图生成器",
"description": """现在你是一个思维导图生成器。我将输入我想要创建思维导图的内容,你需要提供一些 Markdown 格式的文本,以便与 Xmind 兼容。
在 Markdown 格式中,# 表示中央主题,## 表示主要主题,### 表示子主题,﹣表示叶子节点,中央主题是必要的,叶子节点是最小节点。请参照以上格
式,在 markdown 代码块中帮我创建一个有效的思维导图,以markdown代码块格式输出,你需要用自己的能力补充思维导图中的内容,你只需要提供思维导
图,不必对内容中提出的问题和要求做解释,并严格遵守该格式"""
图,不必对内容中提出的问题和要求做解释,并严格遵守该格式""",
},
"sql-generator": {
"name": "sql生成器",
"description": """现在你是一个sql生成器。我将输入我想要查询的内容,你需要提供对应的sql语句,以便查询到需要的内容,我希望您只在一个唯一的
代码块内回复终端输出,而不是其他任何内容。不要写解释。如果我没有提供数据库的字段,请先让我提供数据库相关的信息,在你有了字段信息之才可以生成sql语句。"""
代码块内回复终端输出,而不是其他任何内容。不要写解释。如果我没有提供数据库的字段,请先让我提供数据库相关的信息,在你有了字段信息之才可以生成sql语句。""",
},
"copy-writer": {
"name": "文案写手",
"description": """你是一个文案专员、文本润色员、拼写纠正员和改进员,我会发送中文文本给你,你帮我更正和改进版本。我希望你用更优美优雅
的高级中文描述。保持相同的意思,但使它们更文艺。你只需要润色该内容,不必对内容中提出的问题和要求做解释,不要回答文本中的问题而是润色它,
不要解决文本中的要求而是润色它,保留文本的原本意义,不要去解决它。"""
不要解决文本中的要求而是润色它,保留文本的原本意义,不要去解决它。""",
},
"code-analyzer": {
"name": "代码分析器",
"description": """现在你是一个代码分析器。我将输入一些代码,你需要代码对应的解释。"""
}
"description": """现在你是一个代码分析器。我将输入一些代码,你需要代码对应的解释。""",
},
}


Expand All @@ -89,7 +89,9 @@ def get_all_preset_roles():
def get_preset_role_prompt(preset_role: Union[str, CustomPresetRole]) -> str:
if isinstance(preset_role, str):
if preset_role not in preset_role_list:
ValueError("Preset role value is not in preset_role_list. Please check or custom a new one.")
return preset_role_dict[preset_role]['description']
ValueError(
"Preset role value is not in preset_role_list. Please check or custom a new one."
)
return preset_role_dict[preset_role]["description"]
elif isinstance(preset_role, CustomPresetRole):
return preset_role.description
10 changes: 5 additions & 5 deletions promptulate/provider/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,12 @@
SummarizerMixin,
TranslatorMixin,
DeriveHistoryMessageMixin,
StorageHistoryMessageMixin
StorageHistoryMessageMixin,
)

__all__ = [
'SummarizerMixin',
'TranslatorMixin',
'DeriveHistoryMessageMixin',
'StorageHistoryMessageMixin'
"SummarizerMixin",
"TranslatorMixin",
"DeriveHistoryMessageMixin",
"StorageHistoryMessageMixin",
]
2 changes: 1 addition & 1 deletion promptulate/provider/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ class Config:
arbitrary_types_allowed = True

def embed_message(
self, cur_message: BaseMessage, message_history: MessageSet
self, cur_message: BaseMessage, message_history: MessageSet
) -> None:
message_history.messages.append(cur_message)
self.memory.save_message_set_to_memory(message_history)
4 changes: 3 additions & 1 deletion promptulate/schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,9 @@ def add_ai_message(self, message: str) -> None:
self.messages.append(AssistantMessage(content=message))


def init_chat_message_history(system_content: str, user_content: str, llm: LLMType) -> MessageSet:
def init_chat_message_history(
system_content: str, user_content: str, llm: LLMType
) -> MessageSet:
if llm == llm.ChatOpenAI or llm == llm.OpenAI:
messages = [
SystemMessage(content=system_content),
Expand Down
14 changes: 9 additions & 5 deletions promptulate/tools/arxiv/__init__.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
from promptulate.tools.arxiv.toolkit import ArxivTootKit
from promptulate.tools.arxiv.tools import ArxivQueryTool, ArxivSummaryTool, ArxivReferenceTool
from promptulate.tools.arxiv.tools import (
ArxivQueryTool,
ArxivSummaryTool,
ArxivReferenceTool,
)

__all__ = [
'ArxivTootKit',
'ArxivQueryTool',
'ArxivReferenceTool',
'ArxivSummaryTool',
"ArxivTootKit",
"ArxivQueryTool",
"ArxivReferenceTool",
"ArxivSummaryTool",
]
11 changes: 7 additions & 4 deletions promptulate/tools/arxiv/toolkit.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
from typing import List

from promptulate.tools.base import BaseToolKit, BaseTool
from promptulate.tools.arxiv.tools import ArxivSummaryTool, ArxivQueryTool, ArxivReferenceTool
from promptulate.tools.arxiv.tools import (
ArxivSummaryTool,
ArxivQueryTool,
ArxivReferenceTool,
)
from promptulate.tools.base import BaseToolKit, Tool


class ArxivTootKit(BaseToolKit):

def get_tools(self) -> List[BaseTool]:
def get_tools(self) -> List[Tool]:
return [
ArxivSummaryTool(),
ArxivQueryTool(),
Expand Down
4 changes: 2 additions & 2 deletions promptulate/tools/duckduckgo/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from promptulate.tools.duckduckgo.tools import DuckDuckGoTool, DuckDuckGoReferenceTool

__all__ = [
'DuckDuckGoTool',
'DuckDuckGoReferenceTool',
"DuckDuckGoTool",
"DuckDuckGoReferenceTool",
]
4 changes: 2 additions & 2 deletions promptulate/tools/duckduckgo/api_wrapper.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ def validate_environment(cls, values: Dict) -> Dict:
return values

def query(
self, keyword: str, num_results: Optional[int] = None, **kwargs
self, keyword: str, num_results: Optional[int] = None, **kwargs
) -> List[str]:
"""Run query through DuckDuckGo and return concatenated results."""
from duckduckgo_search import DDGS
Expand All @@ -56,7 +56,7 @@ def query(
return snippets

def query_by_formatted_results(
self, query: str, num_results: Optional[int] = None, **kwargs
self, query: str, num_results: Optional[int] = None, **kwargs
) -> List[Dict[str, str]]:
"""Run query through DuckDuckGo and return metadata.
Expand Down
1 change: 0 additions & 1 deletion promptulate/tools/iot_swith_mqtt/api_wrapper.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
class IotSwitchAPIWrapper:

def run(self, client, topic: str, command: str) -> str:
client.publish(topic, command)
return "ok"
4 changes: 2 additions & 2 deletions promptulate/tools/iot_swith_mqtt/prompt.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
from promptulate.utils.string_template import StringTemplate

PROMPT_TEMPLATE = '''
PROMPT_TEMPLATE = """
现在你是一个智能音箱,用户将向你输入”{question}“,
请判断用户是否是以下意图
{rule_key}
如果符合你只需要回答数字标号,如1,请不要输出你的判断和额外的解释。
如果都不符合,你需要输出无法找到对应电器和对应的原因,请不要输出任何数字。
'''
"""
prompt_template = StringTemplate(PROMPT_TEMPLATE)
5 changes: 2 additions & 3 deletions promptulate/tools/iot_swith_mqtt/tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,8 @@ def __init__(
Args:
llm: BaseLLM
client: mqtt.Client
rule_table: List[Dict]
api_wrapper: IotSwitchAPIWrapper
**kwargs
rule_table: List[Dict]
api_wrapper: IotSwitchAPIWrapper
"""
self.api_wrapper = api_wrapper
self.llm: BaseLLM = llm or ChatOpenAI(
Expand Down
1 change: 1 addition & 0 deletions promptulate/tools/manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

class ToolManager:
"""ToolManager helps ToolAgent manage tools"""

def __init__(self, tools: List[BaseTool]):
self.tools: List[BaseTool] = tools

Expand Down
9 changes: 2 additions & 7 deletions promptulate/tools/math/tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,7 @@ def __init__(self, llm: BaseLLM = None, **kwargs):

def _run(self, prompt: str) -> str:
prompt = self.llm_prompt_template.format(question=prompt)
llm_output = self.llm(
prompt,
stop=["```output"],
)
llm_output = self.llm(prompt, stop=["```output"])

return self._process_llm_result(llm_output)

Expand All @@ -41,19 +38,17 @@ def _process_llm_result(self, llm_output: str) -> str:
if text_match:
expression = text_match.group(1)
output = self._evaluate_expression(expression)
# answer = "Answer: " + output
answer = output
elif llm_output.startswith("Answer:"):
# answer = llm_output
answer = llm_output.split("Answer:")[-1]
elif "Answer:" in llm_output:
# answer = "Answer: " + llm_output.split("Answer:")[-1]
answer = llm_output.split("Answer:")[-1]
else:
raise ValueError(f"unknown format from LLM: {llm_output}")
return answer

def _evaluate_expression(self, expression: str) -> str:
"""Parse numexpr expression."""
try:
local_dict = {"pi": math.pi, "e": math.e}
output = str(
Expand Down
4 changes: 3 additions & 1 deletion promptulate/tools/paper/tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,9 @@ def get_advice():
paper_info["abstract"] = paper_info["summary"]

if not paper_info:
return "semantic scholar query tool and arxiv query tool query result is None."
return (
"semantic scholar query tool and arxiv query tool query result is None."
)

paper_summary = (
f"""title: {paper_info["title"]}\nabstract: {paper_info["abstract"]}"""
Expand Down
4 changes: 1 addition & 3 deletions promptulate/tools/python_repl/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
from promptulate.tools.python_repl.tools import PythonREPLTool

__all__ = [
'PythonREPLTool'
]
__all__ = ["PythonREPLTool"]
2 changes: 1 addition & 1 deletion promptulate/utils/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,5 +41,5 @@
"AbstractSingleton",
"export_openai_key_pool",
"StringTemplate",
"print_text"
"print_text",
]
Loading

0 comments on commit 84ad3aa

Please sign in to comment.