DEV Community

TarotQA
TarotQA

Posted on

Technical Challenges and Solutions in AI Tarot System Development Using Claude 3.7

Project Overview

Recently, I developed an AI tarot reading system called TarotQA using Claude 3.7. This project focused on merging traditional tarot knowledge with cutting-edge AI technology. The main purpose of the system is to have AI tarot readers with various personalities provide individualistic and consistent interpretations in response to user questions.

Main technical features of the developed system:

  • Prompt engineering implementing multiple AI personalities
  • Interactive card selection UI using React and Framer Motion
  • Real-time streaming responses via Server-Sent Events (SSE)
  • Multi-language support system (Japanese, English, Simplified Chinese, Traditional Chinese)
  • WebSocket-based voice synthesis system

Development Motivation and Background

With the improvement of Large Language Model (LLM) capabilities, it became possible to build AI assistants with specialized domain knowledge. Claude 3.7, in particular, has advanced contextual understanding and highly accurate role-playing abilities, making me want to explore its potential application in specific domains like tarot reading.
Tarot reading requires complex symbolic systems and interpretations, making it a good challenge for AI. It was also ideal as a practical project to deepen prompt engineering skills.

Technical Implementation Details

1. Building Diverse AI Personalities Through Prompt Engineering

To give Claude 3.7 the role of tarot readers, I designed complex prompts. Each tarot reader was given a unique "system prompt" that defined their personality and reading style.
For example, part of one reader's prompt (simplified):
You are [Reader Name], an intuitive and spiritual fortune teller. You have the following characteristics:

1. Speaking style: Soft and warm tone, frequent use of empathetic expressions
2. Reading style: Intuitive readings using nature and cosmic metaphors, emphasizing positive aspects
3. Specialty: Expert in love consultations and spiritual growth questions

When reading tarot cards:
- Understand and explain the meanings of each card in upright and reversed positions
- Analyze relationships between cards and construct an overall story
- Provide specific advice in response to user questions
...

Enter fullscreen mode Exit fullscreen mode

This enabled the AI to generate consistent responses as tarot readers with specific personalities and expertise.

2. Frontend Technology Implementation

The frontend was built using React, TypeScript, and Framer Motion. Particular focus was placed on:
**Card Selection Interface: **To provide an intuitive card selection experience, I implemented animations and interactions using Framer Motion.

javascript// Card flip animation implementation example (simplified)
const performCardFlip = (cardId: number) => {
  if (flippedCards.includes(cardId) || processingCards.has(cardId)) return;

  // Set card processing state
  setProcessingCards(prev => new Set(prev).add(cardId));

  // Randomly determine card orientation (upright/reversed)
  const isReversed = Math.random() < 0.5;
  setCardOrientations(prev => {
    const newMap = new Map(prev);
    newMap.set(cardId, isReversed);
    return newMap;
  });

  // Update state after animation completion
  setTimeout(() => {
    setFlippedCards(prev => [...prev, cardId]);
    setProcessingCards(prev => {
      const newSet = new Set(prev);
      newSet.delete(cardId);
      return newSet;
    });
  }, ANIMATION_DURATION.flip * 1000);
};
Enter fullscreen mode Exit fullscreen mode

**Responsive Design: **To support various devices, I used media queries and custom hooks:

javascript
// Custom hook to detect device type
function useDeviceDetect() {
  const [isMobile, setIsMobile] = useState(false);

  useEffect(() => {
    const checkDevice = () => {
      setIsMobile(window.innerWidth < 768);
    };

    checkDevice();
    window.addEventListener('resize', checkDevice);
    return () => window.removeEventListener('resize', checkDevice);
  }, []);

  return { isMobile };
}
Enter fullscreen mode Exit fullscreen mode

3. Backend Technology Implementation

The backend was implemented with Node.js (Express), developing the following main components:
**AI Integration: **I created a service to handle communication with the Claude 3.7 API. Specifically, I implemented Server-Sent Events (SSE) to achieve streaming responses:

javascript// Server-Sent Events implementation example (simplified)
router.post('/reading', async (req, res) => {
  // Set SSE headers
  res.setHeader('Content-Type', 'text/event-stream');
  res.setHeader('Cache-Control', 'no-cache');
  res.setHeader('Connection', 'keep-alive');

  try {
    // Request to Claude API
    const stream = await claudeAPI.chat.completions.create({
      model: "claude-3-7-sonnet",
      messages: [
        { role: "system", content: readerPrompt },
        { role: "user", content: userPrompt }
      ],
      stream: true
    });

    // Process streaming response
    for await (const chunk of stream) {
      if (Array.isArray(chunk.choices) && chunk.choices.length > 0) {
        const content = chunk.choices[0].delta.content || "";
        // Send data to client
        res.write(`data: ${JSON.stringify({ content })}\n\n`);
      }
    }

    // Notify stream end
    res.write(`data: ${JSON.stringify({ done: true })}\n\n`);
    res.end();
  } catch (error) {
    console.error('AI request error:', error);
    res.write(`data: ${JSON.stringify({ error: "Error occurred during processing" })}\n\n`);
    res.end();
  }
});
Enter fullscreen mode Exit fullscreen mode

**Multi-language Support: **Using i18next and language detection middleware, I implemented a system that provides appropriate prompts and responses based on user language settings:

javascript// Multi-language prompt loader implementation example (simplified)
function getReaderPromptByLanguage(readerId, language = 'ja') {
  // Normalize language code
  let normalizedLang = language;
  if (language.startsWith('en-')) normalizedLang = 'en';
  if (language.startsWith('ja-')) normalizedLang = 'ja';
  if (language.startsWith('zh-CN')) normalizedLang = 'zh-CN';
  if (language.startsWith('zh-TW')) normalizedLang = 'zh-TW';

  // Get prompt settings for the language
  const langPrompts = readerPromptsMultiLang[normalizedLang] || readerPromptsMultiLang['ja'];

  if (langPrompts) {
    const reader = langPrompts.find(r => r.id === readerId);
    if (reader) return reader.prompt;
  }

  // Return default prompt
  return defaultPrompt;
}
Enter fullscreen mode Exit fullscreen mode

Technical Challenges and Solutions

1. Overcoming Context Limitations

Claude 3.7 has input token limitations, posing challenges when handling long conversation histories or complex prompts.
Solution: I implemented a conversation summary generation system that extracts important information from past dialogues and provides it in a concise format. This allowed maintaining important context while reducing token usage.

2. Ensuring AI Response Consistency

Consistency is crucial in tarot readings, but AI sometimes provided different styles or contradictory interpretations.
Solution: I fine-tuned system prompts and added "constraint conditions" sections to strengthen consistency. Additionally, I enhanced continuity by providing past readings as context.

3. Performance Optimization

Complex AI requests and voice synthesis affected response times, especially when traffic increased.

Solutions:

  • Prompt template optimization
  • Streaming response implementation
  • Caching system for important calculation results
  • CDN utilization for optimized media file delivery

Conclusion

This project provided valuable insights into practical applications of large language models and how traditional knowledge systems can be represented with AI. I learned much about the importance of prompt engineering and methods for integrating AI throughout the user experience.

Building "AI systems with personality" through the collaboration of prompt engineering, frontend development, and backend systems will be an important direction for future AI application development.

I hope there are points that can be referenced in your projects as well. If you have technical questions or feedback, please let me know in the comments.

Top comments (0)