chore: Update readme

This commit is contained in:
2025-09-04 15:18:38 +02:00
parent 900ed70162
commit c801abc2e8

113
README.md
View File

@@ -86,66 +86,93 @@ const provider = createProvider('claude', { apiKey: 'your-key' });
## 🎨 Structured Response Types
Define custom response types for type-safe, structured AI outputs:
Define custom response types for type-safe, structured AI outputs. The library automatically parses the AI's response into your desired type.
```typescript
import { createResponseType, validateResponseType } from 'simple-ai-provider';
import { createResponseType, createClaudeProvider } from 'simple-ai-provider';
// Define your response type
interface UserProfile {
name: string;
age: number;
email: string;
preferences: {
theme: 'light' | 'dark';
notifications: boolean;
};
// 1. Define your response type
interface ProductAnalysis {
productName: string;
priceRange: 'budget' | 'mid-range' | 'premium';
pros: string[];
cons: string[];
overallRating: number; // 1-10 scale
recommendation: 'buy' | 'consider' | 'avoid';
}
const userProfileType = createResponseType<UserProfile>(
// 2. Create a ResponseType object
const productAnalysisType = createResponseType<ProductAnalysis>(
`{
name: string;
age: number;
email: string;
preferences: {
theme: 'light' | 'dark';
notifications: boolean;
};
productName: string;
priceRange: 'budget' | 'mid-range' | 'premium';
pros: string[];
cons: string[];
overallRating: number;
recommendation: 'buy' | 'consider' | 'avoid';
}`,
'A user profile with personal information and preferences',
{
name: 'John Doe',
age: 30,
email: 'john@example.com',
preferences: { theme: 'dark', notifications: true }
}
'A comprehensive product analysis with pros, cons, rating, and recommendation'
);
// Use with any provider
const response = await claude.complete({
// 3. Use with any provider
const claude = createClaudeProvider({ apiKey: 'your-key' });
await claude.initialize();
const response = await claude.complete<ProductAnalysis>({
messages: [
{ role: 'user', content: 'Generate a user profile for a software developer' }
{ role: 'user', content: 'Analyze the iPhone 15 Pro from a consumer perspective.' }
],
responseType: userProfileType,
maxTokens: 500
responseType: productAnalysisType,
maxTokens: 800
});
// Validate and get typed response
const validation = validateResponseType(response.content, userProfileType);
if (validation.isValid) {
const userProfile = validation.data as UserProfile;
console.log(`Name: ${userProfile.name}`);
console.log(`Theme: ${userProfile.preferences.theme}`);
}
// 4. Get the fully typed and parsed response
const analysis = response.content;
console.log(`Product: ${analysis.productName}`);
console.log(`Recommendation: ${analysis.recommendation}`);
console.log(`Rating: ${analysis.overallRating}/10`);
```
### Key Benefits
- **Type Safety**: Get fully typed responses from AI providers
- **Automatic Prompting**: System prompts are automatically generated
- **Validation**: Built-in response validation and parsing
- **Consistency**: Ensures AI outputs match your expected format
- **Developer Experience**: IntelliSense and compile-time type checking
- **Automatic Parsing**: The AI's JSON response is automatically parsed into your specified type.
- **Type Safety**: Get fully typed responses from AI providers with IntelliSense.
- **Automatic Prompting**: System prompts are automatically generated to guide the AI.
- **Validation**: Built-in response validation and parsing logic.
- **Consistency**: Ensures AI outputs match your expected format.
- **Developer Experience**: Catch errors at compile-time instead of runtime.
### Streaming with Response Types
You can also use response types with streaming. The raw stream provides real-time text, and you can parse the final string once the stream is complete.
```typescript
import { parseAndValidateResponseType } from 'simple-ai-provider';
const stream = claude.stream({
messages: [{ role: 'user', content: 'Analyze the Tesla Model 3.' }],
responseType: productAnalysisType,
maxTokens: 600
});
let fullResponse = '';
for await (const chunk of stream) {
if (!chunk.isComplete) {
process.stdout.write(chunk.content);
fullResponse += chunk.content;
} else {
console.log('\n\nStream complete!');
// Validate the complete streamed response
try {
const analysis = parseAndValidateResponseType(fullResponse, productAnalysisType);
console.log('Validation successful!');
console.log(`Product: ${analysis.productName}`);
} catch (e) {
console.error('Validation failed:', (e as Error).message);
}
}
}
```
## 📝 Environment Variables