-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathai_response.py
More file actions
47 lines (38 loc) · 1.62 KB
/
Copy pathai_response.py
File metadata and controls
47 lines (38 loc) · 1.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import sys
import json
import requests
# Helped by Arohan
OLLAMA_API_URL = "http://localhost:11434/v1/chat/completions"
def stream_ollama_response(message):
payload = {
"messages": [{"role": "user", "content": message}],
"model": "qwen2.5-coder",
"stream": True
}
response = requests.post(OLLAMA_API_URL, json=payload, stream=True)
if response.status_code != 200:
print(json.dumps({"error": f"Error {response.status_code}"}))
sys.stdout.flush()
return
buffer = ""
for chunk in response.iter_content(chunk_size=None, decode_unicode=True):
if chunk:
buffer += chunk
lines = buffer.split("\n")
for line in lines[:-1]: # Process complete lines
if line.strip() == "":
continue
if line.startswith("data: "):
line = line[6:] # Remove "data: " prefix
try:
json_data = json.loads(line)
content = json_data.get("choices", [{}])[0].get("delta", {}).get("content", "")
formatted_content = content.replace("\n", "<br>").replace("\t", " ")
print(json.dumps({"data": formatted_content}))
sys.stdout.flush()
except json.JSONDecodeError:
break
buffer = lines[-1]
if __name__ == "__main__":
user_message = sys.argv[1] if len(sys.argv) > 1 else ""
stream_ollama_response(user_message)