-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathfastapi_example.py
More file actions
executable file
Β·522 lines (457 loc) Β· 19.5 KB
/
Copy pathfastapi_example.py
File metadata and controls
executable file
Β·522 lines (457 loc) Β· 19.5 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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
#!/usr/bin/env -S uv run --script
# /// script
# dependencies = [
# "uvicorn",
# "fastapi",
# "pydantic",
# "httpx",
# "anthropic",
# "openai",
# ]
# ///
"""FastAPI Integration Example for AI SDK Python.
This example demonstrates the essential AI SDK FastAPI integration features:
- Text generation with streaming
- Structured object generation
- Tool calling
- WebSocket chat
- Comprehensive AI SDK integration
Requires OPENAI_API_KEY environment variable.
"""
import os
import sys
from pathlib import Path
from typing import List, Dict, Any, Optional
# AI SDK should be available through uv
# FastAPI imports
try:
from fastapi import FastAPI, WebSocket, HTTPException, Request
from fastapi.responses import HTMLResponse, StreamingResponse
from fastapi.websockets import WebSocketDisconnect
except ImportError:
print("FastAPI not installed. Install with: pip install fastapi uvicorn")
exit(1)
# AI SDK imports
try:
from ai_sdk.providers.openai import create_openai
from ai_sdk.core.generate_text import generate_text, stream_text
from ai_sdk.core.generate_object import generate_object
from ai_sdk.integrations.fastapi import AIFastAPI
from ai_sdk.schemas.pydantic import pydantic_schema
from ai_sdk.tools.core import simple_tool
from ai_sdk.providers.types import Message
except ImportError as e:
print(f"AI SDK import error: {e}")
print("Make sure ai_sdk is installed and available")
exit(1)
# Pydantic for structured data
from pydantic import BaseModel, Field
# Core AI SDK models
class ChatRequest(BaseModel):
message: str
model: str = "gpt-4o-mini"
class BookRequest(BaseModel):
preferences: str
class BookRecommendation(BaseModel):
title: str = Field(description="Book title")
author: str = Field(description="Book author")
genre: str = Field(description="Book genre")
rating: int = Field(description="Rating 1-5", ge=1, le=5)
summary: str = Field(description="Brief summary")
why_recommended: str = Field(description="Why this book is recommended")
# AI SDK Tools
@simple_tool("get_weather", "Get current weather for a location", {
"type": "object",
"properties": {
"location": {"type": "string", "description": "The location to get weather for"}
},
"required": ["location"]
})
def get_weather(input_data: dict, options) -> str:
"""Mock weather tool for demonstration."""
location = input_data.get("location", "unknown location")
return f"The weather in {location} is sunny with 72Β°F temperature."
@simple_tool("calculate", "Perform mathematical calculations", {
"type": "object",
"properties": {
"expression": {"type": "string", "description": "Mathematical expression to calculate"}
},
"required": ["expression"]
})
def calculate(input_data: dict, options) -> str:
"""Safe calculator for basic math."""
try:
expression = input_data.get("expression", "")
# Simple safe evaluation (production would need more security)
result = eval(expression.replace(' ', '')) # Simplified for demo
return f"Result: {result}"
except:
return "Invalid mathematical expression"
# Main AI SDK FastAPI Application
def create_ai_app():
"""Create comprehensive AI application using AIFastAPI."""
# Initialize AI provider
api_key = os.getenv("OPENAI_API_KEY")
if not api_key:
raise ValueError("OPENAI_API_KEY environment variable is required")
provider = create_openai(api_key=api_key)
# Create AIFastAPI app with default provider
ai_app = AIFastAPI(default_provider=provider)
# Basic chat endpoint
@ai_app.app.post("/chat")
async def chat(request: ChatRequest):
"""Basic chat endpoint using AI SDK."""
try:
messages = [Message(role="user", content=request.message)]
result = await generate_text(
model=provider(request.model),
messages=messages,
max_tokens=1000,
)
return {"response": result.text}
except Exception as e:
raise HTTPException(status_code=500, detail=f"AI generation failed: {str(e)}")
# Streaming chat endpoint
@ai_app.app.post("/chat/stream")
async def stream_chat(request: ChatRequest):
"""Streaming chat endpoint using AI SDK."""
try:
messages = [Message(role="user", content=request.message)]
async def generate():
async for chunk in stream_text(
model=provider(request.model),
messages=messages,
max_tokens=1000,
):
if chunk.text_delta:
yield f'data: {{"text": "{chunk.text_delta}"}}\n\n'
yield "data: [DONE]\n\n"
return StreamingResponse(
generate(),
media_type="text/event-stream",
headers={
"Cache-Control": "no-cache",
"Connection": "keep-alive",
}
)
except Exception as e:
raise HTTPException(status_code=500, detail=f"Streaming failed: {str(e)}")
# Tool-enabled chat endpoint
@ai_app.app.post("/chat/tools")
async def chat_with_tools(request: ChatRequest):
"""Chat endpoint with tool calling support."""
try:
messages = [Message(role="user", content=request.message)]
result = await generate_text(
model=provider(request.model),
messages=messages,
tools=[get_weather, calculate],
max_tokens=1500
)
return {"response": result.text}
except Exception as e:
raise HTTPException(status_code=500, detail=f"Tool chat failed: {str(e)}")
# Structured object generation
@ai_app.app.post("/recommend/book")
async def recommend_book(request: BookRequest):
"""Generate structured book recommendations."""
try:
result = await generate_object(
model=provider("gpt-4o-mini"),
prompt=f"Recommend a book based on: {request.preferences}",
schema=pydantic_schema(BookRecommendation)
)
return {"book": result.object}
except Exception as e:
# Fallback response if generation fails
return {
"book": {
"title": "The Pragmatic Programmer",
"author": "David Thomas and Andrew Hunt",
"genre": "Technology",
"rating": 5,
"summary": "Essential guide for software developers with practical advice and techniques.",
"why_recommended": f"Fallback recommendation due to error: {str(e)}"
}
}
# WebSocket chat endpoint
@ai_app.app.websocket("/ws/chat")
async def websocket_chat(websocket: WebSocket):
"""Real-time WebSocket chat."""
await websocket.accept()
try:
while True:
# Receive message from client
data = await websocket.receive_json()
message = data.get("message", "")
if message:
messages = [Message(role="user", content=message)]
# Stream response back
async for chunk in stream_text(
model=provider("gpt-4o-mini"),
messages=messages,
tools=[get_weather, calculate]
):
if chunk.text_delta:
await websocket.send_json({
"type": "text_delta",
"text": chunk.text_delta
})
await websocket.send_json({"type": "done"})
except WebSocketDisconnect:
pass
except Exception as e:
await websocket.send_json({
"type": "error",
"error": str(e)
})
# Health check endpoint
@ai_app.app.get("/health")
async def health_check():
"""Health check endpoint."""
return {
"status": "healthy",
"ai_sdk": "python",
"provider": "openai",
"features": [
"chat",
"streaming",
"websocket",
"object_generation",
"tool_calling"
]
}
# List available tools endpoint
@ai_app.app.get("/tools")
async def list_tools():
"""List available tools."""
return {
"tools": [
{
"name": "get_weather",
"description": "Get current weather for a location",
"parameters": ["location"]
},
{
"name": "calculate",
"description": "Perform mathematical calculations",
"parameters": ["expression"]
}
]
}
return ai_app
# Enhanced demonstration HTML interface
def get_demo_html():
"""Simple HTML interface for testing AI SDK features."""
return HTMLResponse("""
<!DOCTYPE html>
<html>
<head>
<title>AI SDK FastAPI Demo</title>
<style>
body { font-family: Arial, sans-serif; margin: 20px; background: #f8f9fa; }
.container { max-width: 800px; margin: 0 auto; background: white; padding: 20px; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
.chat-area { border: 1px solid #ddd; height: 400px; overflow-y: auto; padding: 15px; margin: 15px 0; background: #fafafa; border-radius: 5px; }
.input-area { display: flex; gap: 10px; margin: 15px 0; align-items: center; }
input, button, select { padding: 10px; border: 1px solid #ddd; border-radius: 4px; }
input[type="text"] { flex: 1; }
button { background: #007bff; color: white; cursor: pointer; border: none; }
button:hover { background: #0056b3; }
.response { background: #e9ecef; padding: 15px; margin: 8px 0; border-radius: 5px; border-left: 4px solid #007bff; }
.user-msg { background: #d4edda; border-left-color: #28a745; }
.error { background: #f8d7da; border-left-color: #dc3545; }
</style>
</head>
<body>
<div class="container">
<h1>π€ AI SDK FastAPI Demo</h1>
<p>Test all AI SDK FastAPI integration features.</p>
<div class="chat-area" id="chatArea"></div>
<div class="input-area">
<input type="text" id="messageInput" placeholder="Ask me anything..." />
<select id="endpointSelect">
<option value="/chat">Basic Chat</option>
<option value="/chat/stream">Streaming Chat</option>
<option value="/chat/tools">Chat with Tools</option>
</select>
<button onclick="sendMessage()">Send</button>
</div>
<div class="input-area">
<input type="text" id="bookInput" placeholder="What kind of book?" />
<button onclick="getBookRecommendation()">π Get Book</button>
</div>
<button onclick="checkHealth()">π Health Check</button>
<button onclick="listTools()">π§ List Tools</button>
</div>
<script>
function addToChatArea(content, className = 'response') {
const chatArea = document.getElementById('chatArea');
chatArea.innerHTML += '<div class="' + className + '">' + content + '</div>';
chatArea.scrollTop = chatArea.scrollHeight;
}
async function sendMessage() {
const input = document.getElementById('messageInput');
const endpoint = document.getElementById('endpointSelect').value;
const message = input.value.trim();
if (!message) return;
addToChatArea('<strong>You:</strong> ' + message, 'user-msg');
input.value = '';
try {
const response = await fetch(endpoint, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ message: message })
});
if (endpoint === '/chat/stream') {
const reader = response.body.getReader();
let streamContent = '<strong>π€ AI:</strong> ';
while (true) {
const { done, value } = await reader.read();
if (done) break;
const chunk = new TextDecoder().decode(value);
const lines = chunk.split('\\n');
for (const line of lines) {
if (line.startsWith('data: ')) {
const data = line.slice(6);
if (data === '[DONE]') {
addToChatArea(streamContent);
return;
}
try {
const parsed = JSON.parse(data);
if (parsed.text) {
streamContent += parsed.text;
}
} catch (e) {}
}
}
}
} else {
const data = await response.json();
addToChatArea('<strong>π€ AI:</strong> ' + (data.response || data.error || 'No response'));
}
} catch (error) {
addToChatArea('<strong>Error:</strong> ' + error.message, 'error');
}
}
async function getBookRecommendation() {
const input = document.getElementById('bookInput');
const preferences = input.value.trim();
if (!preferences) return;
addToChatArea('<strong>You:</strong> Book for: ' + preferences, 'user-msg');
try {
const response = await fetch('/recommend/book', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ preferences: preferences })
});
const data = await response.json();
const book = data.book;
addToChatArea(
'<strong>π Book Recommendation:</strong><br/>' +
'<strong>Title:</strong> ' + book.title + '<br/>' +
'<strong>Author:</strong> ' + book.author + '<br/>' +
'<strong>Genre:</strong> ' + book.genre + '<br/>' +
'<strong>Rating:</strong> ' + book.rating + '/5β<br/>' +
'<strong>Summary:</strong> ' + book.summary + '<br/>' +
'<strong>Why:</strong> ' + book.why_recommended
);
} catch (error) {
addToChatArea('<strong>Error:</strong> ' + error.message, 'error');
}
}
async function checkHealth() {
try {
const response = await fetch('/health');
const data = await response.json();
addToChatArea('<strong>π’ Health:</strong> ' + data.status + ', Features: ' + data.features.join(', '));
} catch (error) {
addToChatArea('<strong>π΄ Error:</strong> ' + error.message, 'error');
}
}
async function listTools() {
try {
const response = await fetch('/tools');
const data = await response.json();
let toolsHtml = '<strong>π§ Available Tools:</strong><br/>';
data.tools.forEach(tool => {
toolsHtml += '<strong>' + tool.name + ':</strong> ' + tool.description + '<br/>';
});
addToChatArea(toolsHtml);
} catch (error) {
addToChatArea('<strong>Error:</strong> ' + error.message, 'error');
}
}
// Auto-focus message input and enable Enter key
document.getElementById('messageInput').addEventListener('keypress', function(e) {
if (e.key === 'Enter') {
sendMessage();
}
});
// Load health check on page load
window.onload = function() {
checkHealth();
};
</script>
</body>
</html>
""")
# Main application setup
def main():
"""Main function to run the FastAPI application with AI SDK features."""
print("π€ AI SDK FastAPI Integration Example")
print("=====================================")
# Check API key
api_key = os.getenv("OPENAI_API_KEY")
if not api_key:
print("β OPENAI_API_KEY environment variable is required")
print("Set it with: export OPENAI_API_KEY='your-api-key-here'")
return
try:
# Create AI application
ai_app = create_ai_app()
print("β
Created AI SDK FastAPI application")
# Add demo HTML endpoint
@ai_app.app.get("/")
async def root():
return get_demo_html()
print("π AI SDK FastAPI Application ready!")
print("\nπ Available endpoints:")
print(" GET / - π Interactive demo interface")
print(" GET /health - π Health check")
print(" GET /tools - π§ List available tools")
print(" POST /chat - π¬ Basic chat")
print(" POST /chat/stream - β‘ Streaming chat")
print(" POST /chat/tools - π οΈ Chat with tools")
print(" POST /recommend/book - π Book recommendations")
print(" WS /ws/chat - π WebSocket chat")
print("\nπ Starting server on http://localhost:8001")
print("π Open http://localhost:8001 in your browser for the interactive demo")
print("\nπ‘ Features demonstrated:")
print(" β
AI SDK integration with FastAPI")
print(" β
Text generation and streaming")
print(" β
Tool calling (weather, calculator)")
print(" β
Structured object generation")
print(" β
WebSocket real-time chat")
# Run the server
try:
import uvicorn
uvicorn.run(
ai_app.app,
host="0.0.0.0",
port=8001,
log_level="info"
)
except ImportError:
print("β uvicorn not available. Install with: pip install uvicorn")
except Exception as e:
print(f"β Failed to start application: {e}")
print("π‘ Troubleshooting:")
print(" 1. Check OPENAI_API_KEY is set correctly")
print(" 2. Ensure all dependencies are installed")
print(" 3. Verify ai_sdk package is available")
import traceback
traceback.print_exc()
if __name__ == "__main__":
print("π Starting AI SDK FastAPI Integration Example...")
main()