chore: Update readme
This commit is contained in:
113
README.md
113
README.md
@@ -86,66 +86,93 @@ const provider = createProvider('claude', { apiKey: 'your-key' });
|
|||||||
|
|
||||||
## 🎨 Structured Response Types
|
## 🎨 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
|
```typescript
|
||||||
import { createResponseType, validateResponseType } from 'simple-ai-provider';
|
import { createResponseType, createClaudeProvider } from 'simple-ai-provider';
|
||||||
|
|
||||||
// Define your response type
|
// 1. Define your response type
|
||||||
interface UserProfile {
|
interface ProductAnalysis {
|
||||||
name: string;
|
productName: string;
|
||||||
age: number;
|
priceRange: 'budget' | 'mid-range' | 'premium';
|
||||||
email: string;
|
pros: string[];
|
||||||
preferences: {
|
cons: string[];
|
||||||
theme: 'light' | 'dark';
|
overallRating: number; // 1-10 scale
|
||||||
notifications: boolean;
|
recommendation: 'buy' | 'consider' | 'avoid';
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const userProfileType = createResponseType<UserProfile>(
|
// 2. Create a ResponseType object
|
||||||
|
const productAnalysisType = createResponseType<ProductAnalysis>(
|
||||||
`{
|
`{
|
||||||
name: string;
|
productName: string;
|
||||||
age: number;
|
priceRange: 'budget' | 'mid-range' | 'premium';
|
||||||
email: string;
|
pros: string[];
|
||||||
preferences: {
|
cons: string[];
|
||||||
theme: 'light' | 'dark';
|
overallRating: number;
|
||||||
notifications: boolean;
|
recommendation: 'buy' | 'consider' | 'avoid';
|
||||||
};
|
|
||||||
}`,
|
}`,
|
||||||
'A user profile with personal information and preferences',
|
'A comprehensive product analysis with pros, cons, rating, and recommendation'
|
||||||
{
|
|
||||||
name: 'John Doe',
|
|
||||||
age: 30,
|
|
||||||
email: 'john@example.com',
|
|
||||||
preferences: { theme: 'dark', notifications: true }
|
|
||||||
}
|
|
||||||
);
|
);
|
||||||
|
|
||||||
// Use with any provider
|
// 3. Use with any provider
|
||||||
const response = await claude.complete({
|
const claude = createClaudeProvider({ apiKey: 'your-key' });
|
||||||
|
await claude.initialize();
|
||||||
|
|
||||||
|
const response = await claude.complete<ProductAnalysis>({
|
||||||
messages: [
|
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,
|
responseType: productAnalysisType,
|
||||||
maxTokens: 500
|
maxTokens: 800
|
||||||
});
|
});
|
||||||
|
|
||||||
// Validate and get typed response
|
// 4. Get the fully typed and parsed response
|
||||||
const validation = validateResponseType(response.content, userProfileType);
|
const analysis = response.content;
|
||||||
if (validation.isValid) {
|
console.log(`Product: ${analysis.productName}`);
|
||||||
const userProfile = validation.data as UserProfile;
|
console.log(`Recommendation: ${analysis.recommendation}`);
|
||||||
console.log(`Name: ${userProfile.name}`);
|
console.log(`Rating: ${analysis.overallRating}/10`);
|
||||||
console.log(`Theme: ${userProfile.preferences.theme}`);
|
|
||||||
}
|
|
||||||
```
|
```
|
||||||
|
|
||||||
### Key Benefits
|
### Key Benefits
|
||||||
|
|
||||||
- **Type Safety**: Get fully typed responses from AI providers
|
- **Automatic Parsing**: The AI's JSON response is automatically parsed into your specified type.
|
||||||
- **Automatic Prompting**: System prompts are automatically generated
|
- **Type Safety**: Get fully typed responses from AI providers with IntelliSense.
|
||||||
- **Validation**: Built-in response validation and parsing
|
- **Automatic Prompting**: System prompts are automatically generated to guide the AI.
|
||||||
- **Consistency**: Ensures AI outputs match your expected format
|
- **Validation**: Built-in response validation and parsing logic.
|
||||||
- **Developer Experience**: IntelliSense and compile-time type checking
|
- **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
|
## 📝 Environment Variables
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user