npm package: @julieshi/satoshi-ai-core
Description: Satoshi AI Core - Advanced AI engine for crypto and DeFi applications
Latest version: 1.0.2

# @goat/ai-core

> Shared AI logic for GOAT applications - Platform-agnostic, intelligent, and reusable.

## 🏗️ Architecture Overview

`@goat/ai-core` is a unified AI engine that provides intelligent RAG (Retrieval-Augmented Generation) capabilities for multiple applications. It automatically decides when to use knowledge retrieval based on query complexity.

## 📦 Installation

### From GitHub (Recommended)

```bash
npm install git+https://github.com/satoshi-inc/goat-ai-agent.git#dev-v2.0.5:packages/ai-core
```

### Local Development

```bash
npm install file:../path/to/goat-ai-agent/packages/ai-core
```

## 🚀 Quick Start

### Basic Usage

```typescript
import { createAIEngine } from "@goat/ai-core";

// Simple AI engine without RAG
const aiEngine = createAIEngine({
  model: "gpt-4o-mini",
  temperature: 0.7,
  maxTokens: 200,
  enableRAG: false,
});

const response = await aiEngine.generateText("Hello, how are you?");
```

### Intelligent RAG Engine

Our RAG engine is designed for ease of use. If you provide a Prisma-compatible `db` client, it automatically uses a default query function for vector search on the `t_knowledge` table.

**Easy Mode (with Prisma `db` client):**

```typescript
import { createRAGEngine } from "@julieshi/satoshi-ai-core";
import { db } from "./db"; // Your Prisma client instance

// Create intelligent RAG engine - it will use the default query function
const aiEngine = createRAGEngine("gpt-4o", db);

// It automatically uses RAG for complex queries
const response = await aiEngine.generateText(
  "Explain DeFi yield farming strategies",
  { originalQuery: "Explain DeFi yield farming strategies" }
);
```

**Custom Mode (with your own query function):**

```typescript
import { createRAGEngine } from "@julieshi/satoshi-ai-core";

// Your custom database query logic
const myCustomQuery = async (vector, limit) => {
  // ... your logic ...
};

// Create engine with a custom query function
const aiEngine = createRAGEngine("gpt-4o", null, myCustomQuery);
```

## 🎯 Usage Patterns

### 1. Web Chat Application (Full RAG)

```typescript
// For professional consultation with knowledge base
const aiEngine = createRAGEngine("gpt-4o", db, queryKnowledge);

const result = await aiEngine.generateStructuredResponse(prompt, {
  temperature: 0.7,
  maxTokens: 500,
  originalQuery: userInput, // Triggers intelligent RAG decision
});
```

### 2. Twitter Bot (Simple Responses)

```typescript
// For quick social media interactions
const aiEngine = createAIEngine({
  model: "gpt-4o",
  temperature: 0.8,
  maxTokens: 160,
  enableRAG: true,
});

const tweet = await aiEngine.generateText(twitterPrompt);
```

### 3. Content Rating (Predefined Criteria)

```typescript
// For joke/content scoring with built-in criteria
const aiEngine = createAIEngine({
  model: "gpt-4o-mini",
  temperature: 0.5,
  maxTokens: 150,
  enableRAG: false, // Uses predefined scoring rules
});

const rating = await aiEngine.generateStructuredResponse(ratingPrompt);
```

## 🧠 Intelligent RAG System

The RAG system automatically decides when to retrieve knowledge:

### ✅ RAG Triggered For:

- Complex queries (>10 characters)
- Technical questions
- Domain-specific topics
- Professional consultations

### ❌ RAG Skipped For:

- Simple greetings: "hi", "hello", "gm"
- Short queries
- General conversation
- Predefined tasks (ratings, etc.)

## ⚙️ Configuration Options

### AIEngineConfig

```typescript
interface AIEngineConfig {
  model: string; // 'gpt-4o' | 'gpt-4o-mini'
  temperature?: number; // 0.0 - 1.0 (default: 0.7)
  maxTokens?: number; // Max response length (default: 500)
  enableRAG?: boolean; // Enable/disable RAG (default: false)
}
```

### Factory Functions

| Function          | Use Case             | RAG    | Model  | Tokens |
| ----------------- | -------------------- | ------ | ------ | ------ |
| `createRAGEngine` | Professional queries | Auto   | gpt-4o | 500    |
| `createAIEngine`  | Custom configuration | Manual | Custom | Custom |

## 🔌 Integration Examples

### Twitter Bot Integration

```typescript
// twitter-goat/src/ai.ts
import { createAIEngine } from "@goat/ai-core";

export const createTwitterAI = () => {
  return createAIEngine({
    model: "gpt-4o-mini",
    temperature: 0.8,
    maxTokens: 100,
    enableRAG: false,
  });
};

// Usage
const ai = createTwitterAI();
const reply = await ai.generateText(buildTwitterPrompt(mention));
```

### Web Application Integration

```typescript
// web-app/src/ai.ts
import { createRAGEngine } from "@goat/ai-core";

const queryKnowledge = async (vector: number[], limit: number) => {
  return await prisma.$queryRaw`
    SELECT content FROM t_knowledge 
    ORDER BY embedding <=> ${vector}::vector 
    LIMIT ${limit}
  `;
};

export const createWebAI = () => {
  return createRAGEngine("gpt-4o", prisma, queryKnowledge);
};

// Usage
const ai = createWebAI();
const response = await ai.generateStructuredResponse(prompt, {
  originalQuery: userInput,
});
```

## 🛠️ Development

### Building

```bash
pnpm build
```

### Development Mode

```bash
pnpm dev
```

### Testing Integration

```bash
# In your project
npm update @goat/ai-core
```

## 📋 Requirements

### Peer Dependencies

- `@ai-sdk/openai`: >=0.0.60
- `@prisma/client`: latest (if using database features)
- `ai`: >=4.0.0

### Environment Variables

```env
OPENAI_API_KEY=your_openai_api_key
```

## 🔄 Version Management

The package follows semantic versioning. To update:

```bash
# Get latest version
npm update @goat/ai-core

# Install specific commit
npm install git+https://github.com/satoshi-inc/goat-ai-agent.git#commit-hash:packages/ai-core
```

## 🤝 Contributing

1. Make changes in `goat-ai-agent/packages/ai-core/`
2. Test with `pnpm build`
3. Commit and push to GitHub
4. Other projects can update with `npm update @goat/ai-core`

## 📚 API Reference

### Core Classes

#### `AIEngine`

- `generateText(prompt, options)` - Generate plain text
- `generateStructuredResponse(prompt, options)` - Generate JSON response
- `generateResponse(request)` - Generic response generation

### Utility Functions

#### `shouldUseRAG(query, enableRAG)`

- Intelligently decides if RAG is needed

#### `retrieveKnowledge(query, queryFunction, options)`

- Database-agnostic knowledge retrieval

#### `buildKnowledgeContext(chunks)`

- Formats knowledge chunks for prompts

## 🐛 Troubleshooting

### Common Issues

1. **Module not found**: Ensure correct GitHub URL and branch
2. **Peer dependency warnings**: Install required peer dependencies
3. **Build errors**: Check TypeScript configuration in consuming project

### Getting Help

- Check the main repository: [satoshi-inc/goat-ai-agent](https://github.com/satoshi-inc/goat-ai-agent)
- Review usage examples in `/apps/client/` and `/packages/api/`

---

**Repository**: [satoshi-inc/goat-ai-agent](https://github.com/satoshi-inc/goat-ai-agent)  
**Package Location**: `packages/ai-core/`  
**License**: MIT