iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
👻

Exploring a D&D-Style Alignment Chart for X Users

に公開

Tried out the D&D-style Alignment Chart for X Users

Introduction

I analyzed the D&D-style personality diagnostic chart currently trending on X (formerly Twitter) because it was quite interesting.

↓ You can try it here.
magic-x-alignment-chart.vercel.app

Alignment chart image

What is D&D?

It refers to Dungeons & Dragons (D&D), the progenitor of tabletop RPGs. D&D has a system called personality (alignment) that is defined during character creation.

Photo of my personal copy that I still own
D&D book photo

Alignment table

It is a system that represents a character's ethics and behavioral tendencies on two axes: "Lawful-Chaotic" and "Good-Evil."

This web app applies the concept of this alignment chart to X (formerly Twitter) users, automatically positioning them using AI-based analysis.

Development Background

This project was inspired by an idea posted by @mdmathewdc.

https://x.com/mdmathewdc/status/1899767815344722325

Subsequently, @rauchg implemented the drag-and-drop functionality,

https://x.com/rauchg/status/1899895262023467035

and @f1shy-dev reportedly advanced it by adding AI analysis features.

https://x.com/vishyfishy2/status/1899929030620598508

Based on these implementations, UI improvements, mobile support, and performance optimizations were carried out to create an app that is user-friendly for more people. It is a very interesting project that demonstrates how an idea evolves into an actual product through the power of the open-source community.

App Features

  1. Automatic Analysis by AI

    • Analyzes user tweets using Exa and OpenAI GPT-4
    • Evaluates user tendencies on two axes: Lawful - Chaotic and Good - Evil
    • Automatically positions users on the grid based on analysis results
  2. Interactive Usability

    • Intuitive position adjustment via drag-and-drop
    • AI analysis results include a lock feature
    • Manual adjustment is also possible with a random placement feature
  3. Tech Stack

    • Next.js (App Router)
    • TypeScript
    • Framer Motion (Animations)
    • Vercel AI SDK
    • IndexedDB (Local storage)
    • Upstash Redis (Cache)

Technical Implementation Points

1. Responsive Design

useEffect(() => {
  const checkMobile = () => {
    setIsMobile(window.innerWidth < 768);
  };
  
  checkMobile();
  window.addEventListener("resize", checkMobile);
  return () => window.removeEventListener("resize", checkMobile);
}, []);

The app implements dynamic layout adjustments based on screen size to achieve an optimal user experience across various devices, from mobile to desktop. In particular, making it compatible with both touch and mouse operations seems to have been a difficult challenge, but a smooth user experience has been achieved by leveraging the features of Framer Motion.

2. Alignment Analysis by AI

export async function analyzeAlignment(username: string) {
  try {
    const tweets = await fetchUserTweets(username);
    
    // Analyze using Exa
    const analysis = await exaClient.run(
      `Determine the D&D alignment (Lawful-Chaotic, Good-Evil) for the user ${username} based on their tweet content.
       Please refer to the following tweets:
       ${tweets.join("\n")}`
    );
    
    return {
      lawChaos: analysis.lawChaosScore, // -5 (Chaotic) to +5 (Lawful)
      goodEvil: analysis.goodEvilScore,  // -5 (Evil) to +5 (Good)
      confidence: analysis.confidence,
      explanation: analysis.reasoning
    };
  } catch (error) {
    console.error("Alignment analysis error:", error);
    throw new Error("An error occurred during user analysis");
  }
}

In this app, the context understanding capability of Exa is utilized to analyze the user's personality and behavioral tendencies from their tweet history, calculating the optimal position on the alignment chart. It seems to enable comprehensive analysis including context and emotion, not just word frequency.

Prompt

// Construct messages to pass to GPT-4
const messages = [
  {
    role: "system",
    content: dedent`
    Analyze the given Twitter user's tweets and determine their position on a D&D-style alignment chart.
    
    Law-Chaos axis:
    - Lawful (-100): Follows rules, tradition, and social norms. Values tradition, loyalty, and order.
    - Neutral (0): A balanced approach to rules and freedom.
    - Chaotic (100): Rebels against convention and values individual freedom. Follows their own beliefs regardless of rules or traditions.
    
    Good-Evil axis:
    - Good (-100): Altruistic, compassionate, and prioritizes others.
    - Neutral (0): Balance between self-interest and consideration for others.
    - Evil (100): Selfish, manipulative, and harms others. Motivated by greed, anger, or desire for power.
    
    Evaluate the user's alignment numerically based ONLY on these tweets. Don't be afraid to lean towards extremes!

    This is for fun, so if you see even a slight hint of a trait, feel free to exaggerate it. For example, if there's an element of evil, emphasize it! We don't want everyone to be "Chaotic Neutral." However, you don't necessarily have to exaggerate chaotic traits; you can also exaggerate more prominent Lawful or Good/Evil traits. Have fun with the analysis.
    
    Keep the explanation from being too wordy while showing the reasoning for your judgment. Mention specific user traits, posts, or projects to make the analysis more personalized.
  `.trim()
  },
  {
    role: "user",
    content:
      dedent`Username: @${username}

<user_profile>
${profile_str}
</user_profile>

<user_tweets filter="top_100">
${tweetTexts}
</user_tweets>`.trim()
  }
] satisfies CoreMessage[]

3. Data Persistence and Caching Strategy

// Data persistence using IndexedDB
const saveToLocalDB = async (placement: StoredPlacement) => {
  if (!db) return;
  try {
    const tx = db.transaction("placements", "readwrite");
    const store = tx.objectStore("placements");
    await store.put({
      ...placement,
      timestamp: new Date()
    });
    await tx.done;
  } catch (error) {
    console.error("Save error:", error);
  }
};

// Caching API responses using Upstash Redis
export async function cachedFetchTweets(username: string) {
  const cacheKey = `tweets:${username}`;
  
  // Check cache
  const cached = await redis.get(cacheKey);
  if (cached) return JSON.parse(cached as string);
  
  // Fetch from API
  const tweets = await fetchFromTwitterAPI(username);
  
  // Save to cache (valid for 24 hours)
  await redis.set(cacheKey, JSON.stringify(tweets), { ex: 86400 });
  
  return tweets;
}

To improve the user experience, efforts have been made to optimize performance by persisting placement information within the browser using IndexedDB and caching API call results using Upstash Redis to reduce redundant API requests. This also seems to address the limitations of the Twitter API.

Potential Implementation Difficulties and Solutions

1. Handling Twitter API Limits

The limitations of the Twitter (now X) API are strict, and frequently sending requests can easily trigger rate limits. To address this issue, the following measures seem to have been taken:

  • Aggressive caching strategy using Upstash Redis
  • Backoff and retry logic
  • User-friendly alternative flows when errors occur

These measures ensure that the app can be used comfortably even within the constraints of the API.

2. Optimizing Mobile UX

const TouchControls = ({ onReset, onRandom }) => {
  return isMobile ? (
    <div className="fixed bottom-4 left-0 right-0 flex justify-center gap-3 z-10">
      <Button variant="outline" onClick={onReset}>
        <RefreshCw size={16} className="mr-2" />Reset
      </Button>
      <Button variant="outline" onClick={onRandom}>
        <Shuffle size={16} className="mr-2" />Random Placement
      </Button>
    </div>
  ) : null;
};

There appeared to be an issue where drag operations and scroll operations conflicted on touch devices. To solve this:

  • Propagation control of touch events
  • Addition of a dedicated control UI for mobile
  • Optimization of element sizes

By implementing these measures, a UI that works comfortably on both mobile and desktop has been achieved.

Conclusion

In this project, a new way to visually represent X users' personalities is proposed by combining modern web technologies with AI. While there were several technical challenges, they were overcome to create an interesting and practical web app.

GitHubで編集を提案

Discussion