1
1
import json
2
2
from typing import Any
3
3
4
- import httpx
5
-
6
4
from .utils import convert_dict_keys_to_camel_case
7
5
8
6
__all__ = ["_create_session" , "_execute" ]
@@ -73,21 +71,20 @@ async def _create_session(self):
73
71
"x-language" : "python" ,
74
72
}
75
73
76
- client = httpx .AsyncClient (timeout = self .timeout_settings )
77
- async with client :
78
- resp = await client .post (
79
- f"{ self .api_url } /sessions/start" ,
80
- json = payload ,
81
- headers = headers ,
82
- )
83
- if resp .status_code != 200 :
84
- raise RuntimeError (f"Failed to create session: { resp .text } " )
85
- data = resp .json ()
86
- self .logger .debug (f"Session created: { data } " )
87
- if not data .get ("success" ) or "sessionId" not in data .get ("data" , {}):
88
- raise RuntimeError (f"Invalid response format: { resp .text } " )
74
+ # async with self._client:
75
+ resp = await self ._client .post (
76
+ f"{ self .api_url } /sessions/start" ,
77
+ json = payload ,
78
+ headers = headers ,
79
+ )
80
+ if resp .status_code != 200 :
81
+ raise RuntimeError (f"Failed to create session: { resp .text } " )
82
+ data = resp .json ()
83
+ self .logger .debug (f"Session created: { data } " )
84
+ if not data .get ("success" ) or "sessionId" not in data .get ("data" , {}):
85
+ raise RuntimeError (f"Invalid response format: { resp .text } " )
89
86
90
- self .session_id = data ["data" ]["sessionId" ]
87
+ self .session_id = data ["data" ]["sessionId" ]
91
88
92
89
93
90
async def _execute (self , method : str , payload : dict [str , Any ]) -> Any :
@@ -109,65 +106,61 @@ async def _execute(self, method: str, payload: dict[str, Any]) -> Any:
109
106
# Convert snake_case keys to camelCase for the API
110
107
modified_payload = convert_dict_keys_to_camel_case (payload )
111
108
112
- client = httpx .AsyncClient (timeout = self .timeout_settings )
113
-
114
- async with client :
115
- try :
116
- # Always use streaming for consistent log handling
117
- async with client .stream (
118
- "POST" ,
119
- f"{ self .api_url } /sessions/{ self .session_id } /{ method } " ,
120
- json = modified_payload ,
121
- headers = headers ,
122
- ) as response :
123
- if response .status_code != 200 :
124
- error_text = await response .aread ()
125
- error_message = error_text .decode ("utf-8" )
126
- self .logger .error (
127
- f"[HTTP ERROR] Status { response .status_code } : { error_message } "
128
- )
129
- raise RuntimeError (
130
- f"Request failed with status { response .status_code } : { error_message } "
131
- )
132
- result = None
133
-
134
- async for line in response .aiter_lines ():
135
- # Skip empty lines
136
- if not line .strip ():
137
- continue
138
-
139
- try :
140
- # Handle SSE-style messages that start with "data: "
141
- if line .startswith ("data: " ):
142
- line = line [len ("data: " ) :]
143
-
144
- message = json .loads (line )
145
- # Handle different message types
146
- msg_type = message .get ("type" )
147
-
148
- if msg_type == "system" :
149
- status = message .get ("data" , {}).get ("status" )
150
- if status == "error" :
151
- error_msg = message .get ("data" , {}).get (
152
- "error" , "Unknown error"
153
- )
154
- self .logger .error (f"[ERROR] { error_msg } " )
155
- raise RuntimeError (
156
- f"Server returned error: { error_msg } "
157
- )
158
- elif status == "finished" :
159
- result = message .get ("data" , {}).get ("result" )
160
- elif msg_type == "log" :
161
- # Process log message using _handle_log
162
- await self ._handle_log (message )
163
- else :
164
- # Log any other message types
165
- self .logger .debug (f"[UNKNOWN] Message type: { msg_type } " )
166
- except json .JSONDecodeError :
167
- self .logger .warning (f"Could not parse line as JSON: { line } " )
168
-
169
- # Return the final result
170
- return result
171
- except Exception as e :
172
- self .logger .error (f"[EXCEPTION] { str (e )} " )
173
- raise
109
+ # async with self._client:
110
+ try :
111
+ # Always use streaming for consistent log handling
112
+ async with self ._client .stream (
113
+ "POST" ,
114
+ f"{ self .api_url } /sessions/{ self .session_id } /{ method } " ,
115
+ json = modified_payload ,
116
+ headers = headers ,
117
+ ) as response :
118
+ if response .status_code != 200 :
119
+ error_text = await response .aread ()
120
+ error_message = error_text .decode ("utf-8" )
121
+ self .logger .error (
122
+ f"[HTTP ERROR] Status { response .status_code } : { error_message } "
123
+ )
124
+ raise RuntimeError (
125
+ f"Request failed with status { response .status_code } : { error_message } "
126
+ )
127
+ result = None
128
+
129
+ async for line in response .aiter_lines ():
130
+ # Skip empty lines
131
+ if not line .strip ():
132
+ continue
133
+
134
+ try :
135
+ # Handle SSE-style messages that start with "data: "
136
+ if line .startswith ("data: " ):
137
+ line = line [len ("data: " ) :]
138
+
139
+ message = json .loads (line )
140
+ # Handle different message types
141
+ msg_type = message .get ("type" )
142
+
143
+ if msg_type == "system" :
144
+ status = message .get ("data" , {}).get ("status" )
145
+ if status == "error" :
146
+ error_msg = message .get ("data" , {}).get (
147
+ "error" , "Unknown error"
148
+ )
149
+ self .logger .error (f"[ERROR] { error_msg } " )
150
+ raise RuntimeError (f"Server returned error: { error_msg } " )
151
+ elif status == "finished" :
152
+ result = message .get ("data" , {}).get ("result" )
153
+ elif msg_type == "log" :
154
+ # Process log message using _handle_log
155
+ await self ._handle_log (message )
156
+ else :
157
+ # Log any other message types
158
+ self .logger .debug (f"[UNKNOWN] Message type: { msg_type } " )
159
+ except json .JSONDecodeError :
160
+ self .logger .error (f"Could not parse line as JSON: { line } " )
161
+
162
+ # Return the final result
163
+ return result
164
+ except Exception as e :
165
+ self .logger .error (f"[EXCEPTION] { str (e )} " )
166
+ raise
0 commit comments