acceptable-dream-85180
07/29/2025, 7:55 PMtall-airline-16756
07/29/2025, 7:55 PMtall-airline-16756
07/29/2025, 7:56 PMimport os
from livekit import api
# Load environment variables
LIVEKIT_API_KEY = os.environ.get("LIVEKIT_API_KEY")
LIVEKIT_API_SECRET = os.environ.get("LIVEKIT_API_SECRET")
def generate_token(room_name, identity=None, name=None):
if not identity:
identity = f"python-user-{room_name}"
if not name:
name = identity
if not LIVEKIT_API_KEY or not LIVEKIT_API_SECRET:
raise ValueError("LIVEKIT_API_KEY and LIVEKIT_API_SECRET must be set")
token = (
api.AccessToken(LIVEKIT_API_KEY, LIVEKIT_API_SECRET)
.with_identity(identity)
.with_name(name)
.with_grants(
api.VideoGrants(
room_join=True,
room=room_name,
)
)
.to_jwt()
)
return token
2. Optional Flask Integration:If you are using Flask, you can integrate token generation as follows:
`from flask import Flask, request, jsonify
from livekit import api
app = Flask(name)
@app.route('/generate-token', methods=['POST'])
def generate_token():
data = request.json
room_name = data.get("room_name")
participant_identity = data.get("identity")
if not room_name or not participant_identity:
return jsonify({"error": "Missing roomName or identity"}), 400
token = api.AccessToken(LIVEKIT_API_KEY, LIVEKIT_API_SECRET) \
.with_identity(participant_identity) \
.with_name(participant_identity) \
.with_grants(api.VideoGrants(
room_join=True,
room=room_name,
)).to_jwt()
return jsonify({"token": token})`This will generate a JWT token that allows the participant to join the specified room with the configured permissions.
Sources: livekit-api/livekit/api/access_token.py | auth.py | complex-agents/turn-taking/turn-taking-frontend/app/api/connection-details/...