Skip to content

Commit e0cbbfe

Browse files
committed
🧹 black cleanup
1 parent c8866ac commit e0cbbfe

File tree

14 files changed

+156
-132
lines changed

14 files changed

+156
-132
lines changed

codeinterpreterapi/callbacks.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ class CodeCallbackHandler(AsyncIteratorCallbackHandler):
1111
def __init__(self, session: "CodeInterpreterSession"):
1212
self.session = session
1313
super().__init__()
14-
14+
1515
async def on_agent_action(
1616
self,
1717
action: AgentAction,
@@ -26,4 +26,4 @@ async def on_agent_action(
2626
f"⚙️ Running code: ```python\n{action.tool_input['code']}\n```" # type: ignore
2727
)
2828
else:
29-
raise ValueError(f"Unknown action: {action.tool}")
29+
raise ValueError(f"Unknown action: {action.tool}")

codeinterpreterapi/chains/functions_agent.py

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -105,9 +105,11 @@ def _format_intermediate_steps(
105105
messages.extend(_convert_agent_action_to_messages(agent_action, observation))
106106

107107
return messages
108-
109108

110-
async def _parse_ai_message(message: BaseMessage, llm: BaseLanguageModel) -> Union[AgentAction, AgentFinish]:
109+
110+
async def _parse_ai_message(
111+
message: BaseMessage, llm: BaseLanguageModel
112+
) -> Union[AgentAction, AgentFinish]:
111113
"""Parse an AI message."""
112114
if not isinstance(message, AIMessage):
113115
raise TypeError(f"Expected an AI message got {type(message)}")
@@ -117,7 +119,7 @@ async def _parse_ai_message(message: BaseMessage, llm: BaseLanguageModel) -> Uni
117119
if function_call:
118120
function_call = message.additional_kwargs["function_call"]
119121
function_name = function_call["name"]
120-
try:
122+
try:
121123
_tool_input = json.loads(function_call["arguments"])
122124
except JSONDecodeError:
123125
if function_name == "python":
@@ -199,8 +201,9 @@ def input_keys(self) -> List[str]:
199201
def functions(self) -> List[dict]:
200202
return [dict(format_tool_to_openai_function(t)) for t in self.tools]
201203

202-
def plan(self): raise NotImplementedError
203-
204+
def plan(self):
205+
raise NotImplementedError
206+
204207
async def aplan(
205208
self,
206209
intermediate_steps: List[Tuple[AgentAction, str]],
@@ -229,7 +232,7 @@ async def aplan(
229232
)
230233
agent_decision = await _parse_ai_message(predicted_message, self.llm)
231234
return agent_decision
232-
235+
233236
@classmethod
234237
def create_prompt(
235238
cls,

codeinterpreterapi/chains/modifications_check.py

Lines changed: 20 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -18,28 +18,27 @@
1818
prompt = ChatPromptTemplate(
1919
input_variables=["code"],
2020
messages=[
21-
SystemMessage(content=
22-
"The user will input some code and you will need to determine if the code makes any changes to the file system. \n"
21+
SystemMessage(
22+
content="The user will input some code and you will need to determine if the code makes any changes to the file system. \n"
2323
"With changes it means creating new files or modifying exsisting ones.\n"
2424
"Answer with a function call `determine_modifications` and list them inside.\n"
2525
"If the code does not make any changes to the file system, still answer with the function call but return an empty list.\n",
2626
),
27-
HumanMessagePromptTemplate.from_template("{code}")
28-
]
27+
HumanMessagePromptTemplate.from_template("{code}"),
28+
],
2929
)
3030

3131
functions = [
3232
{
3333
"name": "determine_modifications",
34-
"description":
35-
"Based on code of the user determine if the code makes any changes to the file system. \n"
36-
"With changes it means creating new files or modifying exsisting ones.\n",
34+
"description": "Based on code of the user determine if the code makes any changes to the file system. \n"
35+
"With changes it means creating new files or modifying exsisting ones.\n",
3736
"parameters": {
3837
"type": "object",
3938
"properties": {
4039
"modifications": {
4140
"type": "array",
42-
"items": { "type": "string" },
41+
"items": {"type": "string"},
4342
"description": "The filenames that are modified by the code.",
4443
},
4544
},
@@ -50,30 +49,30 @@
5049

5150

5251
async def get_file_modifications(
53-
code: str,
52+
code: str,
5453
llm: BaseLanguageModel,
5554
retry: int = 2,
5655
) -> List[str] | None:
57-
if retry < 1:
56+
if retry < 1:
5857
return None
5958
messages = prompt.format_prompt(code=code).to_messages()
6059
message = await llm.apredict_messages(messages, functions=functions)
61-
60+
6261
if not isinstance(message, AIMessage):
6362
raise OutputParserException("Expected an AIMessage")
64-
63+
6564
function_call = message.additional_kwargs.get("function_call", None)
66-
65+
6766
if function_call is None:
68-
return await get_file_modifications(code, llm, retry=retry-1)
69-
else:
67+
return await get_file_modifications(code, llm, retry=retry - 1)
68+
else:
7069
function_call = json.loads(function_call["arguments"])
7170
return function_call["modifications"]
72-
71+
7372

7473
async def test():
7574
llm = ChatOpenAI(model="gpt-3.5-turbo-0613") # type: ignore
76-
75+
7776
code = """
7877
import matplotlib.pyplot as plt
7978
@@ -89,15 +88,16 @@ async def test():
8988
"""
9089

9190
code2 = "import pandas as pd\n\n# Read the Excel file\ndata = pd.read_excel('Iris.xlsx')\n\n# Convert the data to CSV\ndata.to_csv('Iris.csv', index=False)"
92-
91+
9392
modifications = await get_file_modifications(code2, llm)
94-
93+
9594
print(modifications)
9695

9796

9897
if __name__ == "__main__":
9998
import asyncio
10099
from dotenv import load_dotenv
100+
101101
load_dotenv()
102-
102+
103103
asyncio.run(test())

codeinterpreterapi/chains/remove_download_link.py

Lines changed: 17 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -8,51 +8,54 @@
88
AIMessage,
99
OutputParserException,
1010
SystemMessage,
11-
HumanMessage
11+
HumanMessage,
1212
)
1313

1414

1515
prompt = ChatPromptTemplate(
1616
input_variables=["input_response"],
1717
messages=[
18-
SystemMessage(content=
19-
"The user will send you a response and you need to remove the download link from it.\n"
18+
SystemMessage(
19+
content="The user will send you a response and you need to remove the download link from it.\n"
2020
"Reformat the remaining message so no whitespace or half sentences are still there.\n"
2121
"If the response does not contain a download link, return the response as is.\n"
2222
),
23-
HumanMessage(content="The dataset has been successfully converted to CSV format. You can download the converted file [here](sandbox:/Iris.csv)."),
23+
HumanMessage(
24+
content="The dataset has been successfully converted to CSV format. You can download the converted file [here](sandbox:/Iris.csv)."
25+
),
2426
AIMessage(content="The dataset has been successfully converted to CSV format."),
25-
HumanMessagePromptTemplate.from_template("{input_response}")
26-
]
27+
HumanMessagePromptTemplate.from_template("{input_response}"),
28+
],
2729
)
2830

2931

3032
async def remove_download_link(
31-
input_response: str,
33+
input_response: str,
3234
llm: BaseLanguageModel,
3335
) -> str:
3436
messages = prompt.format_prompt(input_response=input_response).to_messages()
3537
message = await llm.apredict_messages(messages)
36-
38+
3739
if not isinstance(message, AIMessage):
3840
raise OutputParserException("Expected an AIMessage")
39-
41+
4042
return message.content
41-
43+
4244

4345
async def test():
4446
llm = ChatOpenAI(model="gpt-3.5-turbo-0613") # type: ignore
45-
47+
4648
example = "I have created the plot to your dataset.\n\nLink to the file [here](sandbox:/plot.png)."
47-
49+
4850
modifications = await remove_download_link(example, llm)
49-
51+
5052
print(modifications)
5153

5254

5355
if __name__ == "__main__":
5456
import asyncio
5557
import dotenv
58+
5659
dotenv.load_dotenv()
57-
60+
5861
asyncio.run(test())

codeinterpreterapi/config.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,10 +9,11 @@ class CodeInterpreterAPISettings(BaseSettings):
99
"""
1010
CodeInterpreter API Config
1111
"""
12+
1213
VERBOSE: bool = False
13-
14+
1415
CODEBOX_API_KEY: str | None = None
1516
OPENAI_API_KEY: str | None = None
16-
17+
1718

1819
settings = CodeInterpreterAPISettings()
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
from .system_message import system_message as code_interpreter_system_message
1+
from .system_message import system_message as code_interpreter_system_message

codeinterpreterapi/prompts/system_message.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
from langchain.schema import SystemMessage
22

33

4-
system_message = SystemMessage(content="""
4+
system_message = SystemMessage(
5+
content="""
56
Assistant is 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.
67
As a language model, Assistant is able to generate human-like text based on the input it receives, allowing it to engage in natural-sounding conversations and provide responses that are coherent and relevant to the topic at hand.
78
Assistant is constantly learning and improving, and its capabilities are constantly evolving.
@@ -13,4 +14,5 @@
1314
Tell the human if they use the code interpreter incorrectly.
1415
Already installed packages are: (numpy pandas matplotlib seaborn scikit-learn yfinance scipy statsmodels sympy bokeh plotly dash networkx).
1516
If you encounter an error, try again and fix the code.
16-
""")
17+
"""
18+
)

codeinterpreterapi/schema/file.py

Lines changed: 20 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -5,53 +5,58 @@
55
class File(BaseModel):
66
name: str
77
content: bytes
8-
8+
99
@classmethod
1010
def from_path(cls, path: str):
1111
with open(path, "rb") as f:
1212
path = path.split("/")[-1]
1313
return cls(name=path, content=f.read())
14-
15-
@classmethod
14+
15+
@classmethod
1616
async def afrom_path(cls, path: str):
17-
await asyncio.to_thread(cls.from_path, path)
18-
17+
await asyncio.to_thread(cls.from_path, path)
18+
1919
@classmethod
2020
def from_url(cls, url: str):
2121
import requests # type: ignore
22+
2223
r = requests.get(url)
2324
return cls(name=url.split("/")[-1], content=r.content)
24-
25+
2526
@classmethod
2627
async def afrom_url(cls, url: str):
2728
import aiohttp
29+
2830
async with aiohttp.ClientSession() as session:
2931
async with session.get(url) as r:
3032
return cls(name=url.split("/")[-1], content=await r.read())
31-
33+
3234
def save(self, path: str):
3335
with open(path, "wb") as f:
3436
f.write(self.content)
35-
37+
3638
async def asave(self, path: str):
3739
await asyncio.to_thread(self.save, path)
38-
40+
3941
def show_image(self):
4042
try:
4143
from PIL import Image # type: ignore
4244
except ImportError:
43-
print("Please install it with `pip install codeinterpreterapi[image_support]` to display images.")
45+
print(
46+
"Please install it with `pip install codeinterpreterapi[image_support]` to display images."
47+
)
4448
exit(1)
45-
49+
4650
from io import BytesIO
51+
4752
img_io = BytesIO(self.content)
4853
img = Image.open(img_io)
49-
54+
5055
# Display the image
5156
img.show()
52-
57+
5358
def __str__(self):
5459
return self.name
55-
60+
5661
def __repr__(self):
57-
return f"File(name={self.name})"
62+
return f"File(name={self.name})"

codeinterpreterapi/schema/input.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
from pydantic import BaseModel
22

33

4-
class CodeInput(BaseModel):
4+
class CodeInput(BaseModel):
55
code: str
6-
76

8-
class FileInput(BaseModel):
7+
8+
class FileInput(BaseModel):
99
filename: str

codeinterpreterapi/schema/response.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,21 +4,21 @@
44

55
class UserRequest(HumanMessage):
66
files: list[File] = []
7-
7+
88
def __str__(self):
99
return self.content
10-
10+
1111
def __repr__(self):
1212
return f"UserRequest(content={self.content}, files={self.files})"
1313

1414

1515
class CodeInterpreterResponse(AIMessage):
1616
files: list[File] = []
17-
# final_code: str = "" TODO: implement
17+
# final_code: str = "" TODO: implement
1818
# final_output: str = "" TODO: implement
19-
19+
2020
def __str__(self):
2121
return self.content
22-
22+
2323
def __repr__(self):
24-
return f"CodeInterpreterResponse(content={self.content}, files={self.files})"
24+
return f"CodeInterpreterResponse(content={self.content}, files={self.files})"

0 commit comments

Comments
 (0)