Practical implementation examples for common use cases with the Freddy API.
import requests
import os
# Basic AI response generation
def generate_response(prompt):
api_key = os.getenv('FREDDY_API_KEY')
response = requests.post(
"https://api.freddy.ai/v2/model/response",
headers={
"api-key": api_key,
"Content-Type": "application/json"
},
json={
"model": "gpt-4",
"messages": [
{"role": "user", "content": prompt}
],
"max_tokens": 150,
"temperature": 0.7
}
)
if response.status_code == 200:
return response.json()["data"]["message"]["content"]
else:
raise Exception(f"API Error: {response.status_code} - {response.text}")
# Usage
result = generate_response("Explain quantum computing in simple terms")
print(result)import requests
class FreddyAuth:
def __init__(self, base_url="https://api.freddy.ai/v2"):
self.base_url = base_url
self.access_token = None
def register(self, email, password, first_name, last_name):
"""Register a new user."""
response = requests.post(
f"{self.base_url}/auth/register",
json={
"email": email,
"password": password,
"first_name": first_name,
"last_name": last_name
}
)
return response.json()
def login(self, email, password):
"""Login and store access token."""
response = requests.post(
f"{self.base_url}/auth/login",
json={
"email": email,
"password": password
}
)
if response.status_code == 200:
data = response.json()["data"]
self.access_token = data["access_token"]
return data
else:
raise Exception(f"Login failed: {response.text}")
def get_user_profile(self):
"""Get current user profile."""
if not self.access_token:
raise Exception("Not authenticated")
response = requests.get(
f"{self.base_url}/users/me",
headers={"Authorization": f"Bearer {self.access_token}"}
)
return response.json()
# Usage
auth = FreddyAuth()
auth.login("user@example.com", "password")
profile = auth.get_user_profile()
print(f"Welcome, {profile['data']['first_name']}!")class ConversationManager:
def __init__(self, api_key):
self.api_key = api_key
self.base_url = "https://api.freddy.ai/v2"
self.headers = {
"api-key": api_key,
"Content-Type": "application/json"
}
def create_thread(self, title, initial_message=None):
"""Create a new conversation thread."""
payload = {"title": title}
if initial_message:
payload["initial_message"] = {
"role": "user",
"content": initial_message
}
response = requests.post(
f"{self.base_url}/threads",
headers=self.headers,
json=payload
)
return response.json()
def send_message(self, thread_id, content, role="user"):
"""Send a message to a thread."""
response = requests.post(
f"{self.base_url}/threads/{thread_id}/messages",
headers=self.headers,
json={
"role": role,
"content": content
}
)
return response.json()
def get_conversation_history(self, thread_id):
"""Get all messages in a thread."""
response = requests.get(
f"{self.base_url}/threads/{thread_id}/messages",
headers=self.headers
)
return response.json()["data"]
def generate_ai_response(self, thread_id, model="gpt-4"):
"""Generate AI response based on conversation history."""
# Get conversation history
messages = self.get_conversation_history(thread_id)
# Generate response
response = requests.post(
f"{self.base_url}/model/response",
headers=self.headers,
json={
"model": model,
"messages": messages,
"max_tokens": 500,
"temperature": 0.7
}
)
ai_response = response.json()["data"]["message"]["content"]
# Save AI response to thread
self.send_message(thread_id, ai_response, role="assistant")
return ai_response
# Usage
chat = ConversationManager(os.getenv('FREDDY_API_KEY'))
# Create new conversation
thread = chat.create_thread("Help with Python", "I need help with Python lists")
thread_id = thread["data"]["thread_id"]
# Send user message
chat.send_message(thread_id, "How do I append items to a list?")
# Generate AI response
ai_response = chat.generate_ai_response(thread_id)
print(f"AI: {ai_response}")class CustomAssistant:
def __init__(self, api_key, assistant_config):
self.api_key = api_key
self.config = assistant_config
self.headers = {
"api-key": api_key,
"Content-Type": "application/json"
}
def create_assistant(self):
"""Create a custom AI assistant."""
response = requests.post(
"https://api.freddy.ai/v2/assistants",
headers=self.headers,
json=self.config
)
return response.json()
def chat_with_assistant(self, assistant_id, user_message, context=None):
"""Chat with the custom assistant."""
messages = []
if context:
messages.append({"role": "system", "content": context})
messages.append({"role": "user", "content": user_message})
response = requests.post(
f"https://api.freddy.ai/v2/assistants/{assistant_id}/chat",
headers=self.headers,
json={"messages": messages}
)
return response.json()["data"]["message"]["content"]
# Create a coding assistant
coding_assistant_config = {
"name": "Python Coding Assistant",
"description": "Helps with Python programming questions",
"instructions": "You are an expert Python developer. Provide clear, concise code examples and explanations.",
"model": "gpt-4",
"tools": ["code_interpreter"]
}
assistant = CustomAssistant(os.getenv('FREDDY_API_KEY'), coding_assistant_config)
assistant_data = assistant.create_assistant()
assistant_id = assistant_data["data"]["assistant_id"]
# Chat with the assistant
response = assistant.chat_with_assistant(
assistant_id,
"How do I read a CSV file in Python?",
context="The user is a beginner programmer"
)
print(response)import os
from pathlib import Path
class FileManager:
def __init__(self, api_key):
self.api_key = api_key
self.headers = {"api-key": api_key}
def upload_file(self, file_path, purpose="assistant"):
"""Upload a file to Freddy."""
file_path = Path(file_path)
with open(file_path, 'rb') as file:
files = {'file': (file_path.name, file, 'application/octet-stream')}
data = {'purpose': purpose}
response = requests.post(
"https://api.freddy.ai/v2/files",
headers=self.headers,
files=files,
data=data
)
return response.json()
def list_files(self):
"""List all uploaded files."""
response = requests.get(
"https://api.freddy.ai/v2/files",
headers=self.headers
)
return response.json()["data"]
def download_file(self, file_id, save_path):
"""Download a file by ID."""
response = requests.get(
f"https://api.freddy.ai/v2/files/{file_id}/content",
headers=self.headers
)
with open(save_path, 'wb') as file:
file.write(response.content)
return save_path
def delete_file(self, file_id):
"""Delete a file by ID."""
response = requests.delete(
f"https://api.freddy.ai/v2/files/{file_id}",
headers=self.headers
)
return response.status_code == 204
# Usage
file_manager = FileManager(os.getenv('FREDDY_API_KEY'))
# Upload a document
upload_result = file_manager.upload_file("./document.pdf", purpose="assistant")
file_id = upload_result["data"]["file_id"]
print(f"Uploaded file: {file_id}")
# List all files
files = file_manager.list_files()
for file in files:
print(f"File: {file['filename']} (ID: {file['file_id']})")
# Download the file
file_manager.download_file(file_id, "./downloaded_document.pdf")class OrganizationManager:
def __init__(self, api_key):
self.api_key = api_key
self.headers = {
"api-key": api_key,
"Content-Type": "application/json"
}
def create_organization(self, name, description=""):
"""Create a new organization."""
response = requests.post(
"https://api.freddy.ai/v2/organizations",
headers=self.headers,
json={
"name": name,
"description": description
}
)
return response.json()
def invite_member(self, org_id, email, role="member"):
"""Invite a user to an organization."""
response = requests.post(
f"https://api.freddy.ai/v2/organizations/{org_id}/invite",
headers=self.headers,
json={
"email": email,
"role": role
}
)
return response.json()
def list_members(self, org_id):
"""List organization members."""
response = requests.get(
f"https://api.freddy.ai/v2/organizations/{org_id}/members",
headers=self.headers
)
return response.json()["data"]
def get_user_organizations(self):
"""Get organizations for current user."""
response = requests.get(
"https://api.freddy.ai/v2/organizations",
headers=self.headers
)
return response.json()["data"]
# Usage
org_manager = OrganizationManager(os.getenv('FREDDY_API_KEY'))
# Create organization
org = org_manager.create_organization("Acme Corp", "AI-powered solutions")
org_id = org["data"]["org_id"]
# Invite team members
org_manager.invite_member(org_id, "alice@acme.com", "admin")
org_manager.invite_member(org_id, "bob@acme.com", "member")
# List members
members = org_manager.list_members(org_id)
for member in members:
print(f"{member['email']} - {member['role']}")from datetime import datetime, timedelta
import matplotlib.pyplot as plt
class AnalyticsClient:
def __init__(self, api_key):
self.api_key = api_key
self.headers = {"api-key": api_key}
def get_usage_stats(self, start_date, end_date, granularity="day"):
"""Get usage statistics for a date range."""
params = {
"start_date": start_date.strftime("%Y-%m-%d"),
"end_date": end_date.strftime("%Y-%m-%d"),
"granularity": granularity
}
response = requests.get(
"https://api.freddy.ai/v2/analytics/usage",
headers=self.headers,
params=params
)
return response.json()["data"]
def get_cost_breakdown(self, start_date, end_date):
"""Get cost breakdown by model/service."""
params = {
"start_date": start_date.strftime("%Y-%m-%d"),
"end_date": end_date.strftime("%Y-%m-%d")
}
response = requests.get(
"https://api.freddy.ai/v2/analytics/costs",
headers=self.headers,
params=params
)
return response.json()["data"]
def plot_usage_trends(self, days=30):
"""Plot usage trends over time."""
end_date = datetime.now()
start_date = end_date - timedelta(days=days)
usage_data = self.get_usage_stats(start_date, end_date)
dates = [datetime.strptime(item["date"], "%Y-%m-%d") for item in usage_data["breakdown"]]
requests_count = [item["requests"] for item in usage_data["breakdown"]]
tokens_used = [item["tokens"] for item in usage_data["breakdown"]]
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(12, 8))
# Plot requests
ax1.plot(dates, requests_count, marker='o')
ax1.set_title("API Requests Over Time")
ax1.set_ylabel("Requests")
ax1.grid(True)
# Plot tokens
ax2.plot(dates, tokens_used, marker='s', color='orange')
ax2.set_title("Token Usage Over Time")
ax2.set_ylabel("Tokens")
ax2.set_xlabel("Date")
ax2.grid(True)
plt.tight_layout()
plt.show()
# Usage
analytics = AnalyticsClient(os.getenv('FREDDY_API_KEY'))
# Get last 30 days usage
end_date = datetime.now()
start_date = end_date - timedelta(days=30)
usage = analytics.get_usage_stats(start_date, end_date)
print(f"Total requests: {usage['total_requests']}")
print(f"Total tokens: {usage['total_tokens']}")
print(f"Total cost: ${usage['cost']:.2f}")
# Plot trends
analytics.plot_usage_trends(30)from flask import Flask, request, jsonify
import hmac
import hashlib
app = Flask(__name__)
class WebhookHandler:
def __init__(self, webhook_secret):
self.webhook_secret = webhook_secret
def verify_signature(self, payload, signature):
"""Verify webhook signature."""
expected_signature = hmac.new(
self.webhook_secret.encode(),
payload,
hashlib.sha256
).hexdigest()
return hmac.compare_digest(f"sha256={expected_signature}", signature)
def handle_user_created(self, data):
"""Handle user.created webhook."""
user_id = data["user_id"]
email = data["email"]
# Send welcome email
print(f"Sending welcome email to {email}")
# Initialize user data
print(f"Initializing data for user {user_id}")
def handle_message_created(self, data):
"""Handle message.created webhook."""
message_id = data["message_id"]
thread_id = data["thread_id"]
content = data["content"]
# Process message for analytics
print(f"Processing message {message_id} in thread {thread_id}")
def handle_usage_threshold(self, data):
"""Handle usage.threshold webhook."""
user_id = data["user_id"]
threshold = data["threshold"]
current_usage = data["current_usage"]
# Send usage alert
print(f"User {user_id} reached {threshold}% usage ({current_usage} tokens)")
webhook_handler = WebhookHandler(os.getenv('WEBHOOK_SECRET'))
@app.route('/webhook', methods=['POST'])
def handle_webhook():
# Verify signature
signature = request.headers.get('X-Freddy-Signature')
if not webhook_handler.verify_signature(request.data, signature):
return jsonify({"error": "Invalid signature"}), 401
# Parse webhook data
data = request.json
event_type = data.get('event')
event_data = data.get('data')
# Route to appropriate handler
if event_type == 'user.created':
webhook_handler.handle_user_created(event_data)
elif event_type == 'message.created':
webhook_handler.handle_message_created(event_data)
elif event_type == 'usage.threshold':
webhook_handler.handle_usage_threshold(event_data)
return jsonify({"status": "processed"}), 200
if __name__ == '__main__':
app.run(debug=True, port=5000)import os
import logging
from dataclasses import dataclass
from typing import List, Optional
@dataclass
class ChatMessage:
role: str
content: str
timestamp: Optional[str] = None
class FreddyApp:
"""Complete Freddy application example."""
def __init__(self, api_key: str):
self.api_key = api_key
self.headers = {
"api-key": api_key,
"Content-Type": "application/json"
}
self.logger = self._setup_logging()
def _setup_logging(self):
"""Set up structured logging."""
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
return logging.getLogger(__name__)
def create_chat_session(self, title: str) -> str:
"""Create a new chat session."""
try:
response = requests.post(
"https://api.freddy.ai/v2/threads",
headers=self.headers,
json={"title": title}
)
response.raise_for_status()
thread_id = response.json()["data"]["thread_id"]
self.logger.info(f"Created chat session: {thread_id}")
return thread_id
except Exception as e:
self.logger.error(f"Failed to create chat session: {e}")
raise
def send_message(self, thread_id: str, message: str) -> str:
"""Send message and get AI response."""
try:
# Send user message
requests.post(
f"https://api.freddy.ai/v2/threads/{thread_id}/messages",
headers=self.headers,
json={"role": "user", "content": message}
)
# Get conversation history
history_response = requests.get(
f"https://api.freddy.ai/v2/threads/{thread_id}/messages",
headers=self.headers
)
messages = history_response.json()["data"]
# Generate AI response
ai_response = requests.post(
"https://api.freddy.ai/v2/model/response",
headers=self.headers,
json={
"model": "gpt-4",
"messages": messages,
"max_tokens": 500,
"temperature": 0.7
}
)
ai_content = ai_response.json()["data"]["message"]["content"]
# Save AI response
requests.post(
f"https://api.freddy.ai/v2/threads/{thread_id}/messages",
headers=self.headers,
json={"role": "assistant", "content": ai_content}
)
self.logger.info(f"Generated response for thread {thread_id}")
return ai_content
except Exception as e:
self.logger.error(f"Failed to send message: {e}")
raise
def get_chat_history(self, thread_id: str) -> List[ChatMessage]:
"""Get chat history as structured data."""
try:
response = requests.get(
f"https://api.freddy.ai/v2/threads/{thread_id}/messages",
headers=self.headers
)
response.raise_for_status()
messages_data = response.json()["data"]
return [
ChatMessage(
role=msg["role"],
content=msg["content"],
timestamp=msg.get("timestamp")
)
for msg in messages_data
]
except Exception as e:
self.logger.error(f"Failed to get chat history: {e}")
raise
# Usage
def main():
app = FreddyApp(os.getenv('FREDDY_API_KEY'))
# Create chat session
thread_id = app.create_chat_session("Python Help Session")
# Interactive chat loop
print("Chat with Freddy AI (type 'quit' to exit)")
while True:
user_input = input("You: ")
if user_input.lower() == 'quit':
break
ai_response = app.send_message(thread_id, user_input)
print(f"AI: {ai_response}")
# Show chat history
print("\n--- Chat History ---")
history = app.get_chat_history(thread_id)
for msg in history:
print(f"{msg.role.title()}: {msg.content}")
if __name__ == "__main__":
main()- Best Practices - Recommended patterns and practices
- Authentication Guide - Secure API access
- Error Handling - Comprehensive error management
- API Reference - Complete endpoint documentation
Build amazing applications with these practical examples! 📝