-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.py
More file actions
88 lines (69 loc) · 2.51 KB
/
Copy pathutils.py
File metadata and controls
88 lines (69 loc) · 2.51 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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
"""Utility functions for working with API responses."""
from typing import Dict, Any, List, Optional
import requests
def extract_chart_from_response(response: Dict[str, Any]) -> Optional[Dict[str, Any]]:
"""Extract the chart image from the API response."""
try:
choice = response["choices"][0]
message = choice["message"]
content = message.get("content", [])
if isinstance(content, list):
for item in content:
if isinstance(item, dict) and item.get("type") == "image_url":
return {
"type": "image_url",
"image_url": item.get("image_url", {})
}
except (KeyError, IndexError, TypeError):
pass
return None
def extract_text_from_response(response: Dict[str, Any]) -> str:
"""Extract the text content from the API response."""
try:
choice = response["choices"][0]
message = choice["message"]
content = message.get("content", "")
if isinstance(content, list):
for item in content:
if isinstance(item, dict) and item.get("type") == "text":
return item.get("text", "")
elif isinstance(content, str):
return content
except (KeyError, IndexError, TypeError):
pass
return ""
def append_ai_message_with_chart(
conversation: List[Dict[str, Any]],
response: Dict[str, Any]
) -> List[Dict[str, Any]]:
"""
Append the AI's response (with chart) to the conversation.
This demonstrates how to properly format the message for OpenAI-compatible
clients that support multimodal content.
"""
choice = response["choices"][0]
message = choice["message"]
# The message already contains the content array with text and image
ai_message = {
"role": message.get("role", "assistant"),
"content": message.get("content", [])
}
conversation.append(ai_message)
return conversation
def make_chat_request(
base_url: str,
messages: List[Dict[str, str]],
model: str = "gpt-3.5-turbo",
stream: bool = False
) -> Dict[str, Any]:
"""Make a chat completion request to the server."""
url = f"{base_url}/v1/chat/completions"
payload = {
"model": model,
"messages": messages,
"stream": stream,
"max_tokens": 100
}
response = requests.post(url, json=payload)
response.raise_for_status()
return response.json()