Skip to content

Commit e3b42f8

Browse files
committed
Revert "Enhance logging and Unicode handling across the application"
This reverts commit e23b862.
1 parent e23b862 commit e3b42f8

File tree

10 files changed

+133
-285
lines changed

10 files changed

+133
-285
lines changed

agent-backend/src/main.py

Lines changed: 0 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22
import signal
33
import threading
44
import time
5-
import sys
65

76
from asyncio import CancelledError
87

@@ -13,13 +12,6 @@
1312
from fastapi import FastAPI
1413
from contextlib import asynccontextmanager
1514

16-
# Configure logging to handle Unicode characters properly
17-
logging.basicConfig(
18-
level=logging.INFO,
19-
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
20-
handlers=[logging.StreamHandler(sys.stdout)],
21-
)
22-
2315
app_logger = logging.getLogger("app")
2416

2517
app_logger.setLevel(LOG_LEVEL.upper())

agent-backend/src/models/sockets.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -45,5 +45,4 @@ def json(self, **kwargs):
4545
# Convert the model to a dictionary and replace enum with its value
4646
d = self.model_dump()
4747
d["event"] = d["event"].value # Convert Enum to string
48-
# Ensure UTF-8 encoding and handle Unicode characters properly
49-
return json.dumps(d, ensure_ascii=False, **kwargs)
48+
return json.dumps(d, **kwargs)

agent-backend/src/redisClient/utilities.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -46,13 +46,14 @@ def insert_hash(self, hash_key: str, key: str, data: list) -> bool:
4646
4747
"""
4848
try:
49-
self.redis_client.hset(hash_key, key, json.dumps(data, ensure_ascii=False))
49+
self.redis_client.hset(hash_key, key, json.dumps(data))
5050
return True
5151
except Exception as err:
5252
logging.exception(err.args[0])
5353
logging.exception(traceback.format_exc())
5454
return False
5555

56+
5657
def get(self, key: str) -> str:
5758
"""
5859
Retrieves the value of a Redis key.
@@ -66,14 +67,13 @@ def get(self, key: str) -> str:
6667
try:
6768
value = self.redis_client.get(key)
6869
if value is not None:
69-
return value.decode("utf-8")
70+
return value.decode('utf-8')
7071
else:
7172
return None
7273
except Exception as err:
7374
logging.exception(err.args[0])
7475
logging.exception(traceback.format_exc())
7576
return None
7677

77-
7878
if __name__ == "__main__":
7979
print(f"Running {__name__}")

agent-backend/src/tools/code_execution_docker_notebook_tool.py

Lines changed: 15 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,19 @@
11
from .code_execution_tool import CodeExecutionTool
22

33
import logging
4+
import os
5+
import pathlib
46
import re
7+
import string
8+
import subprocess
9+
import sys
10+
import time
511
import inspect
612
import json
713

8-
from typing import Dict, Any
14+
from concurrent.futures import ThreadPoolExecutor, TimeoutError
15+
from hashlib import md5
16+
from typing import Callable, Dict, List, Optional, Tuple, Union, Any
917

1018
from io import BytesIO
1119

@@ -22,11 +30,10 @@ def remove_triple_quotes(text):
2230
# Substitute found patterns with an empty string
2331
return re.sub(pattern, "", text)
2432

25-
2633
class CodeExecutionUsingDockerNotebookTool(CodeExecutionTool):
2734

2835
def _run(self, args_str: Dict):
29-
36+
3037
args = json.loads(args_str)
3138
self.execute_function_in_docker(self.function_name, self.code, args)
3239

@@ -141,7 +148,9 @@ def jupyter_execution(code) -> tuple[Optional[str], Union[str, Image.Image]]:
141148
image_list = (
142149
["python:3"]
143150
if use_docker is True
144-
else [use_docker] if isinstance(use_docker, str) else use_docker
151+
else [use_docker]
152+
if isinstance(use_docker, str)
153+
else use_docker
145154
)
146155

147156
# Setup Docker image
@@ -181,11 +190,7 @@ def jupyter_execution(code) -> tuple[Optional[str], Union[str, Image.Image]]:
181190
print(f"Function Execution finished with exit code: {exit_code}")
182191

183192
# Retrieve the logs (output)
184-
try:
185-
logs = container.logs().decode("utf-8").rstrip()
186-
except UnicodeDecodeError:
187-
# Fallback to replace problematic characters
188-
logs = container.logs().decode("utf-8", errors="replace").rstrip()
193+
logs = container.logs().decode("utf-8").rstrip()
189194

190195
# Cleanup
191196
container.remove()
@@ -194,4 +199,4 @@ def jupyter_execution(code) -> tuple[Optional[str], Union[str, Image.Image]]:
194199
return logs
195200
except Exception as e:
196201
logging.exception(e)
197-
raise
202+
raise
Lines changed: 15 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,13 @@
11
import sys
22
from typing import Dict, Type
3+
from langchain.tools import BaseTool
34
import json
45
import subprocess
56

6-
from langchain_core.pydantic_v1 import create_model
7+
from langchain_core.pydantic_v1 import create_model, Field
78
from .global_tools import GlobalBaseTool
89
from models.mongo import Tool
910

10-
1111
class CodeExecutionTool(GlobalBaseTool):
1212
"""
1313
Code execution tool
@@ -16,7 +16,6 @@ class CodeExecutionTool(GlobalBaseTool):
1616
properties_dict (dict): dictionary of tool.data.parameters.properties { proeprty_name: { type: string | number | boolean, ... } }
1717
this dict is used to create a dynamic pydantic model for "args_schema"
1818
"""
19-
2019
name: str = ""
2120
description: str = ""
2221
code: str
@@ -25,10 +24,8 @@ class CodeExecutionTool(GlobalBaseTool):
2524
args_schema: Type = None
2625

2726
def post_init(self):
28-
self.args_schema = create_model(
29-
f"{self.function_name}_model",
30-
**self.convert_args_dict_to_type(self.properties_dict),
31-
)
27+
self.args_schema = create_model(f"{self.function_name}_model", **self.convert_args_dict_to_type(self.properties_dict))
28+
3229

3330
@classmethod
3431
def factory(cls, tool: Tool, **kargs):
@@ -37,40 +34,30 @@ def factory(cls, tool: Tool, **kargs):
3734
description=tool.description,
3835
function_name=tool.data.name,
3936
code=tool.data.code,
40-
properties_dict=(
41-
tool.data.parameters.properties
42-
if tool.data.parameters.properties
43-
else []
44-
),
37+
properties_dict=tool.data.parameters.properties if tool.data.parameters.properties else []
4538
)
4639
code_execution_tool.post_init()
4740
return code_execution_tool
48-
41+
4942
def convert_args_dict_to_type(self, args_schema: Dict):
5043
args_schema_pydantic = dict()
5144
for k, v in args_schema.items():
52-
args_schema_pydantic[k] = (str, None)
45+
args_schema_pydantic[k]=((str, None))
5346
return args_schema_pydantic
54-
47+
5548
def convert_str_args_to_correct_type(self, args):
5649
typed_args = dict()
5750
for k, v in args.items():
5851
prop = self.properties_dict[k]
5952
if prop:
60-
typed_args[k] = (
61-
bool(v)
62-
if prop.type == "boolean"
63-
else (int(v) if prop.type == "integer" else str(v))
64-
)
53+
typed_args[k]=bool(v) if prop.type == "boolean" else (int(v) if prop.type == "integer" else str(v))
6554
return typed_args
66-
55+
6756
def _run(self, args_str: Dict):
6857
args = json.loads(args_str)
6958
typed_args = self.convert_str_args_to_correct_type(args)
7059
indented_code = self.code.replace("\n", "\n ")
71-
function_parameters = ", ".join(
72-
args.keys()
73-
) # Extract the keys as parameter names
60+
function_parameters = ", ".join(args.keys()) # Extract the keys as parameter names
7461
formatted_function = f"""def {self.function_name}({function_parameters}):
7562
{indented_code}
7663
res = {self.function_name}({", ".join([f"{k}={repr(v)}" for k, v in typed_args.items()])})
@@ -79,16 +66,8 @@ def _run(self, args_str: Dict):
7966
if sys.platform != "win32":
8067
formatted_function = formatted_function.replace("\r\n", "\n")
8168
try:
82-
output = subprocess.check_output(
83-
["python", "-c", formatted_function], timeout=5
84-
) # 5 seconds
85-
# Decode output as UTF-8 and handle any encoding issues
86-
try:
87-
decoded_output = output.decode("utf-8")
88-
except UnicodeDecodeError:
89-
# Fallback to replace problematic characters
90-
decoded_output = output.decode("utf-8", errors="replace")
91-
print(decoded_output)
92-
return decoded_output
69+
output = subprocess.check_output(['python', '-c', formatted_function], timeout=5) # 5 seconds
70+
print(output)
71+
return output
9372
except TimeoutError:
94-
return "Not data returned because the call to Code Execution Tool timedout"
73+
return "Not data returned because the call to Code Execution Tool timedout"

agent-backend/src/tools/google_cloud_function.py

Lines changed: 17 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,22 @@
1+
import sys
12
from typing import Dict, Type
3+
from langchain.tools import BaseTool
24
import json
5+
import subprocess
36

47
from init.env_variables import GOOGLE_FUNCTION_LOCATION
5-
from langchain_core.pydantic_v1 import create_model
8+
from langchain_core.pydantic_v1 import create_model, Field
69
from .global_tools import GlobalBaseTool
710
from models.mongo import Tool
811

912

1013
import requests
14+
import os
1115
import google.oauth2.id_token
1216
import google.auth.transport.requests
1317
from google.cloud import logging_v2
1418
from google.api_core.exceptions import GoogleAPIError
1519

16-
1720
class GoogleCloudFunctionTool(GlobalBaseTool):
1821
"""
1922
Google Cloud Function execution tool
@@ -23,7 +26,6 @@ class GoogleCloudFunctionTool(GlobalBaseTool):
2326
properties_dict (dict): dictionary of tool.data.parameters.properties { property_name: { type: string | number | boolean, ... } }
2427
this dict is used to create a dynamic pydantic model for "args_schema"
2528
"""
26-
2729
name: str = ""
2830
description: str = ""
2931
function_name: str
@@ -32,10 +34,7 @@ class GoogleCloudFunctionTool(GlobalBaseTool):
3234
function_id: str = None
3335

3436
def post_init(self):
35-
self.args_schema = create_model(
36-
f"{self.function_name}_model",
37-
**self.convert_args_dict_to_type(self.properties_dict),
38-
)
37+
self.args_schema = create_model(f"{self.function_name}_model", **self.convert_args_dict_to_type(self.properties_dict))
3938

4039
@classmethod
4140
def factory(cls, tool: Tool, **kargs):
@@ -44,16 +43,12 @@ def factory(cls, tool: Tool, **kargs):
4443
description=tool.description,
4544
function_name=tool.data.name,
4645
code=tool.data.code,
47-
properties_dict=(
48-
tool.data.parameters.properties
49-
if tool.data.parameters.properties
50-
else []
51-
),
52-
function_id=str(tool.functionId),
46+
properties_dict=tool.data.parameters.properties if tool.data.parameters.properties else [],
47+
function_id=str(tool.functionId)
5348
)
5449
google_cloud_function_tool.post_init()
5550
return google_cloud_function_tool
56-
51+
5752
def convert_args_dict_to_type(self, args_schema: Dict):
5853
args_schema_pydantic = dict()
5954
for k, v in args_schema.items():
@@ -65,29 +60,25 @@ def convert_str_args_to_correct_type(self, args):
6560
for k, v in args.items():
6661
prop = self.properties_dict.get(k)
6762
if prop:
68-
typed_args[k] = (
69-
bool(v)
70-
if prop.type == "boolean"
71-
else (int(v) if prop.type == "integer" else str(v))
72-
)
63+
typed_args[k] = bool(v) if prop.type == "boolean" else (int(v) if prop.type == "integer" else str(v))
7364
return typed_args
7465

7566
def query_log_entries(self, limit):
7667
client = logging_v2.Client()
7768
filter_str = f'resource.type="cloud_run_revision" severity>=WARNING resource.labels.service_name="function-{self.function_id}"'
7869
try:
7970
entries = client.list_entries(
80-
filter_=filter_str, page_size=limit, order_by="timestamp desc"
71+
filter_=filter_str,
72+
page_size=limit,
73+
order_by='timestamp desc'
8174
)
8275
# Convert entries to a list to access the entries
8376
entries_list = list(entries)
84-
combined_payloads = "\n".join(
85-
entry.payload for entry in entries_list if entry.payload is not None
86-
)
77+
combined_payloads = '\n'.join(entry.payload for entry in entries_list if entry.payload is not None)
8778
return combined_payloads
8879
except GoogleAPIError as e:
8980
print(f"An error occurred: {e}")
90-
return "" # TODO: what is a sensible value here?
81+
return "" # TODO: what is a sensible value here?
9182

9283
def _run(self, **kwargs):
9384
typed_args = self.convert_str_args_to_correct_type(kwargs)
@@ -100,11 +91,8 @@ def _run(self, **kwargs):
10091
TOKEN = google.oauth2.id_token.fetch_id_token(request, audience)
10192
r = requests.post(
10293
audience,
103-
headers={
104-
"Authorization": f"Bearer {TOKEN}",
105-
"Content-Type": "application/json",
106-
},
107-
data=json.dumps(typed_args, ensure_ascii=False),
94+
headers={'Authorization': f"Bearer {TOKEN}", "Content-Type": "application/json"},
95+
data=json.dumps(typed_args)
10896
)
10997
print(f"status code: {r.status_code}")
11098
print(f"response body: {r.text}")

0 commit comments

Comments
 (0)