Val Town Code SearchReturn to Val Town

API Access

You can access search results via JSON API by adding format=json to your query:

https://codesearch.val.run/$2?q=api&page=22&format=json

For typeahead suggestions, use the /typeahead endpoint:

https://codesearch.val.run/typeahead?q=api

Returns an array of strings in format "username" or "username/projectName"

Found 18008 results for "api"(2990ms)

ChatSettings.tsx7 matches

@AIWBUpdated 1 day ago
18
19export default function Settings({ config, onUpdateConfig, onClose }: SettingsProps) {
20 const [apiKey, setApiKey] = useState(config.anthropicApiKey);
21 const [mcpServers, setMcpServers] = useState<MCPServer[]>(config.mcpServers);
22 const [selectedModel, setSelectedModel] = useState(config.selectedModel);
37 const handleSave = () => {
38 onUpdateConfig({
39 anthropicApiKey: apiKey,
40 mcpServers: mcpServers,
41 selectedModel: selectedModel,
141 </div>
142
143 {/* API Key Section */}
144 <div className="form-group">
145 <label className="form-label">Anthropic API Key</label>
146 <input
147 type="password"
148 value={apiKey}
149 onChange={(e) => setApiKey(e.target.value)}
150 placeholder="sk-ant-..."
151 className="form-input"
152 />
153 <div className="text-sm text-gray-600 mt-1">
154 Get your API key from{" "}
155 <a
156 href="https://console.anthropic.com/"

ChatREADME.md7 matches

@AIWBUpdated 1 day ago
1# Anthropic Streaming Chat with MCP
2
3A mobile-optimized single page chat application that uses the Anthropic Messages API with **real-time streaming** and MCP (Model Context Protocol) server support.
4
5Source: https://www.val.town/x/c15r/Chat
16- **⏹️ Stream control** - Stop streaming at any time with the stop button
17- Full-screen mobile-optimized chat interface
18- Direct client-side Anthropic API integration with server-side streaming proxy
19- **Model selection** - Choose between different Claude models (3.5 Sonnet, 3.5 Haiku, 3 Opus, etc.) without clearing chat history
20- Configurable MCP servers with localStorage persistence
64
65The app stores configuration and chat history in localStorage:
66- `anthropic_api_key`: Your Anthropic API key
67- `selected_model`: The chosen Claude model (defaults to claude-3-5-sonnet-20241022)
68- `mcp_servers`: Array of configured MCP servers
69- `chat_messages`: Complete chat history (persists between page loads)
70
71## API Endpoints
72
73- `GET /` - Main application (serves frontend)
80
811. Open the app at the provided URL
822. Click "Settings" in the footer to configure your Anthropic API key and select your preferred Claude model
833. Add/remove/toggle MCP servers as needed
844. Use the "Test" button next to each MCP server to verify connectivity (shows ✅ for success, ❌ for errors)
107- **Auto-scroll**: Messages automatically scroll to bottom during streaming
108- **Auto-resize**: Input field grows with content
109- **Error Handling**: Clear error messages for API issues with stream recovery
110- **Loading States**: Visual feedback during API calls and streaming
111- **Structured Responses**: MCP tool use and results are displayed in organized, collapsible sections
112- **Clean Interface**: Maximized chat area with no header, footer contains all controls

ChatApp.tsx8 matches

@AIWBUpdated 1 day ago
20
21export interface AppConfig {
22 anthropicApiKey: string;
23 mcpServers: MCPServer[];
24 selectedModel: string;
37export default function App() {
38 const [config, setConfig] = useState<AppConfig>({
39 anthropicApiKey: "",
40 mcpServers: DEFAULT_MCP_SERVERS,
41 selectedModel: "claude-3-5-sonnet-20241022",
46 // Load config from localStorage on mount
47 useEffect(() => {
48 const savedApiKey = localStorage.getItem("anthropic_api_key");
49 const savedMcpServers = localStorage.getItem("mcp_servers");
50 const savedMessages = localStorage.getItem("chat_messages");
52
53 setConfig({
54 anthropicApiKey: savedApiKey || "",
55 mcpServers: savedMcpServers ? JSON.parse(savedMcpServers) : DEFAULT_MCP_SERVERS,
56 selectedModel: savedModel || "claude-3-5-sonnet-20241022",
67 }
68
69 // Show settings if no API key is configured
70 if (!savedApiKey) {
71 setShowSettings(true);
72 }
75 // Save config to localStorage when it changes
76 useEffect(() => {
77 if (config.anthropicApiKey) {
78 localStorage.setItem("anthropic_api_key", config.anthropicApiKey);
79 }
80 localStorage.setItem("mcp_servers", JSON.stringify(config.mcpServers));

crm_OBUO_FARMSproducts.ts36 matches

@eddie_walkUpdated 1 day ago
6import type {
7 CreateProductRequest, UpdateProductRequest, StockAdjustmentRequest,
8 ApiResponse, Product, StockMovement
9} from "../../shared/types.ts";
10
15 try {
16 const allProducts = await getAllProducts();
17 return c.json<ApiResponse<Product[]>>({
18 success: true,
19 data: allProducts
21 } catch (error) {
22 console.error('Error fetching products:', error);
23 return c.json<ApiResponse<null>>({
24 success: false,
25 error: "Failed to fetch products"
32 try {
33 const lowStockProducts = await getLowStockProducts();
34 return c.json<ApiResponse<Product[]>>({
35 success: true,
36 data: lowStockProducts
38 } catch (error) {
39 console.error('Error fetching low stock products:', error);
40 return c.json<ApiResponse<null>>({
41 success: false,
42 error: "Failed to fetch low stock products"
50 const id = parseInt(c.req.param('id'));
51 if (isNaN(id)) {
52 return c.json<ApiResponse<null>>({
53 success: false,
54 error: "Invalid product ID"
58 const product = await getProductById(id);
59 if (!product) {
60 return c.json<ApiResponse<null>>({
61 success: false,
62 error: "Product not found"
64 }
65
66 return c.json<ApiResponse<Product>>({
67 success: true,
68 data: product
70 } catch (error) {
71 console.error('Error fetching product:', error);
72 return c.json<ApiResponse<null>>({
73 success: false,
74 error: "Failed to fetch product"
86 for (const field of requiredFields) {
87 if (productData[field as keyof CreateProductRequest] === undefined) {
88 return c.json<ApiResponse<null>>({
89 success: false,
90 error: `Missing required field: ${field}`
94
95 // Validate fish type
96 if (!['Catfish', 'Tilapia'].includes(productData.fishType)) {
97 return c.json<ApiResponse<null>>({
98 success: false,
99 error: "Invalid fish type. Must be 'Catfish' or 'Tilapia'"
100 }, 400);
101 }
103 // Validate product form
104 if (!['Fresh', 'Frozen', 'Live', 'Fillet', 'Smoked', 'Dried'].includes(productData.productForm)) {
105 return c.json<ApiResponse<null>>({
106 success: false,
107 error: "Invalid product form"
111 // Validate unit
112 if (!['kg', 'pieces'].includes(productData.unit)) {
113 return c.json<ApiResponse<null>>({
114 success: false,
115 error: "Invalid unit. Must be 'kg' or 'pieces'"
119 // Validate stock levels
120 if (productData.currentStock < 0 || productData.minStockLevel < 0 || productData.maxStockLevel < 0) {
121 return c.json<ApiResponse<null>>({
122 success: false,
123 error: "Stock levels cannot be negative"
126
127 if (productData.minStockLevel >= productData.maxStockLevel) {
128 return c.json<ApiResponse<null>>({
129 success: false,
130 error: "Minimum stock level must be less than maximum stock level"
134 const newProduct = await createProduct(productData);
135
136 return c.json<ApiResponse<Product>>({
137 success: true,
138 data: newProduct
141 } catch (error) {
142 console.error('Error creating product:', error);
143 return c.json<ApiResponse<null>>({
144 success: false,
145 error: error instanceof Error ? error.message : "Failed to create product"
153 const id = parseInt(c.req.param('id'));
154 if (isNaN(id)) {
155 return c.json<ApiResponse<null>>({
156 success: false,
157 error: "Invalid product ID"
163
164 if (!updatedProduct) {
165 return c.json<ApiResponse<null>>({
166 success: false,
167 error: "Product not found"
169 }
170
171 return c.json<ApiResponse<Product>>({
172 success: true,
173 data: updatedProduct
175 } catch (error) {
176 console.error('Error updating product:', error);
177 return c.json<ApiResponse<null>>({
178 success: false,
179 error: "Failed to update product"
187 const id = parseInt(c.req.param('id'));
188 if (isNaN(id)) {
189 return c.json<ApiResponse<null>>({
190 success: false,
191 error: "Invalid product ID"
197 // Validate required fields
198 if (!adjustmentData.quantity || !adjustmentData.reason || !adjustmentData.movementType) {
199 return c.json<ApiResponse<null>>({
200 success: false,
201 error: "Missing required fields: quantity, reason, movementType"
205 // Validate movement type
206 if (!['IN', 'OUT', 'ADJUSTMENT'].includes(adjustmentData.movementType)) {
207 return c.json<ApiResponse<null>>({
208 success: false,
209 error: "Invalid movement type. Must be 'IN', 'OUT', or 'ADJUSTMENT'"
213 // Validate quantity
214 if (adjustmentData.quantity <= 0) {
215 return c.json<ApiResponse<null>>({
216 success: false,
217 error: "Quantity must be greater than 0"
227 const updatedProduct = await adjustStock(fullAdjustmentData);
228
229 return c.json<ApiResponse<Product>>({
230 success: true,
231 data: updatedProduct
233 } catch (error) {
234 console.error('Error adjusting stock:', error);
235 return c.json<ApiResponse<null>>({
236 success: false,
237 error: error instanceof Error ? error.message : "Failed to adjust stock"
245 const id = parseInt(c.req.param('id'));
246 if (isNaN(id)) {
247 return c.json<ApiResponse<null>>({
248 success: false,
249 error: "Invalid product ID"
254 const movements = await getStockMovements(id, limit);
255
256 return c.json<ApiResponse<StockMovement[]>>({
257 success: true,
258 data: movements
260 } catch (error) {
261 console.error('Error fetching stock movements:', error);
262 return c.json<ApiResponse<null>>({
263 success: false,
264 error: "Failed to fetch stock movements"
273 const movements = await getStockMovements(undefined, limit);
274
275 return c.json<ApiResponse<StockMovement[]>>({
276 success: true,
277 data: movements
279 } catch (error) {
280 console.error('Error fetching all stock movements:', error);
281 return c.json<ApiResponse<null>>({
282 success: false,
283 error: "Failed to fetch stock movements"
295 await resetAllStockToZero();
296
297 return c.json<ApiResponse<{ message: string }>>({
298 success: true,
299 data: { message: "All product stock has been reset to zero" }
301 } catch (error) {
302 console.error('Error resetting stock:', error);
303 return c.json<ApiResponse<null>>({
304 success: false,
305 error: "Failed to reset stock"

stevensDemosendDailyBrief.ts8 matches

@sysbotUpdated 1 day ago
97
98export async function sendDailyBriefing(chatId?: string, today?: DateTime) {
99 // Get API keys from environment
100 const apiKey = Deno.env.get("ANTHROPIC_API_KEY");
101 const telegramToken = Deno.env.get("TELEGRAM_TOKEN");
102
106 }
107
108 if (!apiKey) {
109 console.error("Anthropic API key is not configured.");
110 return;
111 }
122
123 // Initialize Anthropic client
124 const anthropic = new Anthropic({ apiKey });
125
126 // Initialize Telegram bot
162
163 // disabled title for now, it seemes unnecessary...
164 // await bot.api.sendMessage(chatId, `*${title}*`, { parse_mode: "Markdown" });
165
166 // Then send the main content
169
170 if (content.length <= MAX_LENGTH) {
171 await bot.api.sendMessage(chatId, content, { parse_mode: "Markdown" });
172 // Store the briefing in chat history
173 await storeChatMessage(
198 // Send each chunk as a separate message and store in chat history
199 for (const chunk of chunks) {
200 await bot.api.sendMessage(chatId, chunk, { parse_mode: "Markdown" });
201 // Store each chunk in chat history
202 await storeChatMessage(

stevensDemoREADME.md1 match

@sysbotUpdated 1 day ago
53You'll need to set up some environment variables to make it run.
54
55- `ANTHROPIC_API_KEY` for LLM calls
56- You'll need to follow [these instructions](https://docs.val.town/integrations/telegram/) to make a telegram bot, and set `TELEGRAM_TOKEN`. You'll also need to get a `TELEGRAM_CHAT_ID` in order to have the bot remember chat contents.
57- For the Google Calendar integration you'll need `GOOGLE_CALENDAR_ACCOUNT_ID` and `GOOGLE_CALENDAR_CALENDAR_ID`. See [these instuctions](https://www.val.town/v/stevekrouse/pipedream) for details.

stevensDemoREADME.md5 matches

@sysbotUpdated 1 day ago
8## Hono
9
10This app uses [Hono](https://hono.dev/) as the API framework. You can think of Hono as a replacement for [ExpressJS](https://expressjs.com/) that works in serverless environments like Val Town or Cloudflare Workers. If you come from Python or Ruby, Hono is also a lot like [Flask](https://github.com/pallets/flask) or [Sinatra](https://github.com/sinatra/sinatra), respectively.
11
12## Serving assets to the frontend
20### `index.html`
21
22The most complicated part of this backend API is serving index.html. In this app (like most apps) we serve it at the root, ie `GET /`.
23
24We *bootstrap* `index.html` with some initial data from the server, so that it gets dynamically injected JSON data without having to make another round-trip request to the server to get that data on the frontend. This is a common pattern for client-side rendered apps.
25
26## CRUD API Routes
27
28This app has two CRUD API routes: for reading and inserting into the messages table. They both speak JSON, which is standard. They import their functions from `/backend/database/queries.ts`. These routes are called from the React app to refresh and update data.
29
30## Errors
31
32Hono and other API frameworks have a habit of swallowing up Errors. We turn off this default behavior by re-throwing errors, because we think most of the time you'll want to see the full stack trace instead of merely "Internal Server Error". You can customize how you want errors to appear.

stevensDemoNotebookView.tsx5 matches

@sysbotUpdated 1 day ago
8import { type Memory } from "../../shared/types.ts";
9
10const API_BASE = "/api/memories";
11const MEMORIES_PER_PAGE = 20;
12
71 setError(null);
72 try {
73 const response = await fetch(API_BASE);
74 if (!response.ok) {
75 throw new Error(`HTTP error! status: ${response.status}`);
100
101 try {
102 const response = await fetch(API_BASE, {
103 method: "POST",
104 headers: { "Content-Type": "application/json" },
123
124 try {
125 const response = await fetch(`${API_BASE}/${id}`, {
126 method: "DELETE",
127 });
155
156 try {
157 const response = await fetch(`${API_BASE}/${editingMemory.id}`, {
158 method: "PUT",
159 headers: { "Content-Type": "application/json" },

stevensDemoindex.ts11 matches

@sysbotUpdated 1 day ago
18});
19
20// --- API Routes for Memories ---
21
22// GET /api/memories - Retrieve all memories
23app.get("/api/memories", async (c) => {
24 const memories = await getAllMemories();
25 return c.json(memories);
26});
27
28// POST /api/memories - Create a new memory
29app.post("/api/memories", async (c) => {
30 const body = await c.req.json<Omit<Memory, "id">>();
31 if (!body.text) {
36});
37
38// PUT /api/memories/:id - Update an existing memory
39app.put("/api/memories/:id", async (c) => {
40 const id = c.req.param("id");
41 const body = await c.req.json<Partial<Omit<Memory, "id">>>();
58});
59
60// DELETE /api/memories/:id - Delete a memory
61app.delete("/api/memories/:id", async (c) => {
62 const id = c.req.param("id");
63 try {
75// --- Blob Image Serving Routes ---
76
77// GET /api/images/:filename - Serve images from blob storage
78app.get("/api/images/:filename", async (c) => {
79 const filename = c.req.param("filename");
80

stevensDemoindex.html2 matches

@sysbotUpdated 1 day ago
12 type="image/svg+xml"
13 />
14 <link rel="preconnect" href="https://fonts.googleapis.com" />
15 <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
16 <link
17 href="https://fonts.googleapis.com/css2?family=Pixelify+Sans:wght@400..700&display=swap"
18 rel="stylesheet"
19 />

Apiify7 file matches

@wolfUpdated 49 mins ago

dailyQuoteAPI

@SoukyUpdated 2 days ago
Kapil01
apiv1