writing-streamlit-apps
O que ela faz
Esta skill explica como escrever o código em Python de um app Streamlit que roda dentro do PostHog, incluindo como ler os dados do PostHog. É para desenvolvedores que criam apps de dados e querem que eles funcionem de forma confiável.
Quando usar
- ✓Quando você está escrevendo o código em Python de um app Streamlit que lê dados do PostHog.
- ✓Quando um app Streamlit fica lento ou se comporta mal depois que o Streamlit reexecuta.
- ✓Quando você precisa adicionar arquivos auxiliares ou arquivos de dados ao lado do arquivo principal do app.
Link da skill
https://github.com/PostHog/posthog/blob/master/products/streamlit_apps/skills/writing-streamlit-apps/SKILL.mdCopie e cole na sua IA (Claude, ChatGPT ou Cursor) pedindo para seguir as instruções.
Como usar
O jeito mais fácil: copie a mensagem e cole na sua IA. Ela lê a skill e segue as instruções.
Mensagem pronta para colar
Para Claude Code, Codex ou Cursor: rode na pasta do projeto e a skill fica instalada.
Baixe o SKILL.md e coloque na pasta de skills do seu agente.
Exemplo do que pedir para a IA
“Me ajude a escrever o Python de um app Streamlit que mostre em gráfico os eventos diários do PostHog.”
5 skills novas por semana. 1 minuto de leitura.
Como funciona
Ela mostra a forma embutida de ler dados do PostHog para uma tabela, as bibliotecas já disponíveis no sandbox e padrões de cache e de estado. Também explica como adicionar módulos auxiliares e arquivos de dados ao lado do arquivo principal.
Conteúdo técnico (SKILL.md original)
Texto original do autor, em inglês, direto do GitHub.
Writing Streamlit apps for the PostHog sandbox
The source you write becomes app.py at the root of a sandboxed Streamlit 1.31 runtime.
Deployment mechanics (create/start/share) are the managing-streamlit-apps skill; this one is about the code.
Reading PostHog data: posthog_apps.query()
The one and only data door is the in-sandbox bridge:
import posthog_apps
df = posthog_apps.query("SELECT event, count() FROM events GROUP BY event LIMIT 10")
- Takes a HogQL string, returns a pandas DataFrame.
- Raises
RuntimeErroron failure. The message is deliberately generic ("Query execution failed") — the bridge does not return query internals to the sandbox, so you cannot diagnose a bad query from inside the app. Catch it and render withst.error(str(e))so viewers get a message instead of a stack trace, and test queries in the SQL editor where real errors are visible. import posthogdoes NOT exist in the sandbox — the module isposthog_apps, deliberately distinct from the posthog-python SDK's name.- The bridge is pre-authenticated to the app's project; user code never sees a token, and there is nothing to configure.
- Queries run with server-side caps (30 s execution, 256 MB memory) that don't scale with sandbox sizing — so bound time ranges,
LIMITresults, and aggregate in HogQL rather than pulling raw events into pandas.
Design for Streamlit's rerun model
Streamlit reruns the whole script top to bottom on every widget interaction. Two consequences:
Cache every bridge call — uncached, one slider drag re-fires every query:
@st.cache_data(ttl=300, show_spinner="Running query...") def run_query(hogql: str) -> pd.DataFrame: return posthog_apps.query(hogql)Use
st.session_statefor anything that must survive reruns — accumulated selections, pagination cursors, "last refreshed" stamps. Module-level variables reset on every interaction.
Widgets drive parameters naturally, but never interpolate a free-text widget value into HogQL.
The bridge runs your query with the version author's data access, and anyone who can view the app drives those widgets — a raw st.text_input spliced into a query hands viewers the author's access to write their own.
Constrain the input instead: pick from a fixed list you control (st.selectbox over known values), or coerce to a type that can't carry SQL (int(days), a date from st.date_input), and validate before it reaches the query.
Layout and charts
st.set_page_config(page_title=..., layout="wide")first — the default narrow layout wastes most of the screen for data apps.- Structure with
st.columnsfor side-by-side metrics,st.tabsfor alternate views,st.expanderfor detail sections;st.metricfor headline numbers. - Charts:
st.plotly_chart(fig, use_container_width=True)with plotly express is the reliable default;st.dataframe(df, use_container_width=True)for tables. matplotlib/seaborn also work viast.pyplot.
What's installed
The image ships Python 3.11 with: streamlit 1.31, pandas, numpy, polars, plotly, matplotlib, seaborn, scipy, scikit-learn, pyarrow, duckdb, requests, beautifulsoup4, lxml, sqlalchemy, aiohttp.
There is no way to add dependencies: the sandbox never runs pip (a deliberate security posture — no arbitrary package code at boot), and a requirements.txt in an uploaded zip is tolerated but dropped. Only import what's listed above.
Structure and runtime constraints
app.pyis the entry point. Via the MCP set-source flow your source ISapp.py. Helper modules and data files can ship next to it through thefiles(text) andassets(base64) maps;import utilsworks because Streamlit puts the app directory onsys.path, but the process does not run inside that directory, so open data files viaPath(__file__).parent / "data/events.parquet", never a bare relative path. Keep bundled data small: it is sent inline as JSON on every set-source call.- The sandbox is ephemeral: anything written to disk disappears on stop/restart. Don't build state on files; recompute from queries (with caching) or hold it in
st.session_state. - Your code runs as an unprivileged user; there's no posthog SDK, no way to pass your own environment variables or secrets to the app, and no expectation of general network egress. Don't read from
os.environ— anything there belongs to the sandbox runtime, not your app. Design
Perguntas frequentes
Como o app lê os dados do PostHog?
Ele usa uma função de consulta embutida que devolve uma tabela, então o app nunca lida com dados de login.
Por que não consigo importar a biblioteca normal do PostHog?
O sandbox usa seu próprio módulo para acesso aos dados, então a biblioteca normal do PostHog não está disponível ali.
Há limites para as consultas?
Sim. As consultas têm limites de tempo e de memória, então a skill recomenda restringir os intervalos de tempo e limitar os resultados.
Detalhes
Descrição original do autor
Write Streamlit app source code that runs well in a PostHog sandbox — the posthog_apps.query() bridge for reading PostHog data, the packages baked into the sandbox image, caching and session state across Streamlit reruns, layout and chart patterns, and the app.py entry point with any helper modules and data files bundled beside it. Use when authoring or debugging the Python source of a PostHog Streamlit app, when a query inside an app fails, or when asked to "write a streamlit app that shows PostHog data".
repo: PostHog/posthog
Popularidade
- Estrelas no GitHub
- 41 mil
- Posição no ranking
- #6955
- Licença
- —
- Atualizada em
- 02/11/2026
Comentários
- …
Mais skills deste repositório
depot-ci
41 milAjuda seu agente a configurar e executar fluxos de trabalho do Depot CI, uma alternativa ao GitHub Actions, incluindo a migração de fluxos existentes e a leitura dos logs de execução.
depot-container-builds
41 milAjuda seu agente a criar imagens Docker nos builders remotos do Depot, incluindo imagens multiplataforma, envio para registros e correção de falhas de build.
depot-github-runners
41 milAjuda seu agente a levar tarefas do GitHub Actions para runners gerenciados pelo Depot, escolhendo os tamanhos e os rótulos dos runners e resolvendo problemas de configuração.
editing-agents-md
41 milAjuda seu agente a decidir se uma regra deve ficar em um arquivo AGENTS.md ou CLAUDE.md, e a escrevê-la de forma que seja seguida sem deixar o arquivo inchado.
Skills parecidas
angular-developer
280 milAjuda seu agente a criar código Angular e a dar conselhos sobre a estrutura do projeto. É útil para iniciar novos projetos, criar partes do código ou melhorar a performance e acessibilidade.
frontend-a11y
280 milAjuda seu agente a tornar interfaces web acessíveis para todos. Ele garante que sites e apps funcionem bem com leitores de tela e navegação por teclado.
frontend-patterns
280 milFaz seu agente aplicar padrões modernos no desenvolvimento frontend. Ele otimiza performance, gerencia estado e segue boas práticas em React e Next.js.