-
-
Notifications
You must be signed in to change notification settings - Fork 328
Expand file tree
/
Copy pathllms.txt
More file actions
274 lines (220 loc) · 8.07 KB
/
llms.txt
File metadata and controls
274 lines (220 loc) · 8.07 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
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
# Robyn
> Robyn is a high-performance, community-driven, and innovator-friendly async web framework for Python with a Rust runtime. It combines Python's ease of use with Rust's performance.
## Quick Facts
- Version: 0.79.0
- Python: >= 3.10
- License: BSD 2.0
- Repository: https://github.com/sparckles/robyn
- Documentation: https://robyn.tech/documentation
- Discord: https://discord.gg/rkERZ5eNU8
## Installation
```bash
pip install robyn
```
## Basic Usage
```python
from robyn import Robyn
app = Robyn(__file__)
@app.get("/")
async def index(request):
return "Hello, World!"
app.start(port=8080)
```
## Key Features
- **Rust Runtime**: Core server written in Rust using actix-web for high performance
- **Async/Sync Support**: Both async and sync route handlers supported
- **Multi-Process Scaling**: Built-in multiprocess execution via `--processes` and `--workers`
- **WebSockets**: Native WebSocket support
- **Middlewares**: Before/after request middlewares
- **Dependency Injection**: Built-in DI system
- **OpenAPI/Swagger**: Automatic OpenAPI documentation generation
- **Hot Reloading**: Development mode with `--dev` flag
- **AI Agents**: Built-in AI agent routing via `robyn.ai`
- **MCP Support**: Model Context Protocol server capabilities via `app.mcp`
- **Templating**: Jinja2 templating support (optional)
- **CORS**: Built-in CORS helper via `ALLOW_CORS()`
- **Authentication**: AuthenticationHandler base class for custom auth
- **Static Files**: Directory serving via `app.serve_directory()`
- **SSE**: Server-Sent Events support via `SSEResponse`
- **Easy Access Parameters**: Typed path/query params with automatic coercion in handler signatures
- **Direct Rust Integration**: Embed Rust code directly in routes
## Project Structure
```
robyn/
├── src/ # Rust source code
│ ├── lib.rs # PyO3 module entry point
│ ├── server.rs # Main HTTP server implementation
│ ├── types/ # Request, Response, Headers, Cookie types
│ ├── routers/ # HTTP, WebSocket, middleware routers
│ ├── executors/ # Route execution handlers
│ └── websockets/ # WebSocket implementation
├── robyn/ # Python package
│ ├── __init__.py # Main Robyn and SubRouter classes
│ ├── router.py # Python router implementation
│ ├── authentication.py # AuthenticationHandler
│ ├── dependency_injection.py
│ ├── openapi.py # OpenAPI generation
│ ├── mcp.py # MCP protocol support
│ ├── ai.py # AI agent support
│ ├── responses.py # Response helpers (serve_file, html, SSE)
│ ├── ws.py # WebSocket class
│ └── robyn.pyi # Type stubs
├── integration_tests/ # Integration test suite
├── unit_tests/ # Unit test suite
├── docs_src/ # Documentation (Next.js)
├── granian/ # Bundled Granian server (fork)
└── examples/ # Example applications
```
## Core Classes
### Robyn / SubRouter
Main application class and sub-router for modular routes.
```python
from robyn import Robyn, SubRouter
app = Robyn(__file__)
api = SubRouter(__file__, prefix="/api")
@api.get("/users")
def get_users(request):
return {"users": []}
app.include_router(api)
```
### Request Object
```python
request.method # HTTP method
request.url # Url object (scheme, host, path)
request.headers # Headers dict-like
request.query_params # QueryParams
request.path_params # Dict of URL params
request.body # Raw bytes
request.json() # Parse JSON body
request.form_data # Multipart form data
request.ip_addr # Client IP
request.identity # Identity (if authenticated)
```
### Response Object
```python
from robyn import Response
Response(
status_code=200,
headers={"Content-Type": "application/json"},
description="body content" # or body bytes
)
```
### Decorators
```python
@app.get("/path")
@app.post("/path")
@app.put("/path")
@app.delete("/path")
@app.patch("/path")
@app.head("/path")
@app.options("/path")
@app.before_request("/path") # Middleware before
@app.after_request("/path") # Middleware after
@app.startup_handler # Server startup
@app.shutdown_handler # Server shutdown
```
### WebSockets
```python
from robyn import WebSocketDisconnect
@app.websocket("/ws")
async def handler(websocket):
try:
while True:
msg = await websocket.receive_text()
await websocket.send_text(f"Echo: {msg}")
except WebSocketDisconnect:
pass
@handler.on_connect
def on_connect(websocket):
return "Connected"
@handler.on_close
def on_close(websocket):
return "Closed"
```
### Easy Access Parameters
Declare typed path and query parameters directly in handler signatures. Works for both HTTP and WebSocket handlers.
```python
from typing import List, Optional
# HTTP: path params + query params with type coercion
@app.get("/items/:id")
async def get_item(id: int, q: str, page: int = 1):
return {"id": id, "q": q, "page": page}
# Optional, List, and bool params
@app.get("/search")
def search(name: str, tags: List[str], active: bool = False, age: Optional[int] = None):
return {"name": name, "tags": tags, "active": active, "age": age}
# WebSocket: typed query params on handler and callbacks
@app.websocket("/ws")
async def handler(websocket, room: str = "default", page: int = 1):
while True:
msg = await websocket.receive_text()
await websocket.send_text(f"room={room} page={page} msg={msg}")
@handler.on_connect
def on_connect(websocket, room: str = "default"):
return f"connected to {room}"
```
### MCP (Model Context Protocol)
```python
@app.mcp.resource("time://current")
def get_time():
return datetime.now().isoformat()
@app.mcp.tool(name="calc", description="Calculate", input_schema={...})
def calculate(args):
return eval(args["expression"])
@app.mcp.prompt(name="explain", description="Explain code", arguments=[...])
def explain_prompt(args):
return f"Please explain: {args['code']}"
```
## CLI Commands
```bash
python app.py # Start server
python app.py --dev # Development mode (hot reload)
python app.py --processes 4 # Multi-process
python app.py --workers 2 # Workers per process
python app.py --log-level DEBUG # Log level
python app.py --open-browser # Open browser on start
python app.py --create # Create new project scaffold
python app.py --docs # Open documentation
```
## Development Setup
```bash
# Clone
git clone https://github.com/sparckles/robyn.git
cd robyn
# Virtual environment
python3 -m venv .venv && source .venv/bin/activate
# Install tools
pip install pre-commit poetry maturin
# Install dependencies
poetry install --with dev --with test
# Build Rust extension
maturin develop
# Run tests
pytest
```
## Key Dependencies
- **PyO3**: Rust-Python bindings
- **actix-web**: Rust HTTP server (via cookie crate)
- **orjson**: Fast JSON serialization
- **multiprocess**: Multi-process support
- **uvloop**: Fast event loop (non-Windows)
- **watchdog**: File watching for hot reload
## Configuration
Environment variables:
- `ROBYN_HOST`: Server host (default: 127.0.0.1)
- `ROBYN_PORT`: Server port (default: 8080)
- `ROBYN_DEV_MODE`: Enable dev mode
- `ROBYN_BROWSER_OPEN`: Open browser on start
- `ROBYN_CLIENT_TIMEOUT`: Client timeout seconds
- `ROBYN_KEEP_ALIVE_TIMEOUT`: Keep-alive timeout
## Documentation Structure
Main docs at `docs_src/src/pages/documentation/`:
- `api_reference/getting_started.mdx` - Quick start guide
- `api_reference/request_object.mdx` - Request handling
- `api_reference/middlewares.mdx` - Middleware usage
- `api_reference/websockets.mdx` - WebSocket guide
- `api_reference/authentication.mdx` - Auth patterns
- `api_reference/openapi.mdx` - OpenAPI docs
- `api_reference/agents.mdx` - AI agent integration
- `api_reference/mcps.mdx` - MCP server guide
- `example_app/` - Full example application tutorial