freelybase 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- freelybase/__init__.py +86 -0
- freelybase/client.py +134 -0
- freelybase/exceptions.py +19 -0
- freelybase/fb_ai.py +267 -0
- freelybase/fb_file.py +150 -0
- freelybase/fb_live_query.py +238 -0
- freelybase/fb_object.py +253 -0
- freelybase/fb_query.py +359 -0
- freelybase/fb_user.py +303 -0
- freelybase/geo_point.py +93 -0
- freelybase/helpers.py +119 -0
- freelybase/query.py +118 -0
- freelybase-1.0.0.dist-info/METADATA +104 -0
- freelybase-1.0.0.dist-info/RECORD +17 -0
- freelybase-1.0.0.dist-info/WHEEL +5 -0
- freelybase-1.0.0.dist-info/licenses/LICENSE +21 -0
- freelybase-1.0.0.dist-info/top_level.txt +1 -0
freelybase/__init__.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
"""
|
|
2
|
+
FreelyBase Python SDK
|
|
3
|
+
~~~~~~~~~~~~~~~~~~~~~
|
|
4
|
+
标准 Python 包,对齐 Kotlin SDK 能力。
|
|
5
|
+
|
|
6
|
+
依赖:
|
|
7
|
+
pip install requests # 必须
|
|
8
|
+
pip install websocket-client # FBLiveQuery 实时监听
|
|
9
|
+
pip install httpx # AsyncFreelyBase 异步客户端
|
|
10
|
+
pip install cryptography # EncryptedFreelyBase 请求加密
|
|
11
|
+
|
|
12
|
+
快速开始:
|
|
13
|
+
from freelybase import FreelyBase, FBObject, FBQuery, FBUser, FBFile, FBGeoPoint, FBAI
|
|
14
|
+
|
|
15
|
+
# 初始化
|
|
16
|
+
FreelyBase.initialize(app_key="your_app_id", base_url="https://your-domain.com")
|
|
17
|
+
|
|
18
|
+
# 定义数据模型
|
|
19
|
+
class Post(FBObject):
|
|
20
|
+
table_name = "Post"
|
|
21
|
+
title: str = ""
|
|
22
|
+
view_count: int = 0
|
|
23
|
+
active: bool = True
|
|
24
|
+
|
|
25
|
+
# 新增
|
|
26
|
+
post = Post(title="Hello", active=True)
|
|
27
|
+
post.save()
|
|
28
|
+
|
|
29
|
+
# 查询
|
|
30
|
+
results = FBQuery(Post).equal_to("active", True).order("-created_at").limit(20).find()
|
|
31
|
+
|
|
32
|
+
# 用户登录
|
|
33
|
+
user = FBUser.login("user@example.com", "password123")
|
|
34
|
+
|
|
35
|
+
# 文件上传
|
|
36
|
+
fb_file = FBFile.upload("photo.jpg")
|
|
37
|
+
print(fb_file.url)
|
|
38
|
+
|
|
39
|
+
# AI 聊天
|
|
40
|
+
response = FBAI.chat("你好")
|
|
41
|
+
print(response.content)
|
|
42
|
+
"""
|
|
43
|
+
|
|
44
|
+
from .exceptions import FreelyBaseException, FreelyBaseError
|
|
45
|
+
from .client import FreelyBase
|
|
46
|
+
from .geo_point import FBGeoPoint, DistanceUnit
|
|
47
|
+
from .fb_file import FBFile
|
|
48
|
+
from .fb_object import FBObject
|
|
49
|
+
from .fb_query import FBQuery, CachePolicy, clear_query_cache
|
|
50
|
+
from .fb_user import FBUser
|
|
51
|
+
from .fb_live_query import FBLiveQuery
|
|
52
|
+
from .fb_ai import FBAI, AiMessage, AiQuota, AiChatResponse
|
|
53
|
+
from .query import Query
|
|
54
|
+
from .helpers import Relation, Batch
|
|
55
|
+
|
|
56
|
+
__version__ = "2.0.0"
|
|
57
|
+
|
|
58
|
+
__all__ = [
|
|
59
|
+
# 核心
|
|
60
|
+
"FreelyBase",
|
|
61
|
+
"FreelyBaseException",
|
|
62
|
+
"FreelyBaseError", # 向后兼容
|
|
63
|
+
# 数据模型
|
|
64
|
+
"FBObject",
|
|
65
|
+
"FBQuery",
|
|
66
|
+
"CachePolicy",
|
|
67
|
+
"clear_query_cache",
|
|
68
|
+
# 用户
|
|
69
|
+
"FBUser",
|
|
70
|
+
# 文件
|
|
71
|
+
"FBFile",
|
|
72
|
+
# 地理位置
|
|
73
|
+
"FBGeoPoint",
|
|
74
|
+
"DistanceUnit",
|
|
75
|
+
# 实时监听
|
|
76
|
+
"FBLiveQuery",
|
|
77
|
+
# AI
|
|
78
|
+
"FBAI",
|
|
79
|
+
"AiMessage",
|
|
80
|
+
"AiQuota",
|
|
81
|
+
"AiChatResponse",
|
|
82
|
+
# 轻量级字典 API(兼容旧版)
|
|
83
|
+
"Query",
|
|
84
|
+
"Relation",
|
|
85
|
+
"Batch",
|
|
86
|
+
]
|
freelybase/client.py
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
"""FreelyBase SDK 全局配置与 HTTP 客户端"""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import os
|
|
5
|
+
from typing import Any, Dict, Optional
|
|
6
|
+
|
|
7
|
+
import requests
|
|
8
|
+
|
|
9
|
+
from .exceptions import FreelyBaseException
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class FreelyBase:
|
|
13
|
+
"""
|
|
14
|
+
FreelyBase SDK 主入口(单例风格,也可实例化使用)。
|
|
15
|
+
|
|
16
|
+
推荐用法(全局初始化):
|
|
17
|
+
FreelyBase.initialize(app_key="your_app_id", base_url="https://your-domain.com")
|
|
18
|
+
|
|
19
|
+
也可直接实例化:
|
|
20
|
+
fb = FreelyBase(app_key="your_app_id")
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
# ── 全局单例状态 ──────────────────────────────────────────────────────────
|
|
24
|
+
_instance: Optional["FreelyBase"] = None
|
|
25
|
+
|
|
26
|
+
base_url: str = "http://www.freelybase.com/api"
|
|
27
|
+
app_key: str = ""
|
|
28
|
+
token: Optional[str] = None
|
|
29
|
+
debug: bool = False
|
|
30
|
+
_timeout: int = 15
|
|
31
|
+
_session: requests.Session = requests.Session()
|
|
32
|
+
|
|
33
|
+
def __init__(
|
|
34
|
+
self,
|
|
35
|
+
app_key: str = "",
|
|
36
|
+
base_url: str = "http://www.freelybase.com/api",
|
|
37
|
+
token: Optional[str] = None,
|
|
38
|
+
timeout: int = 15,
|
|
39
|
+
debug: bool = False,
|
|
40
|
+
):
|
|
41
|
+
self.app_key = app_key
|
|
42
|
+
self.base_url = base_url.rstrip("/")
|
|
43
|
+
self.token = token
|
|
44
|
+
self._timeout = timeout
|
|
45
|
+
self.debug = debug
|
|
46
|
+
self._session = requests.Session()
|
|
47
|
+
# 设置为全局实例
|
|
48
|
+
FreelyBase._instance = self
|
|
49
|
+
|
|
50
|
+
@classmethod
|
|
51
|
+
def initialize(
|
|
52
|
+
cls,
|
|
53
|
+
app_key: str,
|
|
54
|
+
base_url: str = "http://www.freelybase.com/api",
|
|
55
|
+
timeout: int = 15,
|
|
56
|
+
debug: bool = False,
|
|
57
|
+
) -> "FreelyBase":
|
|
58
|
+
"""初始化全局 SDK 实例,返回实例供链式调用。"""
|
|
59
|
+
inst = cls(app_key=app_key, base_url=base_url, timeout=timeout, debug=debug)
|
|
60
|
+
cls._instance = inst
|
|
61
|
+
return inst
|
|
62
|
+
|
|
63
|
+
@classmethod
|
|
64
|
+
def get_instance(cls) -> "FreelyBase":
|
|
65
|
+
if cls._instance is None:
|
|
66
|
+
raise FreelyBaseException("FreelyBase 未初始化,请先调用 FreelyBase.initialize()")
|
|
67
|
+
return cls._instance
|
|
68
|
+
|
|
69
|
+
# ── Token 管理 ────────────────────────────────────────────────────────────
|
|
70
|
+
|
|
71
|
+
def set_token(self, token: Optional[str]) -> None:
|
|
72
|
+
self.token = token
|
|
73
|
+
|
|
74
|
+
def clear_token(self) -> None:
|
|
75
|
+
self.token = None
|
|
76
|
+
|
|
77
|
+
def is_logged_in(self) -> bool:
|
|
78
|
+
return bool(self.token)
|
|
79
|
+
|
|
80
|
+
# ── 内部 HTTP ─────────────────────────────────────────────────────────────
|
|
81
|
+
|
|
82
|
+
def _headers(self) -> Dict[str, str]:
|
|
83
|
+
h: Dict[str, str] = {"Content-Type": "application/json"}
|
|
84
|
+
if self.token:
|
|
85
|
+
h["Authorization"] = f"Bearer {self.token}"
|
|
86
|
+
return h
|
|
87
|
+
|
|
88
|
+
def _url(self, path: str) -> str:
|
|
89
|
+
return f"{self.base_url}/{path.lstrip('/')}"
|
|
90
|
+
|
|
91
|
+
def _request(self, method: str, path: str, **kwargs) -> Any:
|
|
92
|
+
url = self._url(path)
|
|
93
|
+
kwargs.setdefault("headers", self._headers())
|
|
94
|
+
kwargs.setdefault("timeout", self._timeout)
|
|
95
|
+
if self.debug:
|
|
96
|
+
print(f"[FreelyBase] {method} {url}")
|
|
97
|
+
resp = self._session.request(method, url, **kwargs)
|
|
98
|
+
if not resp.ok:
|
|
99
|
+
try:
|
|
100
|
+
detail = resp.json().get("detail", resp.text)
|
|
101
|
+
except Exception:
|
|
102
|
+
detail = resp.text
|
|
103
|
+
raise FreelyBaseException(
|
|
104
|
+
f"Request failed: {method} {url}",
|
|
105
|
+
status_code=resp.status_code,
|
|
106
|
+
detail=detail,
|
|
107
|
+
)
|
|
108
|
+
if resp.status_code == 204 or not resp.content:
|
|
109
|
+
return {}
|
|
110
|
+
return resp.json()
|
|
111
|
+
|
|
112
|
+
def get(self, path: str, params: Optional[Dict] = None) -> Any:
|
|
113
|
+
return self._request("GET", path, params=params, headers=self._headers())
|
|
114
|
+
|
|
115
|
+
def post(self, path: str, body: Any = None) -> Any:
|
|
116
|
+
return self._request("POST", path, json=body, headers=self._headers())
|
|
117
|
+
|
|
118
|
+
def put(self, path: str, body: Any = None) -> Any:
|
|
119
|
+
return self._request("PUT", path, json=body, headers=self._headers())
|
|
120
|
+
|
|
121
|
+
def delete(self, path: str) -> Any:
|
|
122
|
+
return self._request("DELETE", path, headers=self._headers())
|
|
123
|
+
|
|
124
|
+
# ── 服务器时间 ────────────────────────────────────────────────────────────
|
|
125
|
+
|
|
126
|
+
def server_time(self) -> str:
|
|
127
|
+
"""获取服务器时间,返回 ISO 8601 字符串。"""
|
|
128
|
+
result = self.get("/public/server-time")
|
|
129
|
+
return result.get("server_time", "")
|
|
130
|
+
|
|
131
|
+
def get_public_key(self) -> str:
|
|
132
|
+
"""获取 RSA 公钥(用于请求加密)。"""
|
|
133
|
+
result = self.get("/crypto/public-key")
|
|
134
|
+
return result.get("public_key_pem", "")
|
freelybase/exceptions.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
"""FreelyBase SDK 异常定义"""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
from typing import Any
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class FreelyBaseException(Exception):
|
|
7
|
+
"""SDK 基础异常"""
|
|
8
|
+
|
|
9
|
+
def __init__(self, message: str, status_code: int = 0, detail: Any = None):
|
|
10
|
+
super().__init__(message)
|
|
11
|
+
self.status_code = status_code
|
|
12
|
+
self.detail = detail
|
|
13
|
+
|
|
14
|
+
def __str__(self) -> str:
|
|
15
|
+
return f"[{self.status_code}] {super().__str__()} | detail={self.detail}"
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
# 向后兼容别名
|
|
19
|
+
FreelyBaseError = FreelyBaseException
|
freelybase/fb_ai.py
ADDED
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
"""FBAI - AI 服务,提供聊天和配额管理功能"""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import json
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
|
+
from typing import Any, Callable, Dict, Generator, List, Optional
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
@dataclass
|
|
10
|
+
class AiMessage:
|
|
11
|
+
"""AI 对话消息"""
|
|
12
|
+
role: str # system / user / assistant
|
|
13
|
+
content: str
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass
|
|
17
|
+
class AiQuota:
|
|
18
|
+
"""AI Token 配额信息"""
|
|
19
|
+
remaining: int
|
|
20
|
+
token_unit: int = 1_000_000
|
|
21
|
+
price_fen_per_unit: int = 100
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass
|
|
25
|
+
class AiChatResponse:
|
|
26
|
+
"""AI 聊天响应"""
|
|
27
|
+
content: str
|
|
28
|
+
tokens_used: int = 0
|
|
29
|
+
remaining: int = 0
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class FBAI:
|
|
33
|
+
"""
|
|
34
|
+
AI 服务,提供聊天和配额管理功能。
|
|
35
|
+
|
|
36
|
+
用法:
|
|
37
|
+
# 获取配额
|
|
38
|
+
quota = FBAI.get_quota()
|
|
39
|
+
print(f"剩余 Token: {quota.remaining}")
|
|
40
|
+
|
|
41
|
+
# 非流式响应
|
|
42
|
+
response = FBAI.chat("如何使用 Python?")
|
|
43
|
+
print(response.content)
|
|
44
|
+
|
|
45
|
+
# 流式响应
|
|
46
|
+
def on_chunk(chunk: str):
|
|
47
|
+
print(chunk, end="", flush=True)
|
|
48
|
+
|
|
49
|
+
response = FBAI.chat("写一篇文章", on_chunk=on_chunk)
|
|
50
|
+
|
|
51
|
+
# 多轮对话
|
|
52
|
+
ai = FBAI()
|
|
53
|
+
ai.chat("你好")
|
|
54
|
+
ai.chat("继续上面的话题")
|
|
55
|
+
|
|
56
|
+
# 清除对话历史
|
|
57
|
+
FBAI.clear_history()
|
|
58
|
+
"""
|
|
59
|
+
|
|
60
|
+
# 全局对话历史(类级别,单例风格)
|
|
61
|
+
_history: List[AiMessage] = []
|
|
62
|
+
|
|
63
|
+
def __init__(self):
|
|
64
|
+
self._history: List[AiMessage] = []
|
|
65
|
+
|
|
66
|
+
@staticmethod
|
|
67
|
+
def _get_client():
|
|
68
|
+
from .client import FreelyBase
|
|
69
|
+
return FreelyBase.get_instance()
|
|
70
|
+
|
|
71
|
+
# ── 配额 ──────────────────────────────────────────────────────────────────
|
|
72
|
+
|
|
73
|
+
@classmethod
|
|
74
|
+
def get_quota(cls) -> AiQuota:
|
|
75
|
+
"""获取应用的 AI Token 配额信息。"""
|
|
76
|
+
c = cls._get_client()
|
|
77
|
+
res = c.get(f"/apps/{c.app_key}/ai/quota")
|
|
78
|
+
return AiQuota(
|
|
79
|
+
remaining=int(res.get("ai_token_remaining", 0)),
|
|
80
|
+
token_unit=int(res.get("token_unit", 1_000_000)),
|
|
81
|
+
price_fen_per_unit=int(res.get("price_fen_per_unit", 100)),
|
|
82
|
+
)
|
|
83
|
+
|
|
84
|
+
# ── 对话历史 ──────────────────────────────────────────────────────────────
|
|
85
|
+
|
|
86
|
+
@classmethod
|
|
87
|
+
def clear_history(cls) -> None:
|
|
88
|
+
"""清除全局对话历史。"""
|
|
89
|
+
cls._history.clear()
|
|
90
|
+
|
|
91
|
+
@classmethod
|
|
92
|
+
def get_history(cls) -> List[AiMessage]:
|
|
93
|
+
"""获取全局对话历史。"""
|
|
94
|
+
return list(cls._history)
|
|
95
|
+
|
|
96
|
+
# ── 聊天 ──────────────────────────────────────────────────────────────────
|
|
97
|
+
|
|
98
|
+
@classmethod
|
|
99
|
+
def chat(
|
|
100
|
+
cls,
|
|
101
|
+
message: str,
|
|
102
|
+
system_prompt: Optional[str] = None,
|
|
103
|
+
on_chunk: Optional[Callable[[str], None]] = None,
|
|
104
|
+
history: Optional[List[AiMessage]] = None,
|
|
105
|
+
) -> AiChatResponse:
|
|
106
|
+
"""
|
|
107
|
+
发起 AI 聊天对话(自动管理多轮对话历史)。
|
|
108
|
+
|
|
109
|
+
:param message: 用户消息内容
|
|
110
|
+
:param system_prompt: 系统提示词(仅在历史为空时生效)
|
|
111
|
+
:param on_chunk: 流式响应回调,设置后自动启用流式模式
|
|
112
|
+
:param history: 自定义对话历史,不传则使用全局历史
|
|
113
|
+
:return: AiChatResponse
|
|
114
|
+
"""
|
|
115
|
+
hist = history if history is not None else cls._history
|
|
116
|
+
stream = on_chunk is not None
|
|
117
|
+
|
|
118
|
+
if system_prompt and not hist:
|
|
119
|
+
hist.append(AiMessage("system", system_prompt))
|
|
120
|
+
hist.append(AiMessage("user", message))
|
|
121
|
+
|
|
122
|
+
c = cls._get_client()
|
|
123
|
+
body = {
|
|
124
|
+
"app_id": c.app_key,
|
|
125
|
+
"messages": [{"role": m.role, "content": m.content} for m in hist],
|
|
126
|
+
"stream": stream,
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
if stream:
|
|
130
|
+
response = cls._stream_chat(c, body, on_chunk)
|
|
131
|
+
else:
|
|
132
|
+
res = c.post(f"/apps/{c.app_key}/ai/chat", body)
|
|
133
|
+
response = AiChatResponse(
|
|
134
|
+
content=res.get("content", ""),
|
|
135
|
+
tokens_used=int(res.get("tokens_used", 0)),
|
|
136
|
+
remaining=int(res.get("ai_token_remaining", 0)),
|
|
137
|
+
)
|
|
138
|
+
|
|
139
|
+
hist.append(AiMessage("assistant", response.content))
|
|
140
|
+
return response
|
|
141
|
+
|
|
142
|
+
@classmethod
|
|
143
|
+
def _stream_chat(
|
|
144
|
+
cls,
|
|
145
|
+
client,
|
|
146
|
+
body: Dict[str, Any],
|
|
147
|
+
on_chunk: Callable[[str], None],
|
|
148
|
+
) -> AiChatResponse:
|
|
149
|
+
"""执行流式请求(SSE),同步阻塞直到完成。"""
|
|
150
|
+
import requests
|
|
151
|
+
|
|
152
|
+
url = client._url(f"/apps/{client.app_key}/ai/chat")
|
|
153
|
+
headers = client._headers()
|
|
154
|
+
headers["Accept"] = "text/event-stream"
|
|
155
|
+
|
|
156
|
+
full_content: List[str] = []
|
|
157
|
+
tokens_used = 0
|
|
158
|
+
remaining = 0
|
|
159
|
+
|
|
160
|
+
with requests.post(url, json=body, headers=headers, stream=True, timeout=60) as resp:
|
|
161
|
+
if not resp.ok:
|
|
162
|
+
from .exceptions import FreelyBaseException
|
|
163
|
+
raise FreelyBaseException(
|
|
164
|
+
f"AI chat failed",
|
|
165
|
+
status_code=resp.status_code,
|
|
166
|
+
detail=resp.text,
|
|
167
|
+
)
|
|
168
|
+
for line in resp.iter_lines():
|
|
169
|
+
if not line:
|
|
170
|
+
continue
|
|
171
|
+
if isinstance(line, bytes):
|
|
172
|
+
line = line.decode("utf-8")
|
|
173
|
+
if line.startswith("data:"):
|
|
174
|
+
data_str = line[5:].strip()
|
|
175
|
+
if not data_str or data_str == "[DONE]":
|
|
176
|
+
continue
|
|
177
|
+
try:
|
|
178
|
+
data = json.loads(data_str)
|
|
179
|
+
except json.JSONDecodeError:
|
|
180
|
+
continue
|
|
181
|
+
if data.get("done"):
|
|
182
|
+
tokens_used = int(data.get("tokens_used", 0))
|
|
183
|
+
remaining = int(data.get("ai_token_remaining", 0))
|
|
184
|
+
error = data.get("error")
|
|
185
|
+
if error:
|
|
186
|
+
from .exceptions import FreelyBaseException
|
|
187
|
+
raise FreelyBaseException(f"AI 服务错误: {error}", 502)
|
|
188
|
+
break
|
|
189
|
+
chunk = data.get("content", "")
|
|
190
|
+
if chunk:
|
|
191
|
+
full_content.append(chunk)
|
|
192
|
+
on_chunk(chunk)
|
|
193
|
+
|
|
194
|
+
return AiChatResponse(
|
|
195
|
+
content="".join(full_content),
|
|
196
|
+
tokens_used=tokens_used,
|
|
197
|
+
remaining=remaining,
|
|
198
|
+
)
|
|
199
|
+
|
|
200
|
+
@classmethod
|
|
201
|
+
def stream_chat_iter(
|
|
202
|
+
cls,
|
|
203
|
+
message: str,
|
|
204
|
+
system_prompt: Optional[str] = None,
|
|
205
|
+
history: Optional[List[AiMessage]] = None,
|
|
206
|
+
) -> Generator[str, None, AiChatResponse]:
|
|
207
|
+
"""
|
|
208
|
+
流式聊天生成器版本,逐块 yield 内容。
|
|
209
|
+
|
|
210
|
+
用法:
|
|
211
|
+
for chunk in FBAI.stream_chat_iter("写一首诗"):
|
|
212
|
+
print(chunk, end="", flush=True)
|
|
213
|
+
"""
|
|
214
|
+
hist = history if history is not None else cls._history
|
|
215
|
+
if system_prompt and not hist:
|
|
216
|
+
hist.append(AiMessage("system", system_prompt))
|
|
217
|
+
hist.append(AiMessage("user", message))
|
|
218
|
+
|
|
219
|
+
c = cls._get_client()
|
|
220
|
+
body = {
|
|
221
|
+
"app_id": c.app_key,
|
|
222
|
+
"messages": [{"role": m.role, "content": m.content} for m in hist],
|
|
223
|
+
"stream": True,
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
import requests
|
|
227
|
+
url = c._url(f"/apps/{c.app_key}/ai/chat")
|
|
228
|
+
headers = c._headers()
|
|
229
|
+
headers["Accept"] = "text/event-stream"
|
|
230
|
+
|
|
231
|
+
full_content: List[str] = []
|
|
232
|
+
tokens_used = 0
|
|
233
|
+
remaining = 0
|
|
234
|
+
|
|
235
|
+
with requests.post(url, json=body, headers=headers, stream=True, timeout=60) as resp:
|
|
236
|
+
if not resp.ok:
|
|
237
|
+
from .exceptions import FreelyBaseException
|
|
238
|
+
raise FreelyBaseException("AI chat failed", status_code=resp.status_code, detail=resp.text)
|
|
239
|
+
for line in resp.iter_lines():
|
|
240
|
+
if not line:
|
|
241
|
+
continue
|
|
242
|
+
if isinstance(line, bytes):
|
|
243
|
+
line = line.decode("utf-8")
|
|
244
|
+
if line.startswith("data:"):
|
|
245
|
+
data_str = line[5:].strip()
|
|
246
|
+
if not data_str or data_str == "[DONE]":
|
|
247
|
+
continue
|
|
248
|
+
try:
|
|
249
|
+
data = json.loads(data_str)
|
|
250
|
+
except json.JSONDecodeError:
|
|
251
|
+
continue
|
|
252
|
+
if data.get("done"):
|
|
253
|
+
tokens_used = int(data.get("tokens_used", 0))
|
|
254
|
+
remaining = int(data.get("ai_token_remaining", 0))
|
|
255
|
+
break
|
|
256
|
+
chunk = data.get("content", "")
|
|
257
|
+
if chunk:
|
|
258
|
+
full_content.append(chunk)
|
|
259
|
+
yield chunk
|
|
260
|
+
|
|
261
|
+
response = AiChatResponse(
|
|
262
|
+
content="".join(full_content),
|
|
263
|
+
tokens_used=tokens_used,
|
|
264
|
+
remaining=remaining,
|
|
265
|
+
)
|
|
266
|
+
hist.append(AiMessage("assistant", response.content))
|
|
267
|
+
return response
|
freelybase/fb_file.py
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
"""FBFile - 文件管理,封装上传与 URL 解析"""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import os
|
|
5
|
+
from typing import Optional, TYPE_CHECKING
|
|
6
|
+
|
|
7
|
+
if TYPE_CHECKING:
|
|
8
|
+
from .client import FreelyBase
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
_MIME_MAP = {
|
|
12
|
+
"jpg": "image/jpeg", "jpeg": "image/jpeg",
|
|
13
|
+
"png": "image/png", "gif": "image/gif", "webp": "image/webp",
|
|
14
|
+
"pdf": "application/pdf", "mp4": "video/mp4", "mp3": "audio/mpeg",
|
|
15
|
+
"txt": "text/plain", "json": "application/json",
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _guess_mime(filename: str) -> str:
|
|
20
|
+
ext = filename.rsplit(".", 1)[-1].lower() if "." in filename else ""
|
|
21
|
+
return _MIME_MAP.get(ext, "application/octet-stream")
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class FBFile:
|
|
25
|
+
"""
|
|
26
|
+
文件对象,封装服务端相对路径并提供完整 URL。
|
|
27
|
+
|
|
28
|
+
用法:
|
|
29
|
+
# 上传本地文件
|
|
30
|
+
fb_file = FBFile.upload("photo.jpg", client=fb)
|
|
31
|
+
print(fb_file.url) # https://your-domain.com/uploads/data-files/xxx.jpg
|
|
32
|
+
|
|
33
|
+
# 从已有路径构建(如从数据库读取的字段值)
|
|
34
|
+
fb_file = FBFile.from_path("/uploads/data-files/xxx.jpg", client=fb)
|
|
35
|
+
print(fb_file.url)
|
|
36
|
+
"""
|
|
37
|
+
|
|
38
|
+
def __init__(self, path: str, client: Optional["FreelyBase"] = None):
|
|
39
|
+
self.path = path
|
|
40
|
+
self._client = client
|
|
41
|
+
|
|
42
|
+
@property
|
|
43
|
+
def url(self) -> str:
|
|
44
|
+
"""完整可访问 URL"""
|
|
45
|
+
if self.path.startswith(("http://", "https://")):
|
|
46
|
+
return self.path
|
|
47
|
+
client = self._client or self._get_global_client()
|
|
48
|
+
if client:
|
|
49
|
+
return f"{client.base_url.rstrip('/')}{self.path}"
|
|
50
|
+
return self.path
|
|
51
|
+
|
|
52
|
+
@property
|
|
53
|
+
def name(self) -> str:
|
|
54
|
+
"""文件名(不含路径)"""
|
|
55
|
+
return self.path.rsplit("/", 1)[-1]
|
|
56
|
+
|
|
57
|
+
def __str__(self) -> str:
|
|
58
|
+
return self.path
|
|
59
|
+
|
|
60
|
+
def __repr__(self) -> str:
|
|
61
|
+
return f"FBFile(path={self.path!r})"
|
|
62
|
+
|
|
63
|
+
@classmethod
|
|
64
|
+
def from_path(cls, path: str, client: Optional["FreelyBase"] = None) -> "FBFile":
|
|
65
|
+
"""从已有路径构建 FBFile(不发起网络请求)。"""
|
|
66
|
+
return cls(path, client=client)
|
|
67
|
+
|
|
68
|
+
@classmethod
|
|
69
|
+
def from_url(cls, url: str, client: Optional["FreelyBase"] = None) -> "FBFile":
|
|
70
|
+
"""从完整 URL 构建 FBFile(提取相对路径)。"""
|
|
71
|
+
c = client or cls._get_global_client()
|
|
72
|
+
if c:
|
|
73
|
+
base = c.base_url.rstrip("/")
|
|
74
|
+
path = url[len(base):] if url.startswith(base) else url
|
|
75
|
+
else:
|
|
76
|
+
path = url
|
|
77
|
+
return cls(path, client=client)
|
|
78
|
+
|
|
79
|
+
@classmethod
|
|
80
|
+
def upload(
|
|
81
|
+
cls,
|
|
82
|
+
file_path: str,
|
|
83
|
+
mime_type: Optional[str] = None,
|
|
84
|
+
client: Optional["FreelyBase"] = None,
|
|
85
|
+
) -> "FBFile":
|
|
86
|
+
"""上传本地文件,返回 FBFile 对象。"""
|
|
87
|
+
c = client or cls._get_global_client()
|
|
88
|
+
if c is None:
|
|
89
|
+
raise RuntimeError("未找到 FreelyBase 实例,请先调用 FreelyBase.initialize()")
|
|
90
|
+
filename = os.path.basename(file_path)
|
|
91
|
+
mime = mime_type or _guess_mime(filename)
|
|
92
|
+
headers: dict = {}
|
|
93
|
+
if c.token:
|
|
94
|
+
headers["Authorization"] = f"Bearer {c.token}"
|
|
95
|
+
with open(file_path, "rb") as f:
|
|
96
|
+
resp = c._session.post(
|
|
97
|
+
c._url(f"/public/apps/{c.app_key}/files"),
|
|
98
|
+
files={"file": (filename, f, mime)},
|
|
99
|
+
headers=headers,
|
|
100
|
+
timeout=c._timeout,
|
|
101
|
+
)
|
|
102
|
+
if not resp.ok:
|
|
103
|
+
from .exceptions import FreelyBaseException
|
|
104
|
+
try:
|
|
105
|
+
detail = resp.json().get("detail", resp.text)
|
|
106
|
+
except Exception:
|
|
107
|
+
detail = resp.text
|
|
108
|
+
raise FreelyBaseException("Upload failed", status_code=resp.status_code, detail=detail)
|
|
109
|
+
path = resp.json().get("path", "")
|
|
110
|
+
return cls(path, client=c)
|
|
111
|
+
|
|
112
|
+
@classmethod
|
|
113
|
+
def upload_bytes(
|
|
114
|
+
cls,
|
|
115
|
+
data: bytes,
|
|
116
|
+
filename: str,
|
|
117
|
+
mime_type: Optional[str] = None,
|
|
118
|
+
client: Optional["FreelyBase"] = None,
|
|
119
|
+
) -> "FBFile":
|
|
120
|
+
"""上传字节数据,返回 FBFile 对象。"""
|
|
121
|
+
c = client or cls._get_global_client()
|
|
122
|
+
if c is None:
|
|
123
|
+
raise RuntimeError("未找到 FreelyBase 实例,请先调用 FreelyBase.initialize()")
|
|
124
|
+
mime = mime_type or _guess_mime(filename)
|
|
125
|
+
headers: dict = {}
|
|
126
|
+
if c.token:
|
|
127
|
+
headers["Authorization"] = f"Bearer {c.token}"
|
|
128
|
+
resp = c._session.post(
|
|
129
|
+
c._url(f"/public/apps/{c.app_key}/files"),
|
|
130
|
+
files={"file": (filename, data, mime)},
|
|
131
|
+
headers=headers,
|
|
132
|
+
timeout=c._timeout,
|
|
133
|
+
)
|
|
134
|
+
if not resp.ok:
|
|
135
|
+
from .exceptions import FreelyBaseException
|
|
136
|
+
try:
|
|
137
|
+
detail = resp.json().get("detail", resp.text)
|
|
138
|
+
except Exception:
|
|
139
|
+
detail = resp.text
|
|
140
|
+
raise FreelyBaseException("Upload failed", status_code=resp.status_code, detail=detail)
|
|
141
|
+
path = resp.json().get("path", "")
|
|
142
|
+
return cls(path, client=c)
|
|
143
|
+
|
|
144
|
+
@staticmethod
|
|
145
|
+
def _get_global_client() -> Optional["FreelyBase"]:
|
|
146
|
+
try:
|
|
147
|
+
from .client import FreelyBase
|
|
148
|
+
return FreelyBase._instance
|
|
149
|
+
except Exception:
|
|
150
|
+
return None
|