Skip to content

Commit badfc01

Browse files
authored
feat: docs (#7)
* Update LanguageModelSession.ts * add docs * update * add favicon * Update docusaurus.config.ts * docs deployment
1 parent 91276a6 commit badfc01

29 files changed

+6005
-79
lines changed

bun.lock

Lines changed: 1949 additions & 76 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

docs/.gitignore

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
# Dependencies
2+
/node_modules
3+
4+
# Production
5+
/build
6+
7+
# Generated files
8+
.docusaurus
9+
.cache-loader
10+
11+
# Misc
12+
.DS_Store
13+
.env.local
14+
.env.development.local
15+
.env.test.local
16+
.env.production.local
17+
18+
npm-debug.log*
19+
yarn-debug.log*
20+
yarn-error.log*

docs/README.md

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
# Website
2+
3+
This website is built using [Docusaurus](https://docusaurus.io/), a modern static website generator.
4+
5+
## Installation
6+
7+
```bash
8+
yarn
9+
```
10+
11+
## Local Development
12+
13+
```bash
14+
yarn start
15+
```
16+
17+
This command starts a local development server and opens up a browser window. Most changes are reflected live without having to restart the server.
18+
19+
## Build
20+
21+
```bash
22+
yarn build
23+
```
24+
25+
This command generates static content into the `build` directory and can be served using any static contents hosting service.
26+
27+
## Deployment
28+
29+
Using SSH:
30+
31+
```bash
32+
USE_SSH=true yarn deploy
33+
```
34+
35+
Not using SSH:
36+
37+
```bash
38+
GIT_USER=<Your GitHub username> yarn deploy
39+
```
40+
41+
If you are using GitHub pages for hosting, this command is a convenient way to build the website and push to the `gh-pages` branch.

docs/bun.lock

Lines changed: 2490 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

docs/docs/api-reference.md

Lines changed: 200 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,200 @@
1+
---
2+
sidebar_position: 3
3+
---
4+
5+
# API Reference
6+
7+
## LanguageModelSession
8+
9+
### Constructor
10+
11+
Creates a new LanguageModelSession instance. Throws an error if Apple Intelligence is not available.
12+
13+
```typescript
14+
constructor(config?: LanguageModelSessionConfig)
15+
```
16+
17+
**Parameters**:
18+
- `config.instructions?: string` - System instructions defining AI behavior
19+
- `config.tools?: ToolDefinition[]` - Array of tools the AI can invoke
20+
21+
### Instance Methods
22+
23+
#### `streamResponse(prompt, callback)`
24+
25+
Initiates a streaming response from the language model.
26+
27+
```typescript
28+
streamResponse(prompt: string, callback: (fullResponse: string) => void): void
29+
```
30+
31+
**Parameters**:
32+
- `prompt: string` - The user's message
33+
- `callback: (fullResponse: string) => void` - Called with the complete response so far
34+
35+
## Functions
36+
37+
### `checkFoundationModelsAvailability()`
38+
39+
Check if Apple Intelligence is available on the device.
40+
41+
```typescript
42+
function checkFoundationModelsAvailability(): FoundationModelsAvailability
43+
```
44+
45+
**Returns**: Availability status object with `isAvailable`, `status`, and `message`.
46+
47+
## Hooks
48+
49+
### `useLanguageModel(config?)`
50+
51+
React hook for managing language model sessions with automatic lifecycle management.
52+
53+
```typescript
54+
function useLanguageModel(config?: UseLanguageModelConfig): UseLanguageModelReturn
55+
```
56+
57+
**Parameters**:
58+
- `config.instructions?: string` - System instructions for the AI
59+
- `config.tools?: ToolDefinition[]` - Tools the AI can use
60+
- `config.onResponse?: (response: string) => void` - Callback for responses
61+
- `config.onError?: (error: AppleAIError) => void` - Callback for errors
62+
63+
**Returns**:
64+
- `session: LanguageModelSession | null` - Current session instance
65+
- `response: string` - Latest response from the AI
66+
- `loading: boolean` - Whether a request is in progress
67+
- `error: AppleAIError | null` - Last error that occurred
68+
- `send: (prompt: string) => Promise<string>` - Function to send messages
69+
- `reset: () => void` - Reset response and error state
70+
- `isSessionReady: boolean` - Whether session is initialized and ready
71+
72+
### `useStreamingResponse(session)`
73+
74+
Lower-level hook for streaming AI responses with more control.
75+
76+
```typescript
77+
function useStreamingResponse(session: LanguageModelSession): UseStreamingResponseReturn
78+
```
79+
80+
**Parameters**:
81+
- `session: LanguageModelSession` - The session to use for streaming
82+
83+
**Returns**:
84+
- `response: string` - Current response text
85+
- `isStreaming: boolean` - Whether currently streaming
86+
- `isComplete: boolean` - Whether streaming is complete
87+
- `error: AppleAIError | null` - Last error that occurred
88+
- `streamResponse: (prompt: string, options?: StreamingOptions) => Promise<string>` - Start streaming
89+
- `cancel: () => void` - Cancel current stream
90+
- `reset: () => void` - Reset state
91+
92+
## Types
93+
94+
### `FoundationModelsAvailability`
95+
96+
```typescript
97+
interface FoundationModelsAvailability {
98+
isAvailable: boolean;
99+
status: AvailabilityStatus;
100+
message: string;
101+
}
102+
```
103+
104+
### `AvailabilityStatus`
105+
106+
```typescript
107+
type AvailabilityStatus =
108+
| 'available'
109+
| 'unavailable.platformNotSupported'
110+
| 'unavailable.deviceNotEligible'
111+
| 'unavailable.appleIntelligenceNotEnabled'
112+
| 'unavailable.modelNotReady'
113+
| 'unavailable.unknown'
114+
```
115+
116+
### `LanguageModelSessionConfig`
117+
118+
```typescript
119+
interface LanguageModelSessionConfig {
120+
instructions?: string;
121+
tools?: ToolDefinition[];
122+
}
123+
```
124+
125+
### `ToolDefinition`
126+
127+
```typescript
128+
interface ToolDefinition {
129+
name: string;
130+
description: string;
131+
arguments: AnyMap;
132+
handler: (args: AnyMap) => Promise<AnyMap>;
133+
}
134+
```
135+
136+
### `AppleAIError`
137+
138+
```typescript
139+
class AppleAIError extends Error {
140+
readonly code: string;
141+
readonly details?: Record<string, any>;
142+
143+
constructor(code: string, message: string, details?: Record<string, any>);
144+
static fromErrorInfo(errorInfo: AppleAIErrorInfo): AppleAIError;
145+
toErrorInfo(): AppleAIErrorInfo;
146+
}
147+
```
148+
149+
#### Error Codes
150+
151+
- `SESSION_NOT_INITIALIZED` - Session is not ready
152+
- `TOOL_CALL_ERROR` - Tool call failed
153+
- `TOOL_EXECUTION_ERROR` - Tool execution failed
154+
- `SCHEMA_CREATION_ERROR` - Failed to create tool schema
155+
- `ARGUMENT_PARSING_ERROR` - Failed to parse tool arguments
156+
- `RESPONSE_PARSING_ERROR` - Failed to parse tool response
157+
- `UNKNOWN_TOOL_ERROR` - Unknown tool referenced
158+
- `SESSION_STREAMING_ERROR` - Streaming failed
159+
- `UNSUPPORTED_PLATFORM` - Platform not supported
160+
161+
### `StreamingOptions`
162+
163+
```typescript
164+
interface StreamingOptions {
165+
onToken?: (token: string) => void;
166+
onComplete?: (fullResponse: string) => void;
167+
onError?: (error: AppleAIError) => void;
168+
}
169+
```
170+
171+
## Utilities
172+
173+
### `createTool(definition)`
174+
175+
Helper function to create type-safe tools with Zod schema validation.
176+
177+
```typescript
178+
function createTool<T extends ZodObjectSchema>(definition: {
179+
name: string;
180+
description: string;
181+
arguments: T;
182+
handler: (params: z.infer<T>) => Promise<AnyMap>;
183+
}): ToolDefinition
184+
```
185+
186+
### `isAppleAIError(error)`
187+
188+
Type guard to check if an error is an AppleAIError.
189+
190+
```typescript
191+
function isAppleAIError(error: any): error is AppleAIError
192+
```
193+
194+
### `parseNativeError(error)`
195+
196+
Parse native errors into AppleAIError instances.
197+
198+
```typescript
199+
function parseNativeError(error: any): AppleAIError
200+
```

docs/docs/core-concepts.md

Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
---
2+
sidebar_position: 2
3+
---
4+
5+
# Core Concepts
6+
7+
## Language Model Sessions
8+
9+
The `LanguageModelSession` is the core class that manages AI conversations. Each session maintains context and can be configured with:
10+
11+
- **Instructions**: Define the AI's behavior and role
12+
- **Tools**: Custom functions the AI can invoke
13+
- **Streaming**: Real-time response handling
14+
15+
```typescript
16+
import { LanguageModelSession } from 'react-native-apple-ai';
17+
18+
const session = new LanguageModelSession({
19+
instructions: "You are a helpful coding assistant.",
20+
tools: [weatherTool, calculatorTool]
21+
});
22+
```
23+
24+
## Apple Intelligence Availability
25+
26+
Before using the module, check if Apple Intelligence is available:
27+
28+
```typescript
29+
import { checkFoundationModelsAvailability } from 'react-native-apple-ai';
30+
31+
const availability = checkFoundationModelsAvailability();
32+
console.log(availability.status); // 'available' or 'unavailable.xxx'
33+
console.log(availability.message); // Human-readable message
34+
```
35+
36+
### Availability States
37+
38+
- `available`: Ready to use
39+
- `unavailable.platformNotSupported`: iOS version too old (requires 26.0+)
40+
- `unavailable.deviceNotEligible`: Device doesn't support Apple Intelligence
41+
- `unavailable.appleIntelligenceNotEnabled`: Not enabled in Settings
42+
- `unavailable.modelNotReady`: Model downloading or not ready
43+
- `unavailable.unknown`: Unknown reason
44+
45+
## Tool Calling
46+
47+
Define custom tools that the AI can invoke during conversations:
48+
49+
```typescript
50+
import { z } from 'zod';
51+
import { createTool } from 'react-native-apple-ai';
52+
53+
const weatherTool = createTool({
54+
name: 'get_weather',
55+
description: 'Get current weather for a location',
56+
schema: z.object({
57+
location: z.string().describe('The city and state/country'),
58+
unit: z.enum(['celsius', 'fahrenheit']).optional()
59+
}),
60+
handler: async ({ location, unit = 'celsius' }) => {
61+
// Fetch weather data
62+
return `Weather in ${location}: 22°${unit === 'celsius' ? 'C' : 'F'}`;
63+
}
64+
});
65+
```
66+
67+
## Streaming Responses
68+
69+
Handle real-time AI responses as they're generated:
70+
71+
```typescript
72+
session.streamResponse("Tell me a story", (fullResponse: string) => {
73+
console.log(fullResponse); // Gets called with the complete response so far
74+
});
75+
```
76+
77+
## Error Handling
78+
79+
The module provides specific error types for different failure scenarios:
80+
81+
```typescript
82+
import { AppleAIError, isAppleAIError } from 'react-native-apple-ai';
83+
84+
try {
85+
await session.streamResponse("Hello", (response) => {
86+
console.log(response);
87+
});
88+
} catch (error) {
89+
if (isAppleAIError(error)) {
90+
switch (error.code) {
91+
case 'SESSION_NOT_INITIALIZED':
92+
// Handle session not ready
93+
break;
94+
case 'TOOL_EXECUTION_ERROR':
95+
// Handle tool execution failure
96+
break;
97+
case 'UNSUPPORTED_PLATFORM':
98+
// Handle platform not supported
99+
break;
100+
}
101+
}
102+
}
103+
```

0 commit comments

Comments
 (0)