Spaces:
Runtime error
Runtime error
Commit
·
da1009f
1
Parent(s):
9814b43
fixing pydantic issue v11
Browse files- main/api.py +35 -24
main/api.py
CHANGED
@@ -14,20 +14,25 @@ class InferenceApi(LitAPI):
|
|
14 |
super().__init__()
|
15 |
self.logger = logging.getLogger(__name__)
|
16 |
self.logger.info("Initializing Inference API")
|
17 |
-
self.
|
|
|
18 |
|
19 |
async def setup(self, device: Optional[str] = None):
|
20 |
-
"""Setup method required by LitAPI
|
21 |
self._device = device
|
22 |
-
self.
|
23 |
-
|
|
|
|
|
|
|
|
|
24 |
timeout=60.0
|
25 |
)
|
26 |
-
self.logger.info(f"Inference API setup completed on device: {device}")
|
27 |
|
28 |
def predict(self, x: str, **kwargs) -> Iterator[str]:
|
29 |
"""
|
30 |
Non-async prediction method that yields results.
|
|
|
31 |
"""
|
32 |
loop = asyncio.get_event_loop()
|
33 |
async def async_gen():
|
@@ -53,17 +58,21 @@ class InferenceApi(LitAPI):
|
|
53 |
yield response
|
54 |
|
55 |
def decode_request(self, request: Any, **kwargs) -> str:
|
56 |
-
"""
|
|
|
|
|
|
|
57 |
if isinstance(request, dict) and "prompt" in request:
|
58 |
return request["prompt"]
|
59 |
return request
|
60 |
|
61 |
def encode_response(self, output: Iterator[str], **kwargs) -> Dict[str, Any]:
|
62 |
-
"""
|
63 |
-
|
|
|
|
|
64 |
if self.stream:
|
65 |
return {"generated_text": output}
|
66 |
-
# For non-streaming, take the first (and only) item from the iterator
|
67 |
try:
|
68 |
result = next(output)
|
69 |
return {"generated_text": result}
|
@@ -80,17 +89,18 @@ class InferenceApi(LitAPI):
|
|
80 |
self.logger.debug(f"Forwarding generation request for prompt: {prompt[:50]}...")
|
81 |
|
82 |
try:
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
|
|
94 |
|
95 |
except Exception as e:
|
96 |
self.logger.error(f"Error in generate_response: {str(e)}")
|
@@ -106,7 +116,8 @@ class InferenceApi(LitAPI):
|
|
106 |
self.logger.debug(f"Forwarding streaming request for prompt: {prompt[:50]}...")
|
107 |
|
108 |
try:
|
109 |
-
|
|
|
110 |
"POST",
|
111 |
"/api/v1/generate/stream",
|
112 |
json={
|
@@ -118,12 +129,12 @@ class InferenceApi(LitAPI):
|
|
118 |
response.raise_for_status()
|
119 |
async for chunk in response.aiter_text():
|
120 |
yield chunk
|
|
|
121 |
|
122 |
except Exception as e:
|
123 |
self.logger.error(f"Error in generate_stream: {str(e)}")
|
124 |
raise
|
125 |
|
126 |
async def cleanup(self):
|
127 |
-
"""Cleanup method -
|
128 |
-
|
129 |
-
await self.client.aclose()
|
|
|
14 |
super().__init__()
|
15 |
self.logger = logging.getLogger(__name__)
|
16 |
self.logger.info("Initializing Inference API")
|
17 |
+
self._device = None
|
18 |
+
self.stream = False # Add stream flag for compatibility with LitAPI
|
19 |
|
20 |
async def setup(self, device: Optional[str] = None):
|
21 |
+
"""Setup method required by LitAPI"""
|
22 |
self._device = device
|
23 |
+
self.logger.info(f"Inference API setup completed on device: {device}")
|
24 |
+
|
25 |
+
async def _get_client(self):
|
26 |
+
"""Get or create HTTP client as needed"""
|
27 |
+
return httpx.AsyncClient(
|
28 |
+
base_url="http://localhost:8002",
|
29 |
timeout=60.0
|
30 |
)
|
|
|
31 |
|
32 |
def predict(self, x: str, **kwargs) -> Iterator[str]:
|
33 |
"""
|
34 |
Non-async prediction method that yields results.
|
35 |
+
Implements required LitAPI method.
|
36 |
"""
|
37 |
loop = asyncio.get_event_loop()
|
38 |
async def async_gen():
|
|
|
58 |
yield response
|
59 |
|
60 |
def decode_request(self, request: Any, **kwargs) -> str:
|
61 |
+
"""
|
62 |
+
Convert the request payload to input format.
|
63 |
+
Implements required LitAPI method.
|
64 |
+
"""
|
65 |
if isinstance(request, dict) and "prompt" in request:
|
66 |
return request["prompt"]
|
67 |
return request
|
68 |
|
69 |
def encode_response(self, output: Iterator[str], **kwargs) -> Dict[str, Any]:
|
70 |
+
"""
|
71 |
+
Convert the model output to a response payload.
|
72 |
+
Implements required LitAPI method.
|
73 |
+
"""
|
74 |
if self.stream:
|
75 |
return {"generated_text": output}
|
|
|
76 |
try:
|
77 |
result = next(output)
|
78 |
return {"generated_text": result}
|
|
|
89 |
self.logger.debug(f"Forwarding generation request for prompt: {prompt[:50]}...")
|
90 |
|
91 |
try:
|
92 |
+
async with await self._get_client() as client:
|
93 |
+
response = await client.post(
|
94 |
+
"/api/v1/generate",
|
95 |
+
json={
|
96 |
+
"prompt": prompt,
|
97 |
+
"system_message": system_message,
|
98 |
+
"max_new_tokens": max_new_tokens
|
99 |
+
}
|
100 |
+
)
|
101 |
+
response.raise_for_status()
|
102 |
+
data = response.json()
|
103 |
+
return data["generated_text"]
|
104 |
|
105 |
except Exception as e:
|
106 |
self.logger.error(f"Error in generate_response: {str(e)}")
|
|
|
116 |
self.logger.debug(f"Forwarding streaming request for prompt: {prompt[:50]}...")
|
117 |
|
118 |
try:
|
119 |
+
client = await self._get_client()
|
120 |
+
async with client.stream(
|
121 |
"POST",
|
122 |
"/api/v1/generate/stream",
|
123 |
json={
|
|
|
129 |
response.raise_for_status()
|
130 |
async for chunk in response.aiter_text():
|
131 |
yield chunk
|
132 |
+
await client.aclose()
|
133 |
|
134 |
except Exception as e:
|
135 |
self.logger.error(f"Error in generate_stream: {str(e)}")
|
136 |
raise
|
137 |
|
138 |
async def cleanup(self):
|
139 |
+
"""Cleanup method - no longer needed as clients are created per-request"""
|
140 |
+
pass
|
|