buildfastwithaibuildfastwithai
AI WorkshopsAll blogsAgentic AI Launchpad
Agentic AI Launchpad
Unrot Logo5 min AI learning appUnrotLearn AI in 5 minutes a day.Get the appNext live workshopFree AI WorkshopLive session, recording includedReserve a seat

Newsletter

Stay ahead

AI tools and tips. No spam.

Share
Back to blogs
Tutorials
Coding

How to Build the World's Fastest AI Game Generator with Qwen + Cerebras

August 8, 2025
4 min read
Share:
How to Build the World's Fastest AI Game Generator with Qwen + Cerebras
Share:

How to Build the World's Fastest AI Game Generator with Qwen and Cerebras

In today's rapidly evolving AI landscape, creating interactive applications that generate content in real-time has become increasingly popular. What if you could build an AI-powered game generator that creates playable HTML5 games from simple text descriptions? That's exactly what we'll explore in this tutorial - building the World's Fastest nGame Generator using Alibaba's Qwen3-Coder model and Streamlit.

Introduction: What is This Project About?

Instantly turn text prompts into playable games with the world’s fastest AI game generator — powered by Cerebras Systems and the Qwen-235B model.

  • Describe your game idea (e.g., “Flappy Bird with rockets”) and see it live in seconds

  • Built on Qwen-235B with 256K token context (scalable to 1M) — perfect for large codebases

  • Powered by Cerebras Systems with blazing 1,500–2,000 tokens/sec inference speed

  • Generate and edit HTML5 games in real-time using a Streamlit-based chat interface

  • No coding required — just prompt, play, and tweak instantly in your browser

<iframe src="https://drive.google.com/file/d/FILE_ID/preview" width="640" height="480" allow="autoplay"></iframe>

AI Integration: Cerebras + Qwen3-Coder

from langchain_openai import ChatOpenAI

def get_llm(api_key, model_name):
    return ChatOpenAI(
        model=model_name,
        openai_api_key=api_key,
        openai_api_base="https://api.cerebras.ai/v1"
    )

This setup allows us to connect to the Cerebras API for Qwen3-Coder access.

Architecture and Workflow

Step 1: Project Setup

mkdir qwen-game-generator
cd qwen-game-generator
python -m venv venv
source venv/bin/activate  # or venv\Scripts\activate on Windows
pip install streamlit langchain-openai

Step 2: Create Requirements File

streamlit
langchain-openai

Step 3: Main Application Code

import streamlit as st
from langchain_openai import ChatOpenAI
import os

st.set_page_config(page_title="🎮 World's Fastest Game Generator", layout="centered")

st.sidebar.image("https://github.com/pratik-gond/temp_files/blob/main/image-removebg-preview.png?raw=true", use_container_width=True)
st.sidebar.header("⚙️ Configuration")
model_name = st.sidebar.selectbox("Model", ["qwen-3-235b-a22b-instruct-2507"], index=0)

try:
    api_key = st.secrets["CEREBRAS_API_KEY"]
except KeyError:
    st.error("⚠️ Cerebras API Key not found in secrets.")
    api_key = None

st.sidebar.markdown("### About Qwen Model")
st.sidebar.markdown("Powered by Qwen model from Cerebras, delivering lightning-fast AI responses at **1500 tokens per second**.")

@st.cache_resource(show_spinner=False)
def get_llm(api_key, model_name):
    return ChatOpenAI(
        model=model_name,
        openai_api_key=api_key,
        openai_api_base="https://api.cerebras.ai/v1"
    )

if "messages" not in st.session_state:
    st.session_state.messages = []
if "game_code" not in st.session_state:
    st.session_state.game_code = ""

st.title("🎮 World's Fastest Game Generator")
st.markdown('*Built by [Build Fast with AI](https://buildfastwithai.com/genai-course) - Learn to build AI apps like this!*', unsafe_allow_html=True)

Step 4: Chat Interface Implementation

if api_key:
    for msg in st.session_state.messages:
        with st.chat_message(msg["role"]):
            st.markdown(msg["content"])

    user_input = st.chat_input("Describe your game or suggest an improvement...")

    if user_input:
        st.chat_message("user").markdown(user_input)
        st.session_state.messages.append({"role": "user", "content": user_input})

        is_game_creation = "<html" not in st.session_state.game_code.lower()

        if is_game_creation:
            full_prompt = f"""
You're an expert HTML5 game developer.

Generate a visually appealing and playable HTML5 game based on the following idea.
Requirements:
- Canvas-based game
- Retry button after losing
- Entire game in one standalone HTML file
- NO markdown (no triple backticks)

Game idea: {user_input}
"""
        else:
            full_prompt = f"""
Improve the following HTML5 game based on the user request.

Request: "{user_input}"

Only return a full, standalone HTML file (no explanations or markdown).

Game code:
{st.session_state.game_code}
"""

        with st.chat_message("assistant"):
            with st.spinner("🧠 Thinking... Generating your game..."):
                try:
                    llm = get_llm(api_key, model_name)
                    response = llm.invoke(full_prompt)
                    game_html = response.content.strip()

                    if "<html" not in game_html.lower():
                        st.error("❌ Invalid HTML received. Try rephrasing your request.")
                    else:
                        st.session_state.game_code = game_html
                        st.session_state.messages.append({
                            "role": "assistant",
                            "content": "✅ Game updated! See below 👇",
                        })
                        st.rerun()

                except Exception as e:
                    st.error(f"Cerebras API Error: {str(e)}")

Step 5: Game Display and Download

    if st.session_state.game_code:
        st.divider()
        st.subheader("🎮 Your Game")
        st.components.v1.html(st.session_state.game_code, height=600, scrolling=False)

        st.download_button(
            label="⬇️ Download Game HTML",
            data=st.session_state.game_code,
            file_name="ai_game.html",
            mime="text/html"
        )
else:
    st.error("Please add your Cerebras API Key to .streamlit/secrets.toml")

Step 6: Configuration Setup

# .streamlit/secrets.toml
CEREBRAS_API_KEY = "your-cerebras-api-key-here"

Advanced Features and Customizations

Adding New Models

model_name = st.sidebar.selectbox("Model", [
    "qwen-3-235b-a22b-instruct-2507",
    "gpt-4o-mini",
    "claude-3-5-sonnet"
], index=0)

Customizing Game Requirements

full_prompt = f"""
You're an expert HTML5 game developer.

Generate a visually appealing and playable HTML5 game based on the following idea.
Requirements:
- Canvas-based game
- Retry button after losing
- Sound effects (if possible)
- Mobile-responsive design
- High score tracking
- Entire game in one standalone HTML file
- NO markdown (no triple backticks)

Game idea: {user_input}
"""

Adding Analytics

if st.session_state.game_code:
    st.metric("Games Generated", len(st.session_state.messages) // 2)
    st.metric("Current Game Size", f"{len(st.session_state.game_code)} characters")
LLM AGENTSRAG PIPELINESTOOL CALLINGDEPLOYMENT
Let's build

Start building AI agents with Build Fast

Explore Program

Error Handling and Validation

try:
    api_key = st.secrets["CEREBRAS_API_KEY"]
except KeyError:
    st.error("⚠️ Cerebras API Key not found in secrets...")

if "<html" not in game_html.lower():
    st.error("❌ Invalid HTML received. Try rephrasing your request.")

Running the Application

pip install -r requirements.txt
streamlit run app.py

Cohort program

Claude MasteryCowork & Code

Explore programNo coding needed

Conclusion

The application bridges the gap between AI capabilities and practical game development. By leveraging Qwen3-Coder's code generation and Cerebras' fast inference, we created a tool that's both powerful and accessible.

Resources and Community

Join our community of 12,000+ AI enthusiasts and learn to build powerful AI applications! Whether you're a beginner or an experienced developer, our resources will help you understand and implement Generative AI in your projects.

  • Website: www.buildfastwithai.com

  • LinkedIn: linkedin.com/company/build-fast-with-ai/

  • Instagram: instagram.com/buildfastwithai/

  • Twitter: x.com/satvikps

  • Telegram: t.me/BuildFastWithAI

Enjoyed this article? Share it →
Share:
    You Might Also Like
    Replit's AI Model Routing Is Here: How Intelligent Routing Cuts Costs (2026)
    Analysis
    Replit's AI Model Routing Is Here: How Intelligent Routing Cuts Costs (2026)

    Replit's Intelligent Model Routing automatically chooses the best AI model for each task. Learn how its 65% lower average cost claim works, Free Mode, enterprise controls, tradeoffs and what it means for AI coding.

    What Is an AI Agent? Beginner Guide With Examples (2026)
    Tutorials
    What Is an AI Agent? Beginner Guide With Examples (2026)

    What is an AI agent? Learn how AI agents work, how they differ from chatbots, their core components, types, real examples, tools, memory, workflows, risks and how to build one in 2026.