Search

Results include substring matches and semantically similar vals. Learn more
nbbaier avatar
sqliteWriter
@nbbaier
SQLite QueryWriter The QueryWriter class is a utility for generating and executing SQL queries using natural language and OpenAI. It provides a simplified interface for interacting with your Val Town SQLite database and generating SQL queries based on user inputs. This val is inspired by prisma-gpt . PRs welcome! See Todos below for some ideas I have. Usage Import the QueryWriter class into your script: import { QueryWriter } from "https://esm.town/v/nbbaier/sqliteWriter"; Create an instance of QueryWriter, providing the desired table and an optional model: const writer = new QueryWriter({ table: "my_table", model: "gpt-4-1106-preview" }); Call the writeQuery() method to generate an SQL query based on a user input string: const userInput = "Show me all the customers with more than $1000 in purchases."; const query = await writer.writeQuery(userInput); Alternatively, use the gptQuery() method to both generate and execute the SQL query: const userInput = "Show me all the customers with more than $1000 in purchases."; const result = await writer.gptQuery(userInput); Handle the generated query or query result according to your application's needs. API new QueryWriter(args: { table: string; model?: string }): QueryWriter Creates a new instance of the QueryWriter class. table : The name of the database table to operate on. model (optional): The model to use for generating SQL queries. Defaults to "gpt-3.5-turbo". apiKey (optional): An OpenAI API key. Defaults to Deno.env.get("OPENAI_API_KEY") . writeQuery(str: string): Promise<string> Generates an SQL query based on the provided user input string. str : The user input string describing the desired query. Returns a Promise that resolves to the generated SQL query. gptQuery(str: string): Promise<any> Generates and executes an SQL query based on the provided user input string. str : The user input string describing the desired query. Returns a Promise that resolves to the result of executing the generated SQL query. Todos [ ] Handle multiple tables for more complex use cases [ ] Edit prompt to allow for more than just SELECT queries [ ] Allow a user to add to the system prompt maybe? [ ] Expand usage beyond just Turso SQLite to integrate with other databases
Script
The QueryWriter class is a utility for generating and executing SQL queries using natural language and OpenAI. It provides a
This val is inspired by [prisma-gpt](https://github.com/aliyeysides/prisma-gpt). PRs welcome! See **Todos** below for some id
## Usage
thatsmeadarsh avatar
star_a_github_repository_with_natural_language
@thatsmeadarsh
Using OpenAI Assistant API, Composio to Star a Github Repo This is an example code of using Composio to star a github Repository by creating an AI Agent using OpenAI API Goal Enable OpenAI assistants to perform tasks like starring a repository on GitHub via natural language commands. Tools List of supported tools . FAQs How to get Composio API key? Open app.composio.dev and log in to your account. Then go to app.composio.dev/settings . Navigate to the API Keys -> Generate a new API key .
Script
async function setupUserConnectionIfNotExists(entityId) {
const entity = toolset.client.getEntity(entityId);
const connection = await entity.getConnection(appName);
async function executeAgent(entityName) {
const entity = toolset.client.getEntity(entityName);
await setupUserConnectionIfNotExists(entity.id);
const instruction = "Star a repo ComposioHQ/composio on GitHub";
const client = new OpenAI();
const response = await client.chat.completions.create({
model: "gpt-4-turbo",
janpaul123 avatar
semanticSearchBlobs
@janpaul123
Part of Val Town Semantic Search . Uses Val Town's blob storage to search embeddings of all vals, by downloading them all and iterating through all of them to compute distance. Slow and terrible, but it works! Get metadata from blob storage: allValsBlob${dimensions}EmbeddingsMeta (currently allValsBlob1536EmbeddingsMeta ), which has a list of all indexed vals and where their embedding is stored ( batchDataIndex points to the blob, and valIndex represents the offset within the blob). The blobs have been generated by janpaul123/indexValsBlobs . It is not run automatically. Get all blobs with embeddings pointed to by the metadata, e.g. allValsBlob1536EmbeddingsData_0 for batchDataIndex 0. Call OpenAI to generate an embedding for the search query. Go through all embeddings and compute cosine similarity with the embedding for the search query. Return list sorted by similarity.
Script
import { decode as base64Decode, encode as base64Encode } from "https://deno.land/std@0.166.0/encoding/base64.ts";
import { createClient } from "https://esm.sh/@libsql/client@0.6.0/web";
import { sqlToJSON } from "https://esm.town/v/nbbaier/sqliteExportHelpers?v=22";
import { db as allValsDb } from "https://esm.town/v/sqlite/db?v=9";
willthereader avatar
ReadmeWriter
@willthereader
Val Town AI Readme Writer This val provides a class ReadmeWriter for generating readmes for vals with OpenAI. It can both draft readmes and update them directly PRs welcome! See Todos below for some ideas I have. Usage To draft a readme for a given code, use the draftReadme method: import { ReadmeWriter } from "https://esm.town/v/nbbaier/readmeGPT"; const readmeWriter = new ReadmeWriter({}); const val = "https://www.val.town/v/:username/:valname"; const generatedReadme = await readmeWriter.draftReadme(val); To write and update a readme for a given code, use the writeReadme method: import { ReadmeWriter } from "https://esm.town/v/nbbaier/readmeGPT"; const readmeWriter = new ReadmeWriter({}); const val = "https://www.val.town/v/:username/:valname"; const successMessage = await readmeWriter.writeReadme(val); API Reference Class: ReadmeWriter The ReadmeWriter class represents a utility for generating and updating README files. Constructor Creates an instance of the ReadmeWriter class. Parameters: model (optional): The model to be used for generating the readme. Defaults to "gpt-3.5-turbo". apiKey (optional): An OpenAI API key. Defaults to Deno.env.get("OPENAI_API_KEY") . Methods draftReadme(val: string): Promise<string> : Generates a readme for the given val. Parameters: val : URL of the code repository. Returns: A promise that resolves to the generated readme. writeReadme(val: string): Promise<string> : Generates and updates a readme for the given val. Parameters: val : URL of the code repository. Returns: A promise that resolves to a success message if the update is successful. Todos [ ] Additional options to pass to the OpenAI model [ ] Ability to pass more instructions to the prompt to modify how the readme is constructed
Script
import { type WriterOptions } from "https://esm.town/v/nbbaier/WriterOptions";
import { fetch } from "https://esm.town/v/std/fetch?v=4";
import OpenAI, { type ClientOptions } from "npm:openai";
export class ReadmeWriter {
model: string;
stevekrouse avatar
uploadTextToS3
@stevekrouse
Part of the Upload and download from AWS S3 guide .
Script
import { S3Client } from "https://deno.land/x/s3_lite_client@0.6.1/mod.ts"
const s3client = new S3Client({
endPoint: "s3.amazonaws.com",
secretKey: Deno.env.get("awsS3Secret"),
const upload = await s3client.putObject("filename.txt", "File contents");
console.log(upload)
karfau avatar
getRaw
@karfau
A helper to get the raw data of a val, using the very nice implementation from @pomdtr.raw . Usage: https://www.val.town/v/karfau.test_getRaw Also look at @karfau.rawUrl to just get the raw url of another val inside a val.
Script
Usage: https://www.val.town/v/karfau.test_getRaw
Also look at [@karfau.rawUrl](https://www.val.town/v/karfau.rawUrl) to just get the raw url of another val inside a val.
iamseeley avatar
convertToResumeJSON
@iamseeley
An interactive, runnable TypeScript val by iamseeley
Script
"work": [{
"name": "Company",
"position": "President",
"url": "https://company.com",
"startDate": "2013-01-01",
janpaul123 avatar
semanticSearchNeon
@janpaul123
Part of Val Town Semantic Search . Uses Neon to search embeddings of all vals, using the pg_vector extension. Call OpenAI to generate an embedding for the search query. Query the vals_embeddings table in Neon using the cosine similarity operator. The vals_embeddings table gets refreshed every 10 minutes by janpaul123/indexValsNeon .
Script
import { decode as base64Decode, encode as base64Encode } from "https://deno.land/std@0.166.0/encoding/base64.ts";
import { Client } from "https://deno.land/x/postgres/mod.ts";
import { db as allValsDb } from "https://esm.town/v/sqlite/db?v=9";
export default async function semanticSearchPublicVals(query) {
const client = new Client(Deno.env.get("NEON_URL_VALSEMBEDDINGS"));
await client.connect();
const openai = new OpenAI();
const embeddedBinaryString = `[${queryEmbedding.join(",")}]`;
const result = await client
.queryObject`SELECT id, embedding <=> ${embeddedBinaryString} AS distance FROM vals_embeddings ORDER BY embedding <=> ${e
postpostscript avatar
sqliteBuilderBeta
@postpostscript
sqliteBuilder: Opinionated safe(r) query builder using tagged templates import { Statement } from "https://esm.town/v/postpostscript/sqliteBuilder"; const unsafeId = "1234 or TRUE" console.log(Statement` SELECT * FROM table WHERE id = ${unsafeId} ${Statement`AND other_`} `) // StatementInstance { // sql: "\nSELECT *\nFROM table\nWHERE id = ?\nAND otherCondition\n", // args: [ "1234 or TRUE" ], // log: false // } const results = await Statement`SELECT ...`.execute() // [ { key: "value", anotherKey: "anotherValue" }, ... ] Or you can pass it directly to @std/sqlite.execute : import { sqlite } from "https://esm.town/v/std/sqlite" await sqlite.execute(Statement`Select ...`) You can combine multiple statements using Statement.prototype.combineWith : Statement`...`.combineWith(Statement`...`, " AND ") [ Statement`fieldA`, Statement`fieldB`, Statement`fieldC`, ].reduce((a, b) => a.combineWith(b, ", "))
Script
import { MaybePromise } from "https://esm.town/v/postpostscript/typeUtils";
import { type InStatement, type InValue, sqlite } from "https://esm.town/v/std/sqlite";
import { LibsqlError, type Row } from "npm:@libsql/client";
export { LibsqlError } from "npm:@libsql/client";
export type SqliteInterface = {
execute(statement: InStatement): MaybePromise<{
andrewgao avatar
imgGenUrl
@andrewgao
URL to AI Image Source code credit: @maxm on val.town
HTTP (deprecated)
import { generateImage } from "https://esm.town/v/isidentical/falImageGen?v=11";
import { blob } from "https://esm.town/v/std/blob?v=12";
const genKey = (key: string): string => {
saolsen avatar
sqlite
@saolsen
This is a wrapper of the val town std sqlite library that adds tracing via https://www.val.town/v/saolsen/tracing.
Script
import { SpanStatusCode } from "https://cdn.skypack.dev/@opentelemetry/api";
import { type ResultSet, type TransactionMode } from "npm:@libsql/client";
import { InStatement, sqlite as std_sqlite } from "https://esm.town/v/std/sqlite?v=4";
import { get_tracer } from "https://esm.town/v/saolsen/tracing?v=136";
liamdanielduffy avatar
REACT_DOM_MINIFIED_PT2
@liamdanielduffy
// set by liamdanielduffy.buildReactDomMinified at 2023-06-01T12:04:43.610Z
Script
// set by liamdanielduffy.buildReactDomMinified at 2023-06-01T12:04:43.610Z
export let REACT_DOM_MINIFIED_PT2 = "}else\"/$\"===c&&b++}a=a.previousSibling}return null}function pb(a){var b=a[Da];\nif(b)r
vince avatar
isAchatOrVente
@vince
An interactive, runnable TypeScript val by vince
Script
type Side = "credit" | "debit";
type Result = "achat" | "vente" | "unknown";
filename: string;
side: Side;
const filename = payload.filename;
const side = payload.side;
let result: Result;
if (side === "credit") {
if (/^FA\d+\.pdf$/.test(filename)) {
result = "achat";
else if (side === "debit") {
if (/^AV\d+\.pdf$/.test(filename)) {
nbbaier avatar
draftReadme
@nbbaier
Code Documentation Assistant The Code Documentation Assistant is an AI-powered tool that helps generate documentation for code. It uses the OpenAI GPT-3.5 Turbo model to generate readme files in GitHub-flavored markdown based on the provided code. Usage Importing the Code Documentation Assistant import { draftReadme, writeReadme } from "code-doc-assistant"; Function: draftReadme async function draftReadme(options: WriterOptions): Promise<string> The draftReadme function generates a readme file based on the provided options. Parameters options (required): An object containing the following properties: username (string): The username of the code owner. valName (string): The name of the Val containing the code. model (optional, default: "gpt-3.5-turbo"): The OpenAI model to use for generating the readme. userPrompt (optional): Additional prompt to include in the documentation. Return Value A promise that resolves to a string representing the generated readme file. Function: writeReadme async function writeReadme(options: WriterOptions): Promise<string> The writeReadme function generates a readme file and updates the readme of the corresponding Val with the generated content. Parameters options (required): An object containing the following properties: username (string): The username of the code owner. valName (string): The name of the Val containing the code. model (optional, default: "gpt-3.5-turbo"): The OpenAI model to use for generating the readme. userPrompt (optional): Additional prompt to include in the documentation. Return Value A promise that resolves to a string indicating the success of the readme update. Example import { draftReadme, writeReadme } from "code-doc-assistant"; const options = { username: "your-username", valName: "your-val-name", }; const generatedReadme = await draftReadme(options); console.log(generatedReadme); const successMessage = await writeReadme(options); console.log(successMessage); License This project is licensed under the MIT License .
Script
import { fetch } from "https://esm.town/v/std/fetch?v=4";
import OpenAI, { type ClientOptions } from "npm:openai";
export interface WriterOptions extends ClientOptions {
username: string;
throw new Error("Error getting val code: " + error.message);
async function performOpenAICall(prompt: string, model: string, openaiOptions: ClientOptions) {
const openai = new OpenAI(openaiOptions);
rlesser avatar
sqliteTableExportUtils
@rlesser
SQLite Table Export Utils This allows for a val.town-hosted SQLite table to be exported as: JSON ( Record<string, unknown>[] ) Arrow IPC ( Uint8Array ) TODO: Others? This can then be used by a HTTP endpoint, like so: import { exportSQLiteTable, SQLiteTableExportFormat } from "https://esm.town/v/rlesser/sqliteTableExportUtils"; export default async function(req: Request): Promise<Response> { const tableName = new URL(req.url).searchParams.get("table"); if (!tableName) { return new Response("Table name is required", { status: 400 }); } const format = (new URL(req.url).searchParams.get("format") || "arrowIPC") as SQLiteTableExportFormat; const data = await exportSQLiteTable(tableName, format); if (data instanceof Uint8Array) { return new Response(data, { headers: { "Content-Type": "application/octet-stream" }, }); } else { return Response.json(data); } } TODO Specify limit and offset of export, for pagination Smart assessment of if the export is going to be over the val.town limit of 10MB, adjust to paginated of so. Support other export formats. PRs welcome!
Script
import { sqlite } from "https://esm.town/v/std/sqlite";
import { type ResultSet } from "npm:@libsql/client";
import { DataType, Float64, Int32, Table, tableToIPC, Utf8, vectorFromArray } from "npm:apache-arrow";
import { zip } from "npm:lodash-es@4.17.21";