Skip to content

Add Streamlit playground for live TAC demos#50

Open
xinghaohuang91 wants to merge 2 commits into
mainfrom
playground-demo
Open

Add Streamlit playground for live TAC demos#50
xinghaohuang91 wants to merge 2 commits into
mainfrom
playground-demo

Conversation

@xinghaohuang91
Copy link
Copy Markdown
Contributor

Summary

Type of Change

  • Bug fix
  • New feature
  • Breaking change
  • Documentation update
  • Refactoring

Checklist

  • Tests added/updated
  • Documentation updated
  • Tested E2E

SDK Parity

This is the Python SDK. If this change affects shared functionality, ensure the TypeScript SDK is updated as well.

Tip: Use the /sync-to-ts-sdk skill in Claude Code to automatically generate and create a TypeScript SDK PR from your changes.

  • Change is Python-specific (no TypeScript update needed)
  • TypeScript SDK PR created:

Copilot AI review requested due to automatic review settings May 15, 2026 16:57
Copy link
Copy Markdown

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Adds a Streamlit-based interactive playground that lets users enter their Twilio/TAC/OpenAI credentials in a sidebar and spin up a TAC FastAPI server in a background thread for live webhook testing. Intended to be deployed to Streamlit Community Cloud, Hugging Face Spaces, or Railway.

Changes:

  • New playground/app.py Streamlit UI that boots TACFastAPIServer + voice/SMS channels with an OpenAI-backed on_message_ready handler.
  • Supporting deployment files: playground/requirements.txt (installs TAC from ../.[server]), playground/packages.txt, and playground/README.md with deploy/usage docs.
  • .streamlit/config.toml enabling XSRF protection, capping uploads at 5 MB, and disabling usage stats.

Reviewed changes

Copilot reviewed 5 out of 5 changed files in this pull request and generated 6 comments.

Show a summary per file
File Description
playground/app.py Streamlit UI; credential intake, background uvicorn thread, message handler, webhook URL panel.
playground/requirements.txt Streamlit/uvicorn/openai/dotenv deps plus editable install of TAC with [server] extras.
playground/packages.txt Empty placeholder for HF Spaces system packages.
playground/README.md Deploy instructions for Streamlit Cloud / HF Spaces / Railway and local usage.
.streamlit/config.toml Streamlit server/browser configuration.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread playground/app.py
Comment on lines +227 to +238
def run_server():
config = uvicorn.Config(
server.app,
host="0.0.0.0",
port=8000,
log_level="info",
)
server_instance = uvicorn.Server(config)
asyncio.run(server_instance.serve())

thread = threading.Thread(target=run_server, daemon=True)
thread.start()
Comment thread playground/app.py
Comment on lines +251 to +256
if st.button(
"🛑 Stop Server", disabled=not st.session_state.server_running, type="secondary"
):
st.session_state.server_running = False
st.session_state.server_thread = None
st.info("Server stopped. Refresh the page to start a new session.")
Comment thread playground/app.py
Comment on lines +141 to +161
os.environ["TWILIO_ACCOUNT_SID"] = twilio_sid
os.environ["TWILIO_AUTH_TOKEN"] = twilio_token
os.environ["TAC_API_KEY"] = tac_api_key
os.environ["TAC_API_TOKEN"] = tac_api_token
os.environ["TAC_CONVERSATION_CONFIGURATION_ID"] = tac_conversation_config
if tac_memory_store:
os.environ["TAC_MEMORY_STORE_ID"] = tac_memory_store
os.environ["OPENAI_API_KEY"] = openai_key

try:
# Import here after env vars are set
from openai import AsyncOpenAI
from openai.types.chat import (
ChatCompletionAssistantMessageParam,
ChatCompletionMessageParam,
ChatCompletionSystemMessageParam,
ChatCompletionUserMessageParam,
)

# Initialize TAC
tac = TAC(config=TACConfig.from_env())
Comment thread playground/app.py
Comment on lines +268 to +291
# Get Streamlit app URL
# Streamlit Cloud provides this in session state
app_url = st.query_params.get("url", "https://<your-streamlit-app>.streamlit.app")

# If we can detect the actual URL, use it
if "streamlit.app" not in app_url:
app_url = "https://<your-streamlit-app>.streamlit.app"

st.markdown("### Your Webhook URLs:")
st.code(f"{app_url}/twiml", language="text")
st.code(f"{app_url}/webhook", language="text")

st.info(
"""
**Next Steps:**
1. Copy the webhook URLs above
2. Go to [Twilio Console](https://console.twilio.com/us1/develop/phone-numbers/manage/incoming)
3. Select your phone number
4. Set **Voice webhook** to: `/twiml`
5. Set **SMS webhook** to: `/webhook`
6. Send a message or call your number!
"""
)

Comment thread playground/app.py
Comment on lines +169 to +212
conversation_history: dict[str, list[ChatCompletionMessageParam]] = {}

SYSTEM_MESSAGE: ChatCompletionSystemMessageParam = {
"role": "system",
"content": (
"You are a customer service agent speaking with a user over voice or SMS. "
"Keep responses short and conversational — a sentence or two. "
"Do not use markdown, asterisks, bullets, or emojis."
),
}

async def handle_message_ready(
user_message: str,
context: ConversationSession,
memory_response: TACMemoryResponse | None,
) -> str:
"""Handle incoming messages"""
conv_id = context.conversation_id

try:
if conv_id not in conversation_history:
conversation_history[conv_id] = [SYSTEM_MESSAGE]

user_msg: ChatCompletionUserMessageParam = {
"role": "user",
"content": user_message,
}
conversation_history[conv_id].append(user_msg)

# Use TAC memory adapter
client = with_tac_memory(openai_client, memory_response, context)

response = await client.chat.completions.create(
model="gpt-4o-mini",
messages=conversation_history[conv_id],
)

llm_response = response.choices[0].message.content or ""

assistant_msg: ChatCompletionAssistantMessageParam = {
"role": "assistant",
"content": llm_response,
}
conversation_history[conv_id].append(assistant_msg)
Comment thread playground/app.py
Comment on lines +66 to +67
if "server_port" not in st.session_state:
st.session_state.server_port = 8501 # Streamlit's port
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants