Trending Vals
2
3
stevekrouse
cerebrasTemplate
HTTP
Cerebras Inference template This val shows you how you can deploy an app using Cerebras Inference on Val Town
in seconds. What is Cerebras? Cerebras is an American chip manufacturer that
produces large wafer chips that deliver mind-blowing LLM inference speeds.
As of this writing on Jan 17, 2025, Cerebras Inference
provides Llama 3.18b, 3.1 70b, and 3.370b at a jaw-dropping 2k tokens per second β
that's 50x faster than what the frontier labs produce. Llama 3.370b at 2k tokens
per second is particularly noteworthy because it is
a GPT-4-class model . This level
of intelligence at that level of speed will unlock whole new classes of applications. Quick start Set up Cerebras Sign up for Cerebras Get a Cerebras API Key Save it in a Val Town environment variable called CEREBRAS_API_KEY Once Cerebras is set up in your Val Town account, there are two ways to get started: Fork this app and customize it (or ask Townie AI to customize it) Start a new chat with Townie AI and copy & paste
the following instructions: . Use Cerebras for AI on the backend like so:
const { OpenAI } = await import("https://esm.sh/openai");
const client = new OpenAI({
apiKey: Deno.env.get("CEREBRAS_API_KEY"),
baseURL: "https://api.cerebras.ai/v1"
});
const response = await client.chat.completions.create({
model: "llama-3.3-70b",
messages: [],
});
const generatedText = response.choices[0].message.content; For example, the val in this template was created by asking
Townie AI to "Make a chatgpt clone",
then I hit shift-enter twice, and then pasted in the instructions on
how to use Cerebras from above, then hit enter. Townie built this app on its first try, in about 20 seconds. Sample apps Cerebras Searcher - a Perplexity clone that uses the SerpAPI to do RAG
and summaries with Cerebras ( requires a SerpAPI key ) Cerebras Coder - an app that
generates websites in a second with Cerebras Cerebras Debater - an
app that truly shows Cerebras's speed: it's Cerebras talking to Cerebras in a debate
0
4
5
stevekrouse
discordWebhook
Script
Send a Discord message Send a message to a Discord channel from Val Town. It's useful for notifying your team or community when someone interesting happens, like a user signup, Stripe payment, mention on social media, etc. import { discordWebhook } from "https://esm.town/v/stevekrouse/discordWebhook";
await discordWebhook({
url: Deno.env.get("engDiscord"),
content: "Hi from val town!",
});
Example val: https://www.val.town/v/stevekrouse.discordWebhookEx Setup 1. Create a Discord Webhook Follow the instructions here: https://support.discord.com/hc/en-us/articles/228383668-Intro-to-Webhooks It really only takes 2 minutes. 2. Copy webhook URL Paste it into your secrets as discordWebhook . 3. Send a message! import { discordWebhook } from "https://esm.town/v/stevekrouse/discordWebhook";
await discordWebhook({
url: Deno.env.get("engDiscord"),
content: "Hi from val town!",
}); Example val: https://www.val.town/v/stevekrouse.discordWebhookEx
1
8
stevekrouse
steel_puppeteer_starter
Script
Steel + Puppeteer Starter This template shows you how to use Steel with Puppeteer
to run browser automations in the cloud on Val Town.
It includes session management, error handling,
and a basic example you can customize. This starter
templated was ported from
this one on Github . Quick start The script shows you how to: Create and manage a Steel browser session Connect Puppeteer to the session Navigate to a website (Hacker News in this example) Extract data from the page (top 5 stories) Handle errors and cleanup properly View your live session in Steel's session viewer To run it: Get your free Steel API key at https://app.steel.dev/settings/api-keys Add it to your Val Town Environment Variables as STEEL_API_KEY Click Fork on this val Click Run on this val Writing your automation Find this section in the script: // ============================================================
// Your Automations Go Here!
// ============================================================
// Example automation (you can delete this)
await page.goto('https://news.ycombinator.com');
// ... rest of example code You can replace the code here with whatever automation scripts you want to run. Configuration The template includes common Steel configurations you can enable: const session = await client.sessions.create({
useProxy: true, // Use Steel's proxy network
solveCaptcha: true, // Enable CAPTCHA solving
sessionTimeout: 1800000, // 30 minute timeout (default: 15 mins)
userAgent: 'custom-ua', // Custom User-Agent
}); Error handling The template includes error handling and cleanup: try {
// Your automation code
} finally {
// Cleanup runs even if there's an error
if (browser) await browser.close();
if (session) await client.sessions.release(session.id);
} Support Steel Documentation API Reference Discord Community
2
9
nbbaier
sqliteExplorerApp
HTTP
SQLite Explorer View and interact with your Val Town SQLite data. It's based off Steve's excellent SQLite Admin val, adding the ability to run SQLite queries directly in the interface. This new version has a revised UI and that's heavily inspired by LibSQL Studio by invisal . This is now more an SPA, with tables, queries and results showing up on the same page. Install Install the latest stable version (v86) by forking this val: Authentication Login to your SQLite Explorer with password authentication with your Val Town API Token as the password. Todos / Plans [ ] improve error handling [ ] improve table formatting [ ] sticky table headers [x] add codemirror [ ] add loading indication to the run button (initial version shipped) [ ] add ability to favorite queries [ ] add saving of last query run for a table (started) [ ] add visible output for non-query statements [ ] add schema viewing [ ] add refresh to table list sidebar after CREATE/DROP/ALTER statements [ ] add automatic execution of initial select query on double click [x] add views to the sidebar [ ] add triggers to sidebar [ ] add upload from SQL, CSV and JSON [ ] add ability to connect to a non-val town Turso database [x] fix wonky sidebar separator height problem (thanks to @stevekrouse) [x] make result tables scrollable [x] add export to CSV, and JSON (CSV and JSON helper functions written in this val . Thanks to @pomdtr for merging the initial version!) [x] add listener for cmd+enter to submit query
21
10
12
13
stevekrouse
aqi
Cron
AQI Alerts Get email alerts when AQI is unhealthy near you. Set up Click Fork Change location (Line 4) to describe your location. It accepts fairly flexible English descriptions which it turns into locations via nominatim's geocoder API . Click Run Background This val uses nominatim's geocoder to get your lat, lon, and air quality data from OpenAQ. It uses EPA's NowCast
AQI Index calculation and severity levels. Learn more: https://www.val.town/v/stevekrouse.easyAQI
6
14
15
stevekrouse
twitterAlert
Cron
Twitter/π keyword alerts Custom notifications for when you, your company, or anything you care about is mentioned on Twitter. If you believe in Twitter/π-driven development, you want to get notified
when anyone is talking about your tech, even if they're not tagging you. To get this Twitter Alert bot running for you,
fork this val and modify the query and where the notification gets delivered. 1. Query Change the keywords for what you want to get notified for
and the excludes for what you don't want to get notified for. You can use Twitter's search operators to customize your query, for some collection of keywords, filtering out others, and much more! 2. Notification Below I'm sending these mentions to a public channel in our company Discord, but you can customize that to whatever you want, @std/email, Slack, Telegram, whatever. Twitter Data & Limitations The Twitter API has become unusable. This val gets Twitter data via SocialData ,
an affordable Twitter scraping API. In order to make this val easy for
you to fork & use without signing up for another API, I am proxying
SocialData via @stevekrouse/socialDataProxy. Val Town Pro users can call this proxy
100 times per day, so be sure not to set this cron to run more than once every 15 min. If you want to run it more, get your own SocialData
API token and pay for it directly.
4
16
17
steveruizok
tldraw_computer_example
HTTP
tldraw computer custom endpoint example This val is an example custom endpoint for tldraw computer 's data component. Usage To use this val with tldraw.computer, follow these steps: Fork this Val. Click the Copy endpoint button on your new Val. Open a project on tldraw.computer Create a Data component in your tldraw computer project In the Source dropdown, select Custom and the POST method Paste the endpoint into Data component's the HTTP Endpoint input. Run the component. To see the output, connect the Data component to a Text component. How it works In tldraw computer, you can configure a Data component to use a custom HTTP endpoint as its data source. You can also configure the request method, either GET or POST. If a Data component's request method is POST, then when the component next updates, it will send a POST request to the endpoint. The request's body will contain an array of the Data objects that the component had received as inputs. If the request method if GET, then the component will only make the requestβits body will be empty. In both cases, the component will expect back a response that includes an array of Data objects these objects will be passed along as the data component's outputs. The endpoint (your forked version of this Val) can do whatever it likes between the request and response, but the response must include data in the correct format. If the format is wrong, the computer app will create a text data object instead that includes the response as plain text. Support If you're running into any difficulties, check out the #tldraw-computer channel on the tldraw discord.
3
20
yawnxyz
ai
HTTP
An http and class wrapper for Vercel's AI SDK Usage: Groq: https://yawnxyz-ai.web.val.run/generate?prompt="tell me a beer joke"&provider=groq&model=llama3-8b-8192 Perplexity: https://yawnxyz-ai.web.val.run/generate?prompt="what's the latest phage directory capsid & tail article about?"&provider=perplexity Mistral: https://yawnxyz-ai.web.val.run/generate?prompt="tell me a joke?"&provider=mistral&model="mistral-small-latest" async function calculateEmbeddings(text) {
const url = `https://yawnxyz-ai.web.val.run/generate?embed=true&value=${encodeURIComponent(text)}`;
try {
const response = await fetch(url);
const data = await response.json();
return data;
} catch (error) {
console.error('Error calculating embeddings:', error);
return null;
}
}
1
21
stevekrouse
newStripeSubscriber
HTTP
New Stripe Subscription Handler This val processes new Stripe subscribers to Val Town Pro. It sends our team
a Discord notifcation and sends a welcome email to the new subscriber. It takes a couple of
steps if you'd like to set up something similar for your own Stripe account. Setup Fork this HTTP val Create a new webhook in Stripe Add your val's HTTP endpoint URL into the Stripe webhook Select customer.subscription.updated as the only event to listen to (more on this below) Add your stripe_sk_customer_readonly to your Val Town Env Variables Add your webhook's signing secret as STRIPE_WEBHOOK_SECRET to you Val Town Env Variables How the code is structured Verifies the signature to make sure it's really from Stripe Filters out only newly created subscriptions Sends off the Discord message & email Which Stripe event type to listen to Stripe sends webhooks for many different kinds of events. Relevant for us here are: customer.subscription.created (what we used to listen for) customer.subscription.updated (what we're currently listening for) The issue with customer.subscription.created is that it triggers too early,
before the user's payment actually goes through. This is a problem
because in early Nov 2024 we started getting credit card fraudsters
testing cards using our service. We started getting lots of notifications
for new subscriptions that never actually became active. Note: if anyone knows good ways to prevent that sort of behavior at
the root, please let me know by commenting on this val! In order to only get notified on a valid subscription, we now subscribe
to customer.subscription.updated . This event happens on any subscription change,
including renewals and cancellations, so now we have to filter those events
to only get new subscriptions, ie where: event.data.previous_attributes.status === 'incomplete' && event.data.object.status === 'active'
2
22
rozek
resettableQuotaTracker
Script
Public vals often use resources which have some usage limits ("quota"). Publishing such vals carries the risk that these quotas may be exceeded. For this reason, it makes sense to keep track
of resource consumption and trigger a relevant response when a preset limit is reached (for example, one could provide the user with a meaningful error message). The "resettableQuotaTracker" is designed to help monitor resources that are replenished at a specific time (e.g., at a certain time each day or at the beginning of a month). Usage Example Using a resettableQuotaTracker (within the val that requires the resource) is quite simple: import { resettableQuotaTracker } from 'https://esm.town/v/rozek/resettableQuotaTracker'
const ResourceTable = 'xxx' // enter name of sqlite table that can be used
const ResourceLimit = 10 // max. number of allowed requests before reset
;(async () => {
const Tracker = await resettableQuotaTracker.new(ResourceTable,ResourceLimit)
let exceeded = await Tracker.LimitExceeded() // true if quota exceeded
// can be used to chech the current status
await Tracker.incrementIfAllowed() // increments resource usage if allowed
// or throws a "LimitExceeded" exception otherwise
... now use your resource as usual
})() Simply enter the name of an sqlite table in ResourceTable where the resource consumption should be logged, and specify in ResourceLimit how many calls are allowed before the resource needs to be replenished. The "resettableQuotaTracker" is designed to be accessed simultaneously from multiple vals without interfering with each other. Resetting the consumption must be handled, for example, by a separate CRON job. import { resettableQuotaTracker } from 'https://esm.town/v/rozek/resettableQuotaTracker'
const ResourceTable = '' // enter name of sqlite table that can be used
;(async () => {
const Tracker = await resettableQuotaTracker.new(ResourceTable)
await Tracker.reset()
})() API Reference static async new (TableName:string, Limit?:number):resettableQuotaTracker creates a new resettableQuotaTracker instance for the table TableName . If this table does not exist yet, it will be created automatically, with Limit set as the quota (default for Limit is 10). async isReady ():Promise<boolean> returns a Promise that resolves to true as soon as the resettableQuotaTracker is available (this is unfortunately necessary because the constructor contains asynchronous code). async reset ():Promise<void> can be used to reset the resource consumption back to 0. async Usage ():Promise<number> returns the number of counted calls so far. async Limit ():Promise<number> returns the currently configured limit. async setLimit (newLimit:number):Promise<void> can be used to configure a new limit. async LimitExceeded ():Promise<boolean> returns true if the configured limit has been reached or exceeded, or false if further calls are still allowed. async increment ():Promise<void> increases the consumption counter by 1 (even if the configured limit has already been reached). async incrementIfAllowed ():Promise<void> increases the consumption counter by 1 only if the configured limit has not yet been reached. Important: the check and the incrementing of the counter occur in the same transaction , allowing multiple resettableQuotaTracker instances to access the same table simultaneously. Tests Some tests can be found at val resettableQuotaTracker_Test
1
24
stevekrouse
easyAQI
Script
easyAQI Get the Air Quality Index (AQI) for a location via open data sources. It's "easy" because it strings together multiple lower-level APIs to give you a simple interface for AQI. Accepts a location in basically any string format (ie "downtown manhattan") Uses Nominatim to turn that into longitude and latitude Finds the closest sensor to you on OpenAQ Pulls the readings from OpenAQ Calculates the AQI via EPA's NowCAST algorithm Uses EPA's ranking to classify the severity of the score (ie "Unhealthy for Sensitive Groups") It uses blob storage to cache the openai location id for your location string to skip a couple steps for the next time. Example usage @stevekrouse.easyAQI({ location: "brooklyn navy yard" })
// Returns { "aqi": 23.6, "severity": "Good" } Forkable example: val.town/v/stevekrouse.easyAQIExample Also useful for getting alerts when the AQI is unhealthy near you: https://www.val.town/v/stevekrouse.aqi
3
25
stevekrouse
umbrellaReminder
Cron
βοΈ Umbrella reminder if there's rain today Setup Fork this val π https://val.town/v/stevekrouse.umbrellaReminder/fork Customize the location (line 8). You can supply any free-form description of a location. β οΈ Only works for US-based locations (where weather.gov covers). How it works Geocodes an free-form description of a location to latitude and longitude β @stevekrouse.nominatimSearch Converts a latitude and longitude to weather.gov grid β @stevekrouse.weatherGovGrid Gets the hourly forecast for that grid Filters the forecast for periods that are today and >30% chance of rain If there are any, it formats them appropriately, and sends me an email
9
29
pomdtr
password_auth
Script
Password Auth Middleware Protect your vals behind a password. Use session cookies to persist authentication. Usage import { passwordAuth } from "https://esm.town/v/pomdtr/password_auth?v=84";
export default passwordAuth(() => {
return new Response("OK");
}, { verifyPassword: (password) => password == Deno.env.get("VAL_PASSWORD") }); If you want to use an api token to authenticate: import { passwordAuth } from "https://esm.town/v/pomdtr/password_auth?v=84";
import { verifyToken } from "https://esm.town/v/pomdtr/verifyToken";
export default passwordAuth(() => {
return new Response("OK");
}, { verifyPassword: verifyToken }); TODO [x] allow to authenticate using a val town token [ ] add a way to send an email to ask a password from the val owner [ ] automatically extend the session [ ] automatically remove expired sessions FAQ How to sign out ? Navigate to <your-site>/signout .
15
30