{"_id":"@ai-standards/ai","name":"@ai-standards/ai","dist-tags":{"latest":"0.9.0"},"versions":{"0.9.0":{"name":"@ai-standards/ai","version":"0.9.0","description":"AI engine and models for native AI","main":"dist/index.js","types":"dist/index.d.ts","repository":{"type":"git","url":"git+https://github.com/ai-standards/nativeai.git","directory":"packages/ai"},"homepage":"https://github.com/ai-standards/nativeai/tree/main/packages/ai","bugs":{"url":"https://github.com/ai-standards/nativeai/issues"},"scripts":{"build":"tsc","dev":"tsc --watch","test":"vitest","test:run":"vitest run"},"keywords":["ai","machine-learning","models","engine"],"author":"","license":"MIT","publishConfig":{"access":"public"},"devDependencies":{"@types/jest":"^29.0.0","@types/keytar":"^4.4.0","jest":"^29.0.0","typescript":"^5.0.0","vitest":"^1.6.1"},"dependencies":{"keytar":"^7.9.0","openai":"^6.3.0"},"_id":"@ai-standards/ai@0.9.0","gitHead":"6fbc94f94ad4bf457b278de9bfc504539a5c3f33","_nodeVersion":"24.5.0","_npmVersion":"11.5.1","dist":{"integrity":"sha512-KKWXdxMZ86z0mqTwMJCeUTrt+ryt7DrCB/fq3clwd2c9/nPaf5iYdMEsS5VIV2qxjE1wA/2gBlIMBYgKVyRxuA==","shasum":"16d6b873f48fe7d910903f5f38e1cb3896081b4e","tarball":"https://registry.npmjs.org/@ai-standards/ai/-/ai-0.9.0.tgz","fileCount":85,"unpackedSize":297692,"signatures":[{"keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U","sig":"MEUCIDKqCmrv+L3GMLDq8s9IgpXqcdMBPC5Cs7IK41dbu7HQAiEAiF112x5c9hmCj/OFZW8Oz53ZCt8wrIJYT0OetCnyWvM="}]},"_npmUser":{"name":"forrestlyman","email":"forrestswork@gmail.com"},"directories":{},"maintainers":[{"name":"forrestlyman","email":"forrestswork@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages-npm-production","tmp":"tmp/ai_0.9.0_1760281622038_0.5381350671438254"},"_hasShrinkwrap":false}},"time":{"created":"2025-10-12T15:07:01.968Z","0.9.0":"2025-10-12T15:07:02.245Z","modified":"2025-10-12T15:07:02.519Z"},"maintainers":[{"name":"forrestlyman","email":"forrestswork@gmail.com"}],"description":"AI engine and models for native AI","homepage":"https://github.com/ai-standards/nativeai/tree/main/packages/ai","keywords":["ai","machine-learning","models","engine"],"repository":{"type":"git","url":"git+https://github.com/ai-standards/nativeai.git","directory":"packages/ai"},"bugs":{"url":"https://github.com/ai-standards/nativeai/issues"},"license":"MIT","readme":"# Native AI Client\n\nA unified TypeScript/JavaScript client library for AI services with support for multiple providers. Currently supports OpenAI with a clean, extensible adapter pattern.\n\n## Installation\n\n```bash\nnpm install @ai-standards/ai\n```\n\n## Quick Start\n\n### 1. Store your API key securely\n\n```typescript\nimport { setKey } from '@ai-standards/ai';\n\n// Store your OpenAI API key (one-time setup)\nawait setKey('your-openai-api-key', 'openai');\n```\n\n### 2. Create and use the client\n\n```typescript\nimport { clientFactory } from '@ai-standards/ai';\n\n// Client automatically uses your stored API key\nconst client = await clientFactory();\n\n// Start using AI features immediately\nconst response = await client.getText({\n  prompt: \"Write a haiku about programming\"\n});\nconsole.log(response.text);\n```\n\n### Alternative Methods\n\n**Manual API Key (not recommended for production):**\n```typescript\nconst client = await clientFactory({\n  apiKey: 'your-openai-api-key'\n});\n```\n\n**Environment Variable:**\n```bash\nexport OPENAI_API_KEY=\"your-openai-api-key\"\n```\n```typescript\nconst client = await clientFactory(); // Uses environment variable\n```\n\n## Secure API Key Storage\n\nThe client uses your system's secure credential manager (Keychain on macOS, Credential Vault on Windows, Secret Service on Linux) to safely store API keys.\n\n### Basic Key Management\n\n```typescript\nimport { setKey, getKey, destroyKey } from '@ai-standards/ai';\n\n// Store your API key (one-time setup)\nawait setKey('your-openai-api-key', 'openai');\n\n// Check if key exists\nconst key = await getKey('openai');\nconsole.log(key ? 'Key stored' : 'No key found');\n\n// Remove stored key\nawait destroyKey('openai');\n```\n\n### Why Use Secure Storage?\n\n✅ **Secure** - Keys stored in system credential manager  \n✅ **Convenient** - No need to manage API keys in code  \n✅ **Safe** - No risk of accidentally committing keys to version control  \n✅ **Cross-platform** - Works on macOS, Windows, and Linux\n\n## Client Methods\n\n### 1. Text Generation (`getText`)\n\nGenerate text completions from a prompt.\n\n```typescript\nconst response = await client.getText({\n  prompt: \"Write a haiku about programming\",\n  model: \"gpt-4o-mini\", // optional, defaults to gpt-4o-mini\n  maxTokens: 100,\n  temperature: 0.7,\n  topP: 1.0,\n  frequencyPenalty: 0,\n  presencePenalty: 0,\n  stop: [\"END\"]\n});\n\nconsole.log(response.text);\nconsole.log(`Model used: ${response.model}`);\nconsole.log(`Tokens used: ${response.usage?.totalTokens}`);\n```\n\n**Response:**\n```typescript\n{\n  text: \"Code flows like water\\nBugs dance in morning sunlight\\nCoffee solves all things\",\n  model: \"gpt-4o-mini\",\n  usage: {\n    promptTokens: 8,\n    completionTokens: 20,\n    totalTokens: 28\n  },\n  finishReason: \"stop\"\n}\n```\n\n### 2. Chat Conversations (`chat`)\n\nHave conversations with the AI using a message-based format.\n\n```typescript\nconst response = await client.chat({\n  messages: [\n    { role: \"system\", content: \"You are a helpful coding assistant.\" },\n    { role: \"user\", content: \"How do I create a REST API in Node.js?\" },\n    { role: \"assistant\", content: \"To create a REST API in Node.js, you can use Express...\" },\n    { role: \"user\", content: \"What about authentication?\" }\n  ],\n  model: \"gpt-4o-mini\",\n  maxTokens: 500,\n  temperature: 0.7\n});\n\nconsole.log(response.message.content);\n```\n\n**Response:**\n```typescript\n{\n  message: {\n    role: \"assistant\",\n    content: \"For authentication in your REST API, you have several options:\\n\\n1. **JWT (JSON Web Tokens)**...\"\n  },\n  model: \"gpt-4o-mini\",\n  usage: {\n    promptTokens: 45,\n    completionTokens: 150,\n    totalTokens: 195\n  },\n  finishReason: \"stop\"\n}\n```\n\n### 3. Streaming Chat (`chatStream`)\n\nGet real-time streaming responses for chat conversations.\n\n```typescript\nconst stream = client.chatStream({\n  messages: [\n    { role: \"user\", content: \"Explain quantum computing in simple terms\" }\n  ],\n  model: \"gpt-4o-mini\",\n  maxTokens: 200\n});\n\nconsole.log(\"Streaming response:\");\nfor await (const chunk of stream) {\n  if (chunk.delta.content) {\n    process.stdout.write(chunk.delta.content);\n  }\n  \n  if (chunk.finishReason) {\n    console.log(`\\nStream finished: ${chunk.finishReason}`);\n  }\n}\n```\n\n**Stream chunks:**\n```typescript\n{ delta: { content: \"Quantum\" }, model: \"gpt-4o-mini\" }\n{ delta: { content: \" computing\" }, model: \"gpt-4o-mini\" }\n{ delta: { content: \" is like\" }, model: \"gpt-4o-mini\" }\n// ... more chunks\n{ delta: { content: \"\" }, model: \"gpt-4o-mini\", finishReason: \"stop\" }\n```\n\n### 4. Structured Data Extraction (`getData`)\n\nExtract structured data in various formats (JSON, CSV, XML, etc.).\n\n```typescript\nconst response = await client.getData({\n  prompt: `Extract the following information from this text:\n  \"John Smith, age 30, works as a Software Engineer at TechCorp, earns $120,000 annually\"\n  \n  Extract: name, age, job_title, company, salary`,\n  format: \"json\",\n  schema: {\n    type: \"object\",\n    properties: {\n      name: { type: \"string\" },\n      age: { type: \"number\" },\n      job_title: { type: \"string\" },\n      company: { type: \"string\" },\n      salary: { type: \"number\" }\n    }\n  },\n  model: \"gpt-4o-mini\"\n});\n\nconsole.log(response.data);\n```\n\n**Response:**\n```typescript\n{\n  data: {\n    name: \"John Smith\",\n    age: 30,\n    job_title: \"Software Engineer\",\n    company: \"TechCorp\",\n    salary: 120000\n  },\n  format: \"json\",\n  model: \"gpt-4o-mini\",\n  usage: {\n    promptTokens: 35,\n    completionTokens: 25,\n    totalTokens: 60\n  }\n}\n```\n\n**CSV Format Example:**\n```typescript\nconst csvResponse = await client.getData({\n  prompt: \"Convert this data to CSV format: John (30), Jane (25), Bob (35)\",\n  format: \"csv\"\n});\n\nconsole.log(csvResponse.data);\n// Output: \"name,age\\nJohn,30\\nJane,25\\nBob,35\"\n```\n\n### 5. Image Generation (`getImage`)\n\nGenerate images from text descriptions.\n\n```typescript\nconst response = await client.getImage({\n  prompt: \"A serene mountain landscape at sunset with a crystal clear lake reflection\",\n  model: \"dall-e-3\",\n  n: 1,\n  size: \"1024x1024\",\n  quality: \"hd\",\n  style: \"vivid\",\n  responseFormat: \"url\"\n});\n\nconsole.log(`Generated image: ${response.data[0].url}`);\nconsole.log(`Revised prompt: ${response.data[0].revised_prompt}`);\n```\n\n**Response:**\n```typescript\n{\n  data: [\n    {\n      url: \"https://oaidalleapiprodscus.blob.core.windows.net/...\",\n      revised_prompt: \"A tranquil mountain landscape during sunset...\"\n    }\n  ],\n  created: 1697123456\n}\n```\n\n**Generate multiple images:**\n```typescript\nconst multipleImages = await client.getImage({\n  prompt: \"A cute robot assistant\",\n  model: \"dall-e-2\", // DALL-E 2 supports multiple images\n  n: 3,\n  size: \"512x512\"\n});\n\nmultipleImages.data.forEach((image, index) => {\n  console.log(`Image ${index + 1}: ${image.url}`);\n});\n```\n\n### 6. Text-to-Speech (`getAudio`)\n\nConvert text to speech audio.\n\n```typescript\nconst response = await client.getAudio({\n  input: \"Hello! This is a test of the text-to-speech functionality.\",\n  model: \"tts-1\",\n  voice: \"alloy\", // alloy, echo, fable, onyx, nova, shimmer\n  responseFormat: \"mp3\",\n  speed: 1.0\n});\n\n// Save the audio to a file\nimport { writeFileSync } from 'fs';\nconst buffer = Buffer.from(response.audio);\nwriteFileSync('output.mp3', buffer);\n\nconsole.log(`Audio generated: ${response.contentType}`);\n```\n\n**Different voices and formats:**\n```typescript\n// High-quality voice with different format\nconst highQualityAudio = await client.getAudio({\n  input: \"This is a high-quality audio sample.\",\n  model: \"tts-1-hd\",\n  voice: \"nova\",\n  responseFormat: \"wav\",\n  speed: 0.8 // Slower speech\n});\n\n// Save as WAV\nconst wavBuffer = Buffer.from(highQualityAudio.audio);\nwriteFileSync('output.wav', wavBuffer);\n```\n\n### 7. Speech-to-Text (`transcribeAudio`)\n\nTranscribe audio files to text.\n\n```typescript\nimport { readFileSync } from 'fs';\n\n// Load audio file\nconst audioFile = new File([readFileSync('audio.mp3')], 'audio.mp3', { \n  type: 'audio/mp3' \n});\n\nconst response = await client.transcribeAudio({\n  file: audioFile,\n  model: \"whisper-1\",\n  language: \"en\", // optional\n  prompt: \"This is a podcast about technology\", // optional context\n  responseFormat: \"json\",\n  temperature: 0\n});\n\nconsole.log(`Transcription: ${response.text}`);\n```\n\n**Verbose format with timestamps:**\n```typescript\nconst verboseResponse = await client.transcribeAudio({\n  file: audioFile,\n  model: \"whisper-1\",\n  responseFormat: \"verbose_json\"\n});\n\nconsole.log(`Full transcription: ${verboseResponse.text}`);\nconsole.log(`Language detected: ${verboseResponse.language}`);\nconsole.log(`Duration: ${verboseResponse.duration} seconds`);\n\n// Print segments with timestamps\nverboseResponse.segments?.forEach(segment => {\n  console.log(`[${segment.start}s - ${segment.end}s]: ${segment.text}`);\n});\n```\n\n**Different response formats:**\n```typescript\n// Get SRT subtitle format\nconst srtResponse = await client.transcribeAudio({\n  file: audioFile,\n  responseFormat: \"srt\"\n});\nconsole.log(srtResponse.text); // SRT formatted subtitles\n\n// Get VTT format\nconst vttResponse = await client.transcribeAudio({\n  file: audioFile,\n  responseFormat: \"vtt\"\n});\nconsole.log(vttResponse.text); // WebVTT formatted subtitles\n```\n\n## Advanced Usage\n\n### Error Handling\n\n```typescript\nimport { clientFactory, NativeAiProvider } from '@ai-standards/ai';\n\ntry {\n  const client = await clientFactory({\n    provider: NativeAiProvider.openAi,\n    apiKey: 'invalid-key'\n  });\n  \n  const response = await client.getText({\n    prompt: \"Hello world\"\n  });\n} catch (error) {\n  console.error('Error:', error.message);\n}\n```\n\n### Custom Configuration\n\n```typescript\n// Use specific model for all requests\nconst client = await clientFactory({\n  provider: NativeAiProvider.openAi,\n  apiKey: process.env.OPENAI_API_KEY\n});\n\n// All requests will use gpt-4 unless overridden\nconst response = await client.getText({\n  prompt: \"Explain machine learning\",\n  model: \"gpt-4\", // Override default\n  temperature: 0.3,\n  maxTokens: 1000\n});\n```\n\n### Working with Files\n\n```typescript\n// For browser environments\nconst fileInput = document.getElementById('audioFile') as HTMLInputElement;\nconst file = fileInput.files?.[0];\n\nif (file) {\n  const transcription = await client.transcribeAudio({\n    file: file,\n    model: \"whisper-1\"\n  });\n  console.log(transcription.text);\n}\n\n// For Node.js environments\nimport { createReadStream } from 'fs';\n\nconst audioBuffer = readFileSync('audio.mp3');\nconst audioFile = new File([audioBuffer], 'audio.mp3', { type: 'audio/mp3' });\n\nconst transcription = await client.transcribeAudio({\n  file: audioFile,\n  model: \"whisper-1\"\n});\n```\n\n## API Reference\n\n### Core Functions\n\n```typescript\n// Client factory\nfunction clientFactory(options?: NativeAiClientOptions): Promise<NativeAiClient>\n\n// Key management\nfunction setKey(key: string, account?: string): Promise<void>\nfunction getKey(account?: string): Promise<string | null>\nfunction destroyKey(account?: string): Promise<boolean>\n```\n\n### Key Types\n\n```typescript\n// Client options (optional - uses stored keys by default)\ninterface NativeAiClientOptions {\n  apiKey?: string;      // Manual API key (alternative method)\n  provider?: string;    // Provider name (defaults to 'openai')\n}\n\n// Message format for chat\ninterface BaseMessage {\n  role: 'system' | 'user' | 'assistant';\n  content: string;\n}\n```\n\n### Supported Models\n\n**OpenAI Models:**\n- Text/Chat: `gpt-4o-mini` (default), `gpt-4`, `gpt-3.5-turbo`, `gpt-4-turbo`\n- Images: `dall-e-3` (default), `dall-e-2`\n- Audio TTS: `tts-1` (default), `tts-1-hd`\n- Audio STT: `whisper-1` (default)\n\n### Supported Audio Formats\n\n**Input (Speech-to-Text):** mp3, mp4, mpeg, mpga, m4a, wav, webm\n\n**Output (Text-to-Speech):** mp3, opus, aac, flac, wav, pcm\n\n### Supported Voices\n\n**TTS Voices:** alloy, echo, fable, onyx, nova, shimmer\n\n## Error Handling\n\nThe client provides detailed error information:\n\n```typescript\ntry {\n  const response = await client.getText({\n    prompt: \"Test\",\n    maxTokens: -1 // Invalid parameter\n  });\n} catch (error) {\n  console.error('API Error:', error.message);\n  console.error('Error code:', error.code);\n  console.error('Error type:', error.type);\n}\n```\n\n## Contributing\n\nThis library uses an adapter pattern to support multiple AI providers. To add a new provider:\n\n1. Implement the `NativeAiAdapter` interface\n2. Add the provider to `NativeAiProvider` enum\n3. Update the `createAdapter` factory function\n4. Add comprehensive tests\n\n## License\n\nMIT License - see LICENSE file for details.","readmeFilename":"README.md","_rev":"1-9000add04c9a02fb2cee2067c89e6855"}