fastkeel 0.1.0__tar.gz

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.
Files changed (54) hide show
  1. fastkeel-0.1.0/.claude/settings.local.json +10 -0
  2. fastkeel-0.1.0/.github/workflows/publish.yml +25 -0
  3. fastkeel-0.1.0/.github/workflows/test.yml +26 -0
  4. fastkeel-0.1.0/.gitignore +38 -0
  5. fastkeel-0.1.0/LICENSE +21 -0
  6. fastkeel-0.1.0/Makefile +18 -0
  7. fastkeel-0.1.0/PKG-INFO +156 -0
  8. fastkeel-0.1.0/README.md +130 -0
  9. fastkeel-0.1.0/fastkeel/__init__.py +4 -0
  10. fastkeel-0.1.0/fastkeel/cli/__init__.py +5 -0
  11. fastkeel-0.1.0/fastkeel/cli/new.py +57 -0
  12. fastkeel-0.1.0/fastkeel/contrib/__init__.py +0 -0
  13. fastkeel-0.1.0/fastkeel/contrib/llm.py +99 -0
  14. fastkeel-0.1.0/fastkeel/contrib/streaming.py +31 -0
  15. fastkeel-0.1.0/fastkeel/core/__init__.py +0 -0
  16. fastkeel-0.1.0/fastkeel/core/app.py +38 -0
  17. fastkeel-0.1.0/fastkeel/core/auth.py +101 -0
  18. fastkeel-0.1.0/fastkeel/core/config.py +118 -0
  19. fastkeel-0.1.0/fastkeel/core/db.py +68 -0
  20. fastkeel-0.1.0/fastkeel/core/middleware.py +53 -0
  21. fastkeel-0.1.0/fastkeel/modules/__init__.py +6 -0
  22. fastkeel-0.1.0/fastkeel/modules/jobs.py +60 -0
  23. fastkeel-0.1.0/fastkeel/modules/payment.py +326 -0
  24. fastkeel-0.1.0/fastkeel/modules/social.py +422 -0
  25. fastkeel-0.1.0/fastkeel/modules/user.py +144 -0
  26. fastkeel-0.1.0/fastkeel/templates/default/config.toml.j2 +33 -0
  27. fastkeel-0.1.0/fastkeel/templates/default/main.py.j2 +16 -0
  28. fastkeel-0.1.0/fastkeel/templates/default/project/__init__.py.j2 +0 -0
  29. fastkeel-0.1.0/fastkeel/templates/default/project/logic/__init__.py.j2 +0 -0
  30. fastkeel-0.1.0/fastkeel/templates/default/project/models/__init__.py.j2 +0 -0
  31. fastkeel-0.1.0/fastkeel/templates/default/project/prompts/.gitkeep.j2 +0 -0
  32. fastkeel-0.1.0/fastkeel/templates/default/project/routes/__init__.py.j2 +8 -0
  33. fastkeel-0.1.0/fastkeel/templates/default/pyproject.toml.j2 +18 -0
  34. fastkeel-0.1.0/fastkeel/templates/default/tests/__init__.py.j2 +0 -0
  35. fastkeel-0.1.0/fastkeel/templates/default/tests/conftest.py.j2 +19 -0
  36. fastkeel-0.1.0/pyproject.toml +41 -0
  37. fastkeel-0.1.0/tests/__init__.py +0 -0
  38. fastkeel-0.1.0/tests/conftest.py +75 -0
  39. fastkeel-0.1.0/tests/test_cli/__init__.py +0 -0
  40. fastkeel-0.1.0/tests/test_cli/test_new.py +105 -0
  41. fastkeel-0.1.0/tests/test_contrib/__init__.py +0 -0
  42. fastkeel-0.1.0/tests/test_contrib/test_llm.py +160 -0
  43. fastkeel-0.1.0/tests/test_core/__init__.py +0 -0
  44. fastkeel-0.1.0/tests/test_core/test_app.py +39 -0
  45. fastkeel-0.1.0/tests/test_core/test_auth.py +80 -0
  46. fastkeel-0.1.0/tests/test_core/test_config.py +150 -0
  47. fastkeel-0.1.0/tests/test_core/test_db.py +95 -0
  48. fastkeel-0.1.0/tests/test_core/test_middleware.py +123 -0
  49. fastkeel-0.1.0/tests/test_integration.py +174 -0
  50. fastkeel-0.1.0/tests/test_modules/__init__.py +0 -0
  51. fastkeel-0.1.0/tests/test_modules/test_jobs.py +78 -0
  52. fastkeel-0.1.0/tests/test_modules/test_payment.py +198 -0
  53. fastkeel-0.1.0/tests/test_modules/test_social.py +331 -0
  54. fastkeel-0.1.0/tests/test_modules/test_user.py +184 -0
@@ -0,0 +1,10 @@
1
+ {
2
+ "permissions": {
3
+ "allow": [
4
+ "Bash(git *)",
5
+ "Bash(python3 -m pip install -e \".[dev]\" -q)",
6
+ "Bash(uv pip *)",
7
+ "Bash(uv run *)"
8
+ ]
9
+ }
10
+ }
@@ -0,0 +1,25 @@
1
+ name: Publish to PyPI
2
+ on:
3
+ release:
4
+ types: [published]
5
+
6
+ env:
7
+ FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: true
8
+
9
+ jobs:
10
+ deploy:
11
+ runs-on: ubuntu-latest
12
+ steps:
13
+ - uses: actions/checkout@v5
14
+ - uses: actions/setup-python@v6
15
+ with:
16
+ python-version: "3.11"
17
+ - name: Build
18
+ run: |
19
+ pip install build twine
20
+ python -m build
21
+ - name: Publish
22
+ env:
23
+ TWINE_USERNAME: __token__
24
+ TWINE_PASSWORD: ${{ secrets.PYPI_TOKEN }}
25
+ run: twine upload dist/*
@@ -0,0 +1,26 @@
1
+ name: Test
2
+ on: [push, pull_request]
3
+
4
+ env:
5
+ FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: true
6
+
7
+ jobs:
8
+ test:
9
+ runs-on: ubuntu-latest
10
+ strategy:
11
+ fail-fast: false
12
+ matrix:
13
+ python-version: ["3.11", "3.12", "3.13"]
14
+
15
+ steps:
16
+ - uses: actions/checkout@v5
17
+ - uses: actions/setup-python@v6
18
+ with:
19
+ python-version: ${{ matrix.python-version }}
20
+ - name: Install dependencies
21
+ run: |
22
+ pip install -e ".[dev]"
23
+ - name: Lint
24
+ run: ruff check .
25
+ - name: Test
26
+ run: pytest
@@ -0,0 +1,38 @@
1
+ # Python
2
+ __pycache__/
3
+ *.py[cod]
4
+ *.egg-info/
5
+ dist/
6
+ build/
7
+ *.egg
8
+ .venv/
9
+ venv/
10
+ env/
11
+
12
+ # IDE
13
+ .vscode/
14
+ .idea/
15
+ *.swp
16
+ *.swo
17
+
18
+ # OS
19
+ .DS_Store
20
+ Thumbs.db
21
+
22
+ # Environment
23
+ .env
24
+ *.env.local
25
+
26
+ # Data
27
+ *.db
28
+ *.sqlite3
29
+ /data/
30
+
31
+ # Internal design docs (not for public)
32
+ DESIGN.md
33
+ TAD.md
34
+ CLAUDE.md
35
+ docs/
36
+
37
+ # Lock files (library, not an application)
38
+ uv.lock
fastkeel-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Helioswei
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,18 @@
1
+ .PHONY: lint test build publish clean
2
+
3
+ lint:
4
+ ruff check .
5
+
6
+ test:
7
+ pytest
8
+
9
+ build:
10
+ python -m build
11
+
12
+ publish: build
13
+ twine upload dist/*
14
+
15
+ clean:
16
+ rm -rf dist/ build/ *.egg-info
17
+ rm -rf .pytest_cache .ruff_cache
18
+ find . -type d -name __pycache__ -exec rm -rf {} + 2>/dev/null || true
@@ -0,0 +1,156 @@
1
+ Metadata-Version: 2.4
2
+ Name: fastkeel
3
+ Version: 0.1.0
4
+ Summary: FastAPI backend scaffold — user auth, social, subscriptions, jobs & LLM
5
+ Project-URL: Homepage, https://github.com/helioswei/fastkeel
6
+ Author: Helioswei
7
+ License: MIT
8
+ License-File: LICENSE
9
+ Requires-Python: >=3.11
10
+ Requires-Dist: apscheduler<4.0.0,>=3.10.0
11
+ Requires-Dist: fastapi<1.0.0,>=0.100.0
12
+ Requires-Dist: httpx<1.0.0,>=0.25.0
13
+ Requires-Dist: jinja2<4.0.0,>=3.0.0
14
+ Requires-Dist: pyjwt<3.0.0,>=2.0.0
15
+ Requires-Dist: sqlalchemy<3.0.0,>=2.0.0
16
+ Requires-Dist: structlog<25.0.0,>=23.0.0
17
+ Requires-Dist: typer<1.0.0,>=0.9.0
18
+ Provides-Extra: dev
19
+ Requires-Dist: build<2.0.0,>=1.0.0; extra == 'dev'
20
+ Requires-Dist: pytest-asyncio<2.0.0,>=0.21.0; extra == 'dev'
21
+ Requires-Dist: pytest-mock<5.0.0,>=3.10.0; extra == 'dev'
22
+ Requires-Dist: pytest<9.0.0,>=7.0.0; extra == 'dev'
23
+ Requires-Dist: ruff<1.0.0,>=0.1.0; extra == 'dev'
24
+ Requires-Dist: twine<6.0.0,>=4.0.0; extra == 'dev'
25
+ Description-Content-Type: text/markdown
26
+
27
+ # fastkeel ⚡
28
+
29
+ > FastAPI backend scaffold — user auth, social, subscriptions, jobs & LLM.
30
+ > `pip install fastkeel`,一行命令生成完整后端骨架。
31
+
32
+ **Status:** v0.1.0 — 生产就绪,[MIT](./LICENSE) 开源。
33
+
34
+ ---
35
+
36
+ ## 快速开始
37
+
38
+ ```bash
39
+ # 安装
40
+ pip install fastkeel
41
+
42
+ # 生成项目
43
+ fastkeel new my-app --with-user --with-social --with-payment --with-jobs
44
+ cd my-app
45
+
46
+ # 安装依赖并启动
47
+ pip install uvicorn
48
+ python main.py
49
+ ```
50
+
51
+ 生成的项目直接可用:注册、登录、搭子关系、支付订阅、定时任务 — 一个 `main.py` 全搞定。
52
+
53
+ ---
54
+
55
+ ## CLI 用法
56
+
57
+ ```bash
58
+ fastkeel new <项目名> [--with-user] [--with-social] [--with-payment] [--with-jobs] [--path <路径>]
59
+ ```
60
+
61
+ | 参数 | 默认 | 说明 |
62
+ |:----|:-----|:-----|
63
+ | `--with-user` | True | 设备注册 + JWT 认证 |
64
+ | `--with-social` | False | 搭子关系 + 群组管理 |
65
+ | `--with-payment` | False | 订阅管理 + 收据验证 |
66
+ | `--with-jobs` | False | APScheduler 定时任务 |
67
+ | `--path` | `.` | 项目生成路径 |
68
+
69
+ 不选的模块不注册路由、不创建表、不引入依赖。
70
+
71
+ ---
72
+
73
+ ## 模块
74
+
75
+ | 模块 | 提供 |
76
+ |:----|:------|
77
+ | `core` | FastAPI app factory、Config (TOML + env)、SQLite (WAL)、JWT、CORS + 统一错误处理 |
78
+ | `user` | 设备注册、登录、JWT 认证、资料更新 |
79
+ | `social` | 搭子邀请码、搭子绑定/解除、群组创建/加入/解散 |
80
+ | `payment` | 套餐管理、收据验证(渠道无关)、订阅生命周期、支付流水 |
81
+ | `jobs` | APScheduler 定时任务、心跳检查、SQLite 持久化 |
82
+ | `contrib/llm` | LLM API 客户端(自动重试、限流、流式、结构化输出)|
83
+
84
+ ### 架构
85
+
86
+ ```
87
+ 你的项目
88
+ ├── main.py # import fastkeel → compose app
89
+ ├── config.toml # TOML 配置(环境变量覆盖)
90
+ ├── project/ # 你的业务逻辑
91
+ │ ├── routes/
92
+ │ ├── logic/
93
+ │ └── prompts/
94
+ └── tests/
95
+
96
+ │ pip install fastkeel
97
+ v
98
+ fastkeel (this repo)
99
+ ├── core/ # 100% 通用,不修改
100
+ ├── modules/ # 90% 通用,include_*() 选装
101
+ ├── contrib/ # 扩展集成,按需 import
102
+ └── cli/ # fastkeel new 命令
103
+ ```
104
+
105
+ 分层规则:
106
+ - `core/` — 项目**永不修改**。需要改意味着抽象边界要调整
107
+ - `modules/` — 通过 config 配置,**不修改源码**
108
+ - `project/` — 写业务逻辑的地方
109
+
110
+ ---
111
+
112
+ ## 开发
113
+
114
+ ```bash
115
+ # Setup
116
+ git clone https://github.com/helioswei/fastkeel
117
+ cd fastkeel
118
+ python -m venv .venv && source .venv/bin/activate
119
+ pip install -e ".[dev]"
120
+
121
+ # Commands
122
+ make lint # ruff check .
123
+ make test # pytest
124
+ make build # python -m build
125
+ make publish # build + twine upload
126
+
127
+ # Test single file
128
+ pytest tests/test_modules/test_user.py -v
129
+ ```
130
+
131
+ ### 测试 (122 tests, 1.5s)
132
+
133
+ | 测试集 | 测试数 |
134
+ |:-------|:-------|
135
+ | `test_core/` (config, db, auth, middleware, app) | 47 |
136
+ | `test_modules/test_user.py` | 13 |
137
+ | `test_modules/test_social.py` | 21 |
138
+ | `test_modules/test_payment.py` | 13 |
139
+ | `test_modules/test_jobs.py` | 5 |
140
+ | `test_contrib/test_llm.py` | 8 |
141
+ | `test_cli/test_new.py` | 9 |
142
+ | `test_integration.py` | 6 |
143
+ | **合计** | **122** |
144
+
145
+ ---
146
+
147
+ ## Roadmap
148
+
149
+ - [ ] **PyPI release** — `python -m build && twine upload dist/*`
150
+ - [ ] **`user_extra_fields` dynamic columns** — `ALTER TABLE ADD COLUMN` from config
151
+ - [ ] **End-to-end generated project test** — `fastkeel new` → `pip install` → serve → curl
152
+ - [ ] **Webhook signature verification** — validate `payment_webhook_secret`
153
+
154
+ ---
155
+
156
+ MIT © 2026 Helioswei
@@ -0,0 +1,130 @@
1
+ # fastkeel ⚡
2
+
3
+ > FastAPI backend scaffold — user auth, social, subscriptions, jobs & LLM.
4
+ > `pip install fastkeel`,一行命令生成完整后端骨架。
5
+
6
+ **Status:** v0.1.0 — 生产就绪,[MIT](./LICENSE) 开源。
7
+
8
+ ---
9
+
10
+ ## 快速开始
11
+
12
+ ```bash
13
+ # 安装
14
+ pip install fastkeel
15
+
16
+ # 生成项目
17
+ fastkeel new my-app --with-user --with-social --with-payment --with-jobs
18
+ cd my-app
19
+
20
+ # 安装依赖并启动
21
+ pip install uvicorn
22
+ python main.py
23
+ ```
24
+
25
+ 生成的项目直接可用:注册、登录、搭子关系、支付订阅、定时任务 — 一个 `main.py` 全搞定。
26
+
27
+ ---
28
+
29
+ ## CLI 用法
30
+
31
+ ```bash
32
+ fastkeel new <项目名> [--with-user] [--with-social] [--with-payment] [--with-jobs] [--path <路径>]
33
+ ```
34
+
35
+ | 参数 | 默认 | 说明 |
36
+ |:----|:-----|:-----|
37
+ | `--with-user` | True | 设备注册 + JWT 认证 |
38
+ | `--with-social` | False | 搭子关系 + 群组管理 |
39
+ | `--with-payment` | False | 订阅管理 + 收据验证 |
40
+ | `--with-jobs` | False | APScheduler 定时任务 |
41
+ | `--path` | `.` | 项目生成路径 |
42
+
43
+ 不选的模块不注册路由、不创建表、不引入依赖。
44
+
45
+ ---
46
+
47
+ ## 模块
48
+
49
+ | 模块 | 提供 |
50
+ |:----|:------|
51
+ | `core` | FastAPI app factory、Config (TOML + env)、SQLite (WAL)、JWT、CORS + 统一错误处理 |
52
+ | `user` | 设备注册、登录、JWT 认证、资料更新 |
53
+ | `social` | 搭子邀请码、搭子绑定/解除、群组创建/加入/解散 |
54
+ | `payment` | 套餐管理、收据验证(渠道无关)、订阅生命周期、支付流水 |
55
+ | `jobs` | APScheduler 定时任务、心跳检查、SQLite 持久化 |
56
+ | `contrib/llm` | LLM API 客户端(自动重试、限流、流式、结构化输出)|
57
+
58
+ ### 架构
59
+
60
+ ```
61
+ 你的项目
62
+ ├── main.py # import fastkeel → compose app
63
+ ├── config.toml # TOML 配置(环境变量覆盖)
64
+ ├── project/ # 你的业务逻辑
65
+ │ ├── routes/
66
+ │ ├── logic/
67
+ │ └── prompts/
68
+ └── tests/
69
+
70
+ │ pip install fastkeel
71
+ v
72
+ fastkeel (this repo)
73
+ ├── core/ # 100% 通用,不修改
74
+ ├── modules/ # 90% 通用,include_*() 选装
75
+ ├── contrib/ # 扩展集成,按需 import
76
+ └── cli/ # fastkeel new 命令
77
+ ```
78
+
79
+ 分层规则:
80
+ - `core/` — 项目**永不修改**。需要改意味着抽象边界要调整
81
+ - `modules/` — 通过 config 配置,**不修改源码**
82
+ - `project/` — 写业务逻辑的地方
83
+
84
+ ---
85
+
86
+ ## 开发
87
+
88
+ ```bash
89
+ # Setup
90
+ git clone https://github.com/helioswei/fastkeel
91
+ cd fastkeel
92
+ python -m venv .venv && source .venv/bin/activate
93
+ pip install -e ".[dev]"
94
+
95
+ # Commands
96
+ make lint # ruff check .
97
+ make test # pytest
98
+ make build # python -m build
99
+ make publish # build + twine upload
100
+
101
+ # Test single file
102
+ pytest tests/test_modules/test_user.py -v
103
+ ```
104
+
105
+ ### 测试 (122 tests, 1.5s)
106
+
107
+ | 测试集 | 测试数 |
108
+ |:-------|:-------|
109
+ | `test_core/` (config, db, auth, middleware, app) | 47 |
110
+ | `test_modules/test_user.py` | 13 |
111
+ | `test_modules/test_social.py` | 21 |
112
+ | `test_modules/test_payment.py` | 13 |
113
+ | `test_modules/test_jobs.py` | 5 |
114
+ | `test_contrib/test_llm.py` | 8 |
115
+ | `test_cli/test_new.py` | 9 |
116
+ | `test_integration.py` | 6 |
117
+ | **合计** | **122** |
118
+
119
+ ---
120
+
121
+ ## Roadmap
122
+
123
+ - [ ] **PyPI release** — `python -m build && twine upload dist/*`
124
+ - [ ] **`user_extra_fields` dynamic columns** — `ALTER TABLE ADD COLUMN` from config
125
+ - [ ] **End-to-end generated project test** — `fastkeel new` → `pip install` → serve → curl
126
+ - [ ] **Webhook signature verification** — validate `payment_webhook_secret`
127
+
128
+ ---
129
+
130
+ MIT © 2026 Helioswei
@@ -0,0 +1,4 @@
1
+ from fastkeel.core.app import create_app
2
+ from fastkeel.core.config import Config
3
+
4
+ __all__ = ["create_app", "Config"]
@@ -0,0 +1,5 @@
1
+ # fastkeel/cli/__init__.py
2
+
3
+ from fastkeel.cli.new import app as cli_app
4
+
5
+ app = cli_app
@@ -0,0 +1,57 @@
1
+ # fastkeel/cli/new.py
2
+ from pathlib import Path
3
+
4
+ import typer
5
+ from jinja2 import Environment, PackageLoader
6
+
7
+ app = typer.Typer(help="fastkeel - FastAPI backend scaffold")
8
+
9
+
10
+ @app.command()
11
+ def new(
12
+ name: str = typer.Argument(help="项目名称"),
13
+ with_user: bool = typer.Option(True, "--with-user/--no-with-user", help="启用用户模块"),
14
+ with_social: bool = typer.Option(False, "--with-social/--no-with-social", help="启用社交模块"),
15
+ with_payment: bool = typer.Option(False, "--with-payment/--no-with-payment", help="启用支付模块"),
16
+ with_jobs: bool = typer.Option(False, "--with-jobs/--no-with-jobs", help="启用定时任务模块"),
17
+ path: str = typer.Option(".", "--path", help="生成路径"),
18
+ ):
19
+ """生成 FastAPI 项目骨架。"""
20
+ target_dir = Path(path) / name
21
+ target_dir.mkdir(parents=True, exist_ok=True)
22
+
23
+ env = Environment(
24
+ loader=PackageLoader("fastkeel", "templates/default"),
25
+ )
26
+
27
+ templates = [
28
+ "main.py.j2",
29
+ "config.toml.j2",
30
+ "pyproject.toml.j2",
31
+ "project/__init__.py.j2",
32
+ "project/models/__init__.py.j2",
33
+ "project/routes/__init__.py.j2",
34
+ "project/logic/__init__.py.j2",
35
+ "project/prompts/.gitkeep.j2",
36
+ "tests/__init__.py.j2",
37
+ "tests/conftest.py.j2",
38
+ ]
39
+
40
+ context = {
41
+ "project_name": name,
42
+ "with_user": with_user,
43
+ "with_social": with_social,
44
+ "with_payment": with_payment,
45
+ "with_jobs": with_jobs,
46
+ }
47
+
48
+ for template_name in templates:
49
+ dest = target_dir / template_name.removesuffix(".j2")
50
+ dest.parent.mkdir(parents=True, exist_ok=True)
51
+ template = env.get_template(template_name)
52
+ content = template.render(**context)
53
+ dest.write_text(content)
54
+
55
+ typer.echo(f"✅ {name} 已创建在 {target_dir}")
56
+ typer.echo(f" cd {name}")
57
+ typer.echo(" pip install -e .")
File without changes
@@ -0,0 +1,99 @@
1
+ # fastkeel/contrib/llm.py
2
+ import asyncio
3
+ import json
4
+ import logging
5
+ from collections.abc import AsyncGenerator
6
+ from typing import Any
7
+
8
+ import httpx
9
+ from pydantic import BaseModel, ValidationError
10
+
11
+ from fastkeel.core.config import Config
12
+
13
+ logger = logging.getLogger(__name__)
14
+
15
+
16
+ class LLMClient:
17
+ """LLM API client with retry, rate limiting, and structured output."""
18
+
19
+ def __init__(self, config: Config) -> None:
20
+ self.api_base = config.llm_api_base.rstrip("/")
21
+ self.model = config.llm_model
22
+ self.max_retries = config.llm_max_retries
23
+ self.semaphore = asyncio.Semaphore(config.llm_rate_limit)
24
+ self._client = httpx.AsyncClient(
25
+ base_url=self.api_base,
26
+ headers={"Authorization": f"Bearer {config.llm_api_key}"},
27
+ timeout=60,
28
+ )
29
+
30
+ async def chat(self, messages: list[dict], **kwargs: Any) -> str:
31
+ """Send a chat request and return the response text."""
32
+ payload = {
33
+ "model": self.model,
34
+ "messages": messages,
35
+ **kwargs,
36
+ }
37
+
38
+ for attempt in range(self.max_retries + 1):
39
+ async with self.semaphore:
40
+ try:
41
+ response = await self._client.post("/chat/completions", json=payload)
42
+ except httpx.RequestError as e:
43
+ if attempt < self.max_retries:
44
+ wait = 2 ** attempt
45
+ logger.warning("Request failed (attempt %d): %s, retrying in %ds", attempt + 1, e, wait)
46
+ await asyncio.sleep(wait)
47
+ continue
48
+ raise RuntimeError(f"API request failed after {self.max_retries} retries") from e
49
+
50
+ if response.status_code in (429, 502, 503, 504) and attempt < self.max_retries:
51
+ wait = 2 ** attempt
52
+ logger.warning("HTTP %d (attempt %d), retrying in %ds", response.status_code, attempt + 1, wait)
53
+ await asyncio.sleep(wait)
54
+ continue
55
+
56
+ if response.status_code != 200:
57
+ raise RuntimeError(
58
+ f"API error: HTTP {response.status_code} — {response.text[:200]}"
59
+ )
60
+
61
+ data = response.json()
62
+ return data["choices"][0]["message"]["content"]
63
+
64
+ raise RuntimeError(f"API request failed after {self.max_retries} retries")
65
+
66
+ async def chat_stream(self, messages: list[dict], **kwargs: Any) -> AsyncGenerator[str, None]:
67
+ """Stream a chat response chunk by chunk."""
68
+ payload = {
69
+ "model": self.model,
70
+ "messages": messages,
71
+ "stream": True,
72
+ **kwargs,
73
+ }
74
+
75
+ async with self.semaphore:
76
+ async with self._client.stream(
77
+ "POST", "/chat/completions", json=payload
78
+ ) as response:
79
+ async for line in response.aiter_lines():
80
+ if line.startswith("data: ") and line != "data: [DONE]":
81
+ chunk = json.loads(line[6:])
82
+ delta = chunk["choices"][0].get("delta", {})
83
+ content = delta.get("content", "")
84
+ if content:
85
+ yield content
86
+
87
+ async def chat_structured(
88
+ self,
89
+ messages: list[dict],
90
+ response_model: type[BaseModel],
91
+ **kwargs: Any,
92
+ ) -> BaseModel:
93
+ """Send a chat request and parse the response as a Pydantic model."""
94
+ text = await self.chat(messages, **kwargs)
95
+ try:
96
+ data = json.loads(text)
97
+ return response_model.model_validate(data)
98
+ except (json.JSONDecodeError, ValidationError) as e:
99
+ raise ValueError(f"Failed to parse structured output: {e}") from e
@@ -0,0 +1,31 @@
1
+ # fastkeel/contrib/streaming.py
2
+ from collections.abc import AsyncGenerator
3
+ from typing import Any
4
+
5
+ from fastapi.responses import StreamingResponse
6
+
7
+
8
+ class SSEStreamer:
9
+ """SSE (Server-Sent Events) streaming response utilities."""
10
+
11
+ @staticmethod
12
+ def from_generator(gen: AsyncGenerator[str, None]) -> StreamingResponse:
13
+ """Wrap an async string generator as an SSE StreamingResponse."""
14
+ async def event_stream() -> AsyncGenerator[bytes, None]:
15
+ async for chunk in gen:
16
+ yield f"data: {chunk}\n\n".encode("utf-8")
17
+
18
+ return StreamingResponse(
19
+ event_stream(),
20
+ media_type="text/event-stream",
21
+ )
22
+
23
+ @staticmethod
24
+ async def from_llm_stream(
25
+ llm_client: Any,
26
+ messages: list[dict],
27
+ ) -> StreamingResponse:
28
+ """Convenience: wrap LLM streaming response as SSE."""
29
+ return SSEStreamer.from_generator(
30
+ llm_client.chat_stream(messages)
31
+ )
File without changes
@@ -0,0 +1,38 @@
1
+ # fastkeel/core/app.py
2
+ from collections.abc import AsyncGenerator
3
+ from contextlib import asynccontextmanager
4
+
5
+ from fastapi import FastAPI
6
+
7
+ from fastkeel.core.auth import set_config_for_dependency
8
+ from fastkeel.core.config import Config
9
+ from fastkeel.core.middleware import register_middleware
10
+
11
+
12
+ @asynccontextmanager
13
+ async def _lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
14
+ """Application lifecycle: startup / shutdown."""
15
+ # Startup: DB init is deferred to first include_*() call
16
+ yield
17
+ # Shutdown: nothing to clean up (SQLite handles itself)
18
+
19
+
20
+ def create_app(config: Config) -> FastAPI:
21
+ """Create a FastAPI app instance. Register middleware, lifecycle hooks."""
22
+ app = FastAPI(title=config.app_name, debug=config.debug, lifespan=_lifespan)
23
+
24
+ # Store config for access elsewhere
25
+ app.state.config = config
26
+
27
+ # Set config for auth dependency injection
28
+ set_config_for_dependency(config)
29
+
30
+ # Register middleware (CORS, error handling)
31
+ register_middleware(app, config)
32
+
33
+ # Health check
34
+ @app.get("/")
35
+ def health_check():
36
+ return {"status": "ok", "app": config.app_name}
37
+
38
+ return app