Spaces:
Sleeping
Sleeping
File size: 6,295 Bytes
1397957 | 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 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 | from typing import Dict, Any, List, Optional, AsyncGenerator
import os
import json
from .provider import BaseProvider, ModelInfo, Message, StreamChunk, ToolCall
class OpenAIProvider(BaseProvider):
def __init__(self, api_key: Optional[str] = None):
self._api_key = api_key or os.environ.get("OPENAI_API_KEY")
self._client = None
@property
def id(self) -> str:
return "openai"
@property
def name(self) -> str:
return "OpenAI"
@property
def models(self) -> Dict[str, ModelInfo]:
return {
"gpt-4o": ModelInfo(
id="gpt-4o",
name="GPT-4o",
provider_id="openai",
context_limit=128000,
output_limit=16384,
supports_tools=True,
supports_streaming=True,
cost_input=2.5,
cost_output=10.0,
),
"gpt-4o-mini": ModelInfo(
id="gpt-4o-mini",
name="GPT-4o Mini",
provider_id="openai",
context_limit=128000,
output_limit=16384,
supports_tools=True,
supports_streaming=True,
cost_input=0.15,
cost_output=0.6,
),
"o1": ModelInfo(
id="o1",
name="o1",
provider_id="openai",
context_limit=200000,
output_limit=100000,
supports_tools=True,
supports_streaming=True,
cost_input=15.0,
cost_output=60.0,
),
}
def _get_client(self):
if self._client is None:
try:
from openai import AsyncOpenAI
self._client = AsyncOpenAI(api_key=self._api_key)
except ImportError:
raise ImportError("openai package is required. Install with: pip install openai")
return self._client
async def stream(
self,
model_id: str,
messages: List[Message],
tools: Optional[List[Dict[str, Any]]] = None,
system: Optional[str] = None,
temperature: Optional[float] = None,
max_tokens: Optional[int] = None,
) -> AsyncGenerator[StreamChunk, None]:
client = self._get_client()
openai_messages = []
if system:
openai_messages.append({"role": "system", "content": system})
for msg in messages:
content = msg.content
if isinstance(content, str):
openai_messages.append({"role": msg.role, "content": content})
else:
openai_messages.append({
"role": msg.role,
"content": [{"type": c.type, "text": c.text} for c in content if c.text]
})
kwargs: Dict[str, Any] = {
"model": model_id,
"messages": openai_messages,
"stream": True,
}
if max_tokens:
kwargs["max_tokens"] = max_tokens
if temperature is not None:
kwargs["temperature"] = temperature
if tools:
kwargs["tools"] = [
{
"type": "function",
"function": {
"name": t["name"],
"description": t.get("description", ""),
"parameters": t.get("parameters", t.get("input_schema", {}))
}
}
for t in tools
]
tool_calls: Dict[int, Dict[str, Any]] = {}
usage_data = None
finish_reason = None
async for chunk in await client.chat.completions.create(**kwargs):
if chunk.choices and chunk.choices[0].delta:
delta = chunk.choices[0].delta
if delta.content:
yield StreamChunk(type="text", text=delta.content)
if delta.tool_calls:
for tc in delta.tool_calls:
idx = tc.index
if idx not in tool_calls:
tool_calls[idx] = {
"id": tc.id or "",
"name": tc.function.name if tc.function else "",
"arguments": ""
}
if tc.id:
tool_calls[idx]["id"] = tc.id
if tc.function:
if tc.function.name:
tool_calls[idx]["name"] = tc.function.name
if tc.function.arguments:
tool_calls[idx]["arguments"] += tc.function.arguments
if chunk.choices and chunk.choices[0].finish_reason:
finish_reason = chunk.choices[0].finish_reason
if chunk.usage:
usage_data = {
"input_tokens": chunk.usage.prompt_tokens,
"output_tokens": chunk.usage.completion_tokens,
}
for tc_data in tool_calls.values():
try:
args = json.loads(tc_data["arguments"]) if tc_data["arguments"] else {}
except json.JSONDecodeError:
args = {}
yield StreamChunk(
type="tool_call",
tool_call=ToolCall(
id=tc_data["id"],
name=tc_data["name"],
arguments=args
)
)
stop_reason = self._map_stop_reason(finish_reason)
yield StreamChunk(type="done", usage=usage_data, stop_reason=stop_reason)
def _map_stop_reason(self, openai_finish_reason: Optional[str]) -> str:
mapping = {
"stop": "end_turn",
"tool_calls": "tool_calls",
"length": "max_tokens",
"content_filter": "end_turn",
}
return mapping.get(openai_finish_reason or "", "end_turn")
|