22import httpx
33import orjson
44
5+ API_URL = "http://localhost:8000/chat/"
6+
7+
58async def chat_with_endpoint ():
69 async with httpx .AsyncClient () as client :
710 while True :
8- # Get user input
911 prompt = input ("\n You: " )
1012 if prompt .lower () == "exit" :
1113 break
1214
13- # Send request to the API
1415 print ("\n Model: " , end = "" , flush = True )
15- async with client .stream (
16- "POST" ,
17- "http://localhost:8000/chat/" ,
18- data = {"prompt" : prompt },
19- timeout = 60
20- ) as response :
21- async for chunk in response .aiter_lines ():
22- if chunk :
16+ try :
17+ async with client .stream ("POST" , API_URL , data = {"prompt" : prompt }, timeout = 60 ) as response :
18+ async for chunk in response .aiter_lines ():
19+ if not chunk :
20+ continue
21+
2322 try :
24- data = orjson .loads (chunk )
25- print (data ["content" ], end = "" , flush = True )
23+ print (orjson .loads (chunk )["content" ], end = "" , flush = True )
2624 except Exception as e :
2725 print (f"\n Error parsing chunk: { e } " )
26+ except httpx .RequestError as e :
27+ print (f"\n Connection error: { e } " )
28+
2829
2930if __name__ == "__main__" :
30- anyio .run (chat_with_endpoint )
31+ anyio .run (chat_with_endpoint )
0 commit comments