-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path__init__.py
More file actions
161 lines (129 loc) · 4.05 KB
/
__init__.py
File metadata and controls
161 lines (129 loc) · 4.05 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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
"""Edgee Gateway SDK for Python"""
import json
import os
from dataclasses import dataclass
from urllib.error import HTTPError
from urllib.request import Request, urlopen
# API Configuration
DEFAULT_BASE_URL = "https://api.edgee.ai"
API_ENDPOINT = "/v1/chat/completions"
@dataclass
class FunctionDefinition:
name: str
description: str | None = None
parameters: dict | None = None
@dataclass
class Tool:
type: str # "function"
function: FunctionDefinition
@dataclass
class ToolCall:
id: str
type: str
function: dict # {"name": str, "arguments": str}
@dataclass
class Message:
role: str # "system" | "user" | "assistant" | "tool"
content: str | None = None
name: str | None = None
tool_calls: list[ToolCall] | None = None
tool_call_id: str | None = None
@dataclass
class InputObject:
messages: list[dict]
tools: list[dict] | None = None
tool_choice: str | dict | None = None
@dataclass
class Choice:
index: int
message: dict
finish_reason: str | None
@dataclass
class Usage:
prompt_tokens: int
completion_tokens: int
total_tokens: int
@dataclass
class SendResponse:
choices: list[Choice]
usage: Usage | None = None
@dataclass
class EdgeeConfig:
api_key: str | None = None
base_url: str | None = None
class Edgee:
def __init__(
self,
config: str | EdgeeConfig | dict | None = None,
):
if isinstance(config, str):
# Backward compatibility: accept api_key as string
api_key = config
base_url = None
elif isinstance(config, EdgeeConfig):
api_key = config.api_key
base_url = config.base_url
elif isinstance(config, dict):
api_key = config.get("api_key")
base_url = config.get("base_url")
else:
api_key = None
base_url = None
self.api_key = api_key or os.environ.get("EDGEE_API_KEY", "")
if not self.api_key:
raise ValueError("EDGEE_API_KEY is not set")
self.base_url = base_url or os.environ.get("EDGEE_BASE_URL", DEFAULT_BASE_URL)
def send(
self,
model: str,
input: str | InputObject | dict,
) -> SendResponse:
"""Send a completion request to the Edgee AI Gateway."""
if isinstance(input, str):
messages = [{"role": "user", "content": input}]
tools = None
tool_choice = None
elif isinstance(input, InputObject):
messages = input.messages
tools = input.tools
tool_choice = input.tool_choice
else:
messages = input.get("messages", [])
tools = input.get("tools")
tool_choice = input.get("tool_choice")
body: dict = {"model": model, "messages": messages}
if tools:
body["tools"] = tools
if tool_choice:
body["tool_choice"] = tool_choice
request = Request(
f"{self.base_url}{API_ENDPOINT}",
data=json.dumps(body).encode("utf-8"),
headers={
"Content-Type": "application/json",
"Authorization": f"Bearer {self.api_key}",
},
method="POST",
)
try:
with urlopen(request) as response:
data = json.loads(response.read().decode("utf-8"))
except HTTPError as e:
error_body = e.read().decode("utf-8")
raise RuntimeError(f"API error {e.code}: {error_body}") from e
choices = [
Choice(
index=c["index"],
message=c["message"],
finish_reason=c.get("finish_reason"),
)
for c in data["choices"]
]
usage = None
if "usage" in data:
usage = Usage(
prompt_tokens=data["usage"]["prompt_tokens"],
completion_tokens=data["usage"]["completion_tokens"],
total_tokens=data["usage"]["total_tokens"],
)
return SendResponse(choices=choices, usage=usage)