Hansimov commited on
Commit
7835035
1 Parent(s): e4f31be

:gem: [Feature] Working example with httpx post

Browse files
Files changed (1) hide show
  1. examples/chat_with_post.py +57 -0
examples/chat_with_post.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import ast
2
+ import httpx
3
+ import json
4
+ import re
5
+
6
+
7
+ chat_api = "http://localhost:22222"
8
+ api_key = "sk-xxxxx"
9
+ requests_headers = {}
10
+
11
+ requests_payload = {
12
+ "model": "precise",
13
+ "messages": [
14
+ {
15
+ "role": "user",
16
+ "content": "search and tell me today's weather of california",
17
+ }
18
+ ],
19
+ "stream": True,
20
+ "invocation_id": 1,
21
+ }
22
+
23
+ with httpx.stream(
24
+ "POST",
25
+ chat_api + "/chat/completions",
26
+ headers=requests_headers,
27
+ json=requests_payload,
28
+ timeout=httpx.Timeout(connect=20, read=60, write=20, pool=None),
29
+ ) as response:
30
+ # https://docs.aiohttp.org/en/stable/streams.html
31
+ # https://github.com/openai/openai-cookbook/blob/main/examples/How_to_stream_completions.ipynb
32
+ response_content = ""
33
+ for line in response.iter_lines():
34
+ remove_patterns = [r"^\s*data:\s*", r"^\s*\[DONE\]\s*"]
35
+ for pattern in remove_patterns:
36
+ line = re.sub(pattern, "", line).strip()
37
+
38
+ if line:
39
+ try:
40
+ line_data = json.loads(line)
41
+ except Exception as e:
42
+ try:
43
+ line_data = ast.literal_eval(line)
44
+ except:
45
+ print(f"Error: {line}")
46
+ raise e
47
+ # print(f"line: {line_data}")
48
+ delta_data = line_data["choices"][0]["delta"]
49
+ finish_reason = line_data["choices"][0]["finish_reason"]
50
+ if "role" in delta_data:
51
+ role = delta_data["role"]
52
+ if "content" in delta_data:
53
+ delta_content = delta_data["content"]
54
+ response_content += delta_content
55
+ print(delta_content, end="", flush=True)
56
+ if finish_reason == "stop":
57
+ print()