Skip to content

Instantly share code, notes, and snippets.

@WomB0ComB0
Last active April 30, 2025 00:53
Show Gist options
  • Save WomB0ComB0/05b95fedb23647ba3e690414222d81f7 to your computer and use it in GitHub Desktop.
Save WomB0ComB0/05b95fedb23647ba3e690414222d81f7 to your computer and use it in GitHub Desktop.
tech-week.ts and related files - with AI-generated descriptions
"use strict";
import { readableStreamToJSON, file } from 'bun';
import { z } from 'zod';
import { generateText } from 'ai';
import { openai } from '@ai-sdk/openai';
import { GoogleMapsService } from './map.js';
import dotenv from 'dotenv';
dotenv.config({ path: '.env' });
const TechWeekEventSchema = z.object({
id: z.string(),
event_name: z.string(),
start_time: z.string(),
city: z.string(),
neighborhood: z.string().nullable(),
invite_url: z.string(),
hosts: z.array(z.string()),
target_audiences: z.array(z.string()),
themes: z.array(z.string()),
formats: z.array(z.string()),
is_featured: z.boolean(),
starred_on_calendar: z.string().nullable(),
day: z.string(),
time: z.string(),
});
type TechWeekEvent = z.infer<typeof TechWeekEventSchema>;
function eventsOverlap(event1: TechWeekEvent, event2: TechWeekEvent): boolean {
const event1Start = new Date(event1.start_time);
const event2Start = new Date(event2.start_time);
const estimatedDuration = 2 * 60 * 60 * 1000; // 2 hours in milliseconds
const event1End = new Date(event1Start.getTime() + estimatedDuration);
const event2End = new Date(event2Start.getTime() + estimatedDuration);
return event1Start < event2End && event1End > event2Start;
}
function findNonOverlappingEvents(events: TechWeekEvent[]): TechWeekEvent[] {
const sortedEvents = [...events].sort((a, b) =>
new Date(a.start_time).getTime() - new Date(b.start_time).getTime()
);
const selectedEvents: TechWeekEvent[] = [];
for (const event of sortedEvents) {
if (selectedEvents.length === 0 ||
!eventsOverlap(selectedEvents[selectedEvents.length - 1], event)) {
selectedEvents.push(event);
}
}
return selectedEvents;
}
(async () => {
try {
const apiKey = process.env.GOOGLE_MAPS_API_KEY || '';
const mapsService = new GoogleMapsService(apiKey);
let jsonData;
try {
const stream = file('tech-week.json').stream();
jsonData = await readableStreamToJSON(stream);
} catch (error) {
console.error('Error reading JSON file:', error);
return;
}
const parseResult = z.array(TechWeekEventSchema).safeParse(jsonData);
if (parseResult.success) {
const allEvents = parseResult.data;
let events = allEvents.filter(event => {
if (event.invite_url === "Invite Only") return false;
if (!event.neighborhood) return false;
return true;
});
events = events.slice(0, 100);
console.log(`Filtered to ${events.length} events`);
const nonOverlappingEvents = findNonOverlappingEvents(events);
console.log(`Selected ${nonOverlappingEvents.length} non-overlapping events`);
let routeInfo = '';
if (nonOverlappingEvents.length > 1 && apiKey) {
routeInfo = await calculateRoutes(nonOverlappingEvents, mapsService);
}
const formattedEvents = nonOverlappingEvents.map(event => ({
name: event.event_name,
time_location: `${event.day} | ${event.time} | ${event.city}${event.neighborhood ? ` (${event.neighborhood})` : ''}`,
details: `Hosts: ${event.hosts.join(', ')} | Themes: ${event.themes.join(', ')}`,
url: event.invite_url
}));
const prompt = `Based on my resume and this optimized, non-overlapping list of tech events, suggest which events I should attend.
${JSON.stringify(formattedEvents, null, 2)}
${routeInfo}
Please format your response as a markdown table with columns for Event Name, Time/Location, Details, and Registration Link.`;
const { text } = await generateText({
model: openai('gpt-4o'),
system: 'You are a helpful assistant who can analyze events and match them to a person\'s resume and skills.',
prompt: prompt,
maxTokens: 3000,
});
await Bun.write('./response.md', text);
await Bun.spawn({ cmd: ['/bin/sh', '-c', `xdg-open ./response.md`] });
{
for (const event of nonOverlappingEvents) setTimeout(async () => {
await Bun.spawn({ cmd: ['/bin/sh', '-c', `xdg-open ${event.invite_url}`] });
}, 1000);
}
} else {
console.error('Failed to parse events:', parseResult.error);
}
} catch (error) {
console.error('An unexpected error occurred:', error);
}
})();
async function calculateRoutes(events: TechWeekEvent[], mapsService: GoogleMapsService): Promise<string> {
try {
const eventLocations = events.map(event => `${event.city}${event.neighborhood ? `, ${event.neighborhood}` : ''}`);
let routeInfo = "## Optimal Route Information\n\n";
for (let i = 0; i < events.length - 1; i++) {
const origin = eventLocations[i];
const destination = eventLocations[i + 1];
try {
const result = await mapsService.getDirections(origin, destination);
if (result && result.routes && result.routes.length > 0) {
const route = result.routes[0];
const leg = route.legs[0];
routeInfo += `- From "${events[i].event_name}" to "${events[i+1].event_name}":\n`;
routeInfo += ` - Distance: ${leg.distance?.text}\n`;
routeInfo += ` - Duration: ${leg.duration?.text}\n`;
routeInfo += ` - Route: ${route.summary}\n\n`;
}
} catch (error) {
console.error(`Failed to get directions from ${origin} to ${destination}:`, error);
}
}
return routeInfo;
} catch (error) {
console.error('Error calculating routes:', error);
return "Could not calculate routes between events.";
}
}

tech-week.ts Description

File Type: ts

Generated Description:

tech-week.ts Analysis

This TypeScript file (tech-week.ts) processes a JSON file containing information about tech events, filters and selects a subset of non-overlapping events, generates an optimal route (if applicable), and uses a large language model (LLM) to suggest which events to attend based on the filtered data. The final output is a markdown file containing the LLM's recommendations.

1. Summary

The script reads a JSON file (tech-week.json) containing tech event details, validates the data using Zod, filters the events based on criteria (e.g., excluding "Invite Only" events and those without a neighborhood), selects non-overlapping events using a custom algorithm, and then calculates an optimal route between those events using the Google Maps API. Finally, it presents this information to an LLM (likely OpenAI's GPT-4) to receive personalized recommendations and writes the LLM's response to a markdown file (response.md). The script then opens this markdown file using the system's default application.

2. Key Components/Functions

  • eventsOverlap(event1, event2): This function determines if two events overlap based on their start times and an estimated duration (2 hours). It uses Date objects for time comparisons.

  • findNonOverlappingEvents(events): This function takes an array of events and returns a new array containing only the non-overlapping events, sorted chronologically. It utilizes the eventsOverlap function.

  • calculateRoutes(events, mapsService): This function (incomplete in the provided snippet) uses the Google Maps service to calculate the optimal route between the selected non-overlapping events. It constructs route information in markdown format for inclusion in the LLM prompt.

  • Zod Schema Validation (TechWeekEventSchema): A Zod schema is used to validate the structure and data types of each event object within the JSON file, ensuring data integrity.

  • LLM Interaction (generateText): The script leverages an LLM (OpenAI's GPT-4) to provide personalized event recommendations based on the filtered and routed events. The prompt includes the filtered events and route information.

  • Google Maps API Integration: The script integrates with the Google Maps API to calculate routes between event locations. This requires a Google Maps API key.

3. Notable Patterns/Techniques

  • Data Validation: Uses Zod for robust data validation, ensuring data integrity and preventing runtime errors.
  • Functional Programming: The script employs functional programming principles, using functions like eventsOverlap and findNonOverlappingEvents to improve code organization and readability.
  • Asynchronous Operations: Leverages async/await for handling asynchronous operations, such as file reading, API calls, and LLM interaction.
  • Error Handling: Uses try...catch blocks to handle potential errors during file reading, data parsing, API calls, and LLM interactions.
  • Environmental Variables: Uses dotenv to load environment variables from a .env file, making it easy to manage sensitive information like API keys.
  • LLM-based Decision Making: The script intelligently uses an LLM to provide personalized recommendations, rather than relying solely on algorithmic filtering.

4. Potential Use Cases

  • Personalized Tech Event Recommendation: The primary use case is to recommend relevant and non-overlapping tech events to individuals based on their location and preferences.
  • Event Planning Tool: Could be extended to plan other types of events, requiring changes to the event schema and filtering criteria.
  • Route Optimization: The route optimization aspect could be used in other applications requiring efficient route planning.
  • Intelligent Event Aggregation: The script demonstrates the power of combining structured data processing, API integration, and LLMs to create intelligent and personalized applications.

The script's structure and functionality are well-designed and demonstrate best practices in modern JavaScript development. The use of an LLM adds a significant layer of sophistication by providing context-aware recommendations beyond simple algorithmic filtering.

Description generated on 4/29/2025, 4:54:28 PM

@WomB0ComB0
Copy link
Author

@WomB0ComB0
Copy link
Author

To provide you with the best recommendations, I would need to know more about your skills, interests, and goals as outlined in your resume. However, I can suggest a few events based on common tech interests such as AI, B2C, SaaS, and Fundraising/Investing. Here's a markdown table with some events that might be of interest:

| Event Name                                      | Time/Location                                | Details                                                                 | Registration Link                                                   |
|-------------------------------------------------|----------------------------------------------|-------------------------------------------------------------------------|---------------------------------------------------------------------|
| The World's First VIBEATHON                     | Monday | 9:00 AM | New York City (Chelsea)            | Themes: AI, B2C / Consumer, SaaS                                      | [Link](https://partiful.com/e/dFWMaelGpf0HW7SUwq6J)                 |
| AI Real-Time Data Monitoring in HealthTech      | Monday | 1:30 PM | New York City (Financial District) | Themes: Deep tech, Defense, Engineering                               | [Link](https://partiful.com/e/4dCiGBLO6NVuwMoSFR6Q)                 |
| AI Unleashed: AWS & Lux's NY Tech Week Kickoff! | Monday | 4:00 PM | New York City (Midtown)            | Themes: AI, Deep Tech, GTM                                            | [Link](http://partiful.com/e/3Ew1BfzhVVt4xzgOssfk?)                 |
| TechWeek Opening After Party at GOSPËL          | Monday | 8:30 PM | New York City (SoHo)               | Themes: AI, Fundraising / Investing                                   | [Link](https://partiful.com/e/fR6UyIvV5GSxYiYJDwe9)                 |
| AI in Marketing: Strategic Prompt Workshop      | Tuesday | 3:30 PM | New York City (Financial District) | Themes: AI, GTM (marketing sales growth), Women-focused               | [Link](https://partiful.com/e/TCojygfnjpM1B5gf6Xsc)                 |
| The New Consumer Startup Stack                  | Tuesday | 6:00 PM | New York City (Midtown)            | Themes: B2C / Consumer, AI, GTM (marketing sales growth)              | [Link](https://partiful.com/e/uTA1dfYrnC3p4urETx0V)                 |
| Modern Data & ML Infra Meetup                   | Wednesday | 8:30 AM | New York City (Flatiron)           | Themes: AI, B2B, SaaS                                                 | [Link](https://partiful.com/e/dT2cCBevNeYSa4FZqoZx)                 |
| Anote / Mindstone AI Meetup                     | Wednesday | 6:00 PM | New York City (Midtown)            | Themes: AI                                                            | [Link](https://partiful.com/e/Zh8NuBWFrQ6eMoKD80Gs)                 |
| Generative AI Summit                            | Thursday | 9:00 AM | New York City (SoHo)               | Themes: AI, Deep Tech, Engineering                                    | [Link](https://partiful.com/e/UaCTrRQASHwd5EYcQ3D3?)                |
| AWS X Lyzr Agentic AI Developer Meetup and Tech Chat | Thursday | 12:00 PM | New York City (Hudson Yards)      | Themes: AI                                                            | [Link](https://partiful.com/e/mc3r2mSCQgDEAFwoOeLd)                 |
| Atlassian: Unleash Every Startup                | Thursday | 4:30 PM | New York City (Union Square)       | Themes: SaaS, B2B                                                     | [Link](https://partiful.com/e/T2bKKysrPhXA5ZqLkdID)                 |
| Pitch Day Google for startups                   | Friday | 12:45 PM | New York City (Financial District) | Themes: AI, Hardware, Deep tech                                       | [Link](https://partiful.com/e/gCChhcmhMahhKdT8KIVY)                 |
| Closing Party                                   | Friday | 9:00 PM | New York City (SoHo)               | Themes: AI, Fundraising / Investing, SaaS                             | [Link](https://partiful.com/e/P2ItZdgU4yznbi6Wdk39)                 |

Please let me know if you have specific areas of interest or skills, and I can tailor the recommendations further!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment