-
Notifications
You must be signed in to change notification settings - Fork 170
Add Cascade Prediction Feature #6
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
rahulvalyu
wants to merge
19
commits into
unicodeveloper:main
Choose a base branch
from
rahulvalyu:main
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
19 commits
Select commit
Hold shift + click to select a range
9829c94
Merge pull request #1 from yorkeccak/main
unicodeveloper 9d500fe
Add OAuth proxy support and usage limits for valyu mode
yorkeccak f3cea5f
Merge pull request #2 from yorkeccak/main
unicodeveloper 75ea44e
feat
yorkeccak 48df2d0
Merge pull request #3 from yorkeccak/main
yorkeccak bb18ab5
feat
yorkeccak efcd03e
feat
yorkeccak 8480708
feat
yorkeccak c922078
feat
yorkeccak 95ddf7f
feat
yorkeccak 1a0eecf
Merge pull request #4 from yorkeccak/main
yorkeccak 431efac
Add cascade prediction state management store
rahulvalyu 8f22d0a
Add cascade analysis API endpoint with Valyu integration
rahulvalyu 4a60175
Add cascade panel UI components
rahulvalyu c0068db
Add cascade analysis button to event popup
rahulvalyu a4e5991
Add cascade visualization layers to threat map
rahulvalyu 2153649
Add cascade tab to sidebar navigation
rahulvalyu 83f5ad1
Update package-lock.json
rahulvalyu ae385d5
Refactor cascade API to use Valyu structured outputs
rahulvalyu File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,175 @@ | ||
| import { NextRequest, NextResponse } from "next/server"; | ||
| import { Valyu } from "valyu-js"; | ||
|
|
||
| const valyuClient = new Valyu(process.env.VALYU_API_KEY || ""); | ||
|
|
||
| // JSON Schema for structured cascade output | ||
| const cascadeSchema = { | ||
| type: "object", | ||
| properties: { | ||
| effects: { | ||
| type: "array", | ||
| description: "List of countries that may be affected by the cascade effects of this event", | ||
| items: { | ||
| type: "object", | ||
| properties: { | ||
| country: { | ||
| type: "string", | ||
| description: "Full name of the affected country", | ||
| }, | ||
| countryCode: { | ||
| type: "string", | ||
| description: "ISO 3166-1 alpha-2 country code (e.g., US, GB, DE)", | ||
| }, | ||
| latitude: { | ||
| type: "number", | ||
| description: "Latitude coordinate of the country's geographic center", | ||
| }, | ||
| longitude: { | ||
| type: "number", | ||
| description: "Longitude coordinate of the country's geographic center", | ||
| }, | ||
| probability: { | ||
| type: "number", | ||
| description: "Probability of being affected (0-100)", | ||
| }, | ||
| timeframeHours: { | ||
| type: "number", | ||
| description: "Expected timeframe for impact in hours", | ||
| }, | ||
| impactType: { | ||
| type: "string", | ||
| enum: ["economic", "military", "political", "humanitarian", "social"], | ||
| description: "Primary type of impact expected", | ||
| }, | ||
| description: { | ||
| type: "string", | ||
| description: "Brief explanation of why and how this country would be affected", | ||
| }, | ||
| factors: { | ||
| type: "array", | ||
| items: { type: "string" }, | ||
| description: "Key factors contributing to the cascade effect (e.g., 'Neighboring country', 'Major trade partner', 'Military alliance')", | ||
| }, | ||
| }, | ||
| required: ["country", "countryCode", "latitude", "longitude", "probability", "timeframeHours", "impactType", "description", "factors"], | ||
| }, | ||
| }, | ||
| summary: { | ||
| type: "string", | ||
| description: "A 2-3 sentence summary of the overall cascade analysis", | ||
| }, | ||
| }, | ||
| required: ["effects", "summary"], | ||
| }; | ||
|
|
||
| export async function POST(request: NextRequest) { | ||
| try { | ||
| const { event } = await request.json(); | ||
|
|
||
| if (!event) { | ||
| return NextResponse.json({ error: "Event data required" }, { status: 400 }); | ||
| } | ||
|
|
||
| const eventCountry = event.location?.country || "Unknown"; | ||
| const eventCategory = event.category || "conflict"; | ||
|
|
||
| // Use Valyu to analyze potential cascade effects with structured output | ||
| const analysisQuery = `Analyze the potential geopolitical and economic ripple effects of this event: | ||
|
|
||
| Event Title: "${event.title}" | ||
| Location: ${eventCountry} | ||
| Category: ${eventCategory} | ||
| Summary: ${event.summary || "No summary available"} | ||
|
|
||
| Identify 8-12 countries most likely to be affected by cascade effects from this event. For each country, analyze: | ||
|
|
||
| 1. The probability of being affected (0-100%) based on: | ||
| - Geographic proximity (neighboring countries) | ||
| - Economic ties (trade partners, supply chains) | ||
| - Political/military alliances | ||
| - Historical relationships and tensions | ||
| - Regional stability implications | ||
|
|
||
| 2. The expected timeframe for when effects would manifest (in hours) | ||
|
|
||
| 3. The primary type of impact (economic, military, political, humanitarian, or social) | ||
|
|
||
| 4. A clear explanation of why this country would be affected | ||
|
|
||
| 5. The key factors driving the cascade effect | ||
|
|
||
| Provide accurate geographic coordinates (latitude/longitude) for each country's center point. | ||
| Sort the results by probability of impact (highest first).`; | ||
|
|
||
| const response = await valyuClient.answer(analysisQuery, { | ||
| structuredOutput: cascadeSchema, | ||
| searchType: "news", | ||
| excludedSources: ["wikipedia.org"], | ||
| }); | ||
|
|
||
| console.log("Valyu response:", JSON.stringify(response, null, 2)); | ||
|
|
||
| // Extract the structured response - contents may be string or object | ||
| let analysisData: { | ||
| effects: Array<{ | ||
| country: string; | ||
| countryCode: string; | ||
| latitude: number; | ||
| longitude: number; | ||
| probability: number; | ||
| timeframeHours: number; | ||
| impactType: "economic" | "military" | "political" | "humanitarian" | "social"; | ||
| description: string; | ||
| factors: string[]; | ||
| }>; | ||
| summary: string; | ||
| }; | ||
|
|
||
| if (typeof response.contents === "string") { | ||
| // Try to parse if it's a JSON string | ||
| try { | ||
| analysisData = JSON.parse(response.contents); | ||
| } catch { | ||
| throw new Error("Failed to parse structured response: " + response.contents?.substring(0, 200)); | ||
| } | ||
| } else if (response.contents && typeof response.contents === "object") { | ||
| analysisData = response.contents as typeof analysisData; | ||
| } else { | ||
| throw new Error("No contents in response: " + JSON.stringify(response).substring(0, 500)); | ||
| } | ||
|
|
||
| // Transform effects to include id and delay for animation | ||
| const effects = analysisData.effects.map((effect, index) => ({ | ||
| id: `cascade-${Date.now()}-${index}`, | ||
| targetCountry: effect.country, | ||
| targetCountryCode: effect.countryCode, | ||
| latitude: effect.latitude, | ||
| longitude: effect.longitude, | ||
| probability: effect.probability, | ||
| timeframeHours: effect.timeframeHours, | ||
| impactType: effect.impactType, | ||
| description: effect.description, | ||
| factors: effect.factors, | ||
| delay: index * 150, // Stagger animation | ||
| })); | ||
|
|
||
| const highRiskCount = effects.filter((e) => e.probability >= 60).length; | ||
|
|
||
| return NextResponse.json({ | ||
| sourceEvent: event, | ||
| effects, | ||
| summary: analysisData.summary, | ||
| totalAffectedCountries: effects.length, | ||
| highRiskCount, | ||
| generatedAt: new Date().toISOString(), | ||
| }); | ||
| } catch (error) { | ||
| console.error("Cascade analysis error:", error); | ||
| const errorMessage = error instanceof Error ? error.message : "Unknown error"; | ||
| return NextResponse.json( | ||
| { error: "Failed to analyze cascade effects", details: errorMessage }, | ||
| { status: 500 } | ||
| ); | ||
| } | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Probably switch these around and log the errorMessage instead? I guess a mixture of both is fine.