This guide provides comprehensive examples for using the Hasab AI Laravel SDK in your Laravel applications.
- Installation
- Configuration
- Usage Patterns
- Chat Service
- Transcription Service
⚠️ Ongoing Implementation - Translation Service
⚠️ Ongoing Implementation - Text-to-Speech (TTS) Service
- Error Handling
Install the package via Composer:
composer require kalebalebachew/hasab-laravelPublish the configuration file:
php artisan vendor:publish --tag=hasab-configAdd your Hasab AI API credentials to your .env file:
HASAB_API_KEY=your-api-key-here
HASAB_BASE_URL=https://hasab.co/api
HASAB_API_VERSION=v1The configuration file (config/hasab.php) will be published to your application:
return [
'key' => env('HASAB_API_KEY', ''),
'base_url' => env('HASAB_BASE_URL', 'https://hasab.co/api'),
'version' => env('HASAB_API_VERSION', 'v1'),
];The SDK supports three different usage patterns:
use Hasab\Facades\Hasab;
$response = Hasab::chat()->complete([
'message' => 'Hello, Hasab!',
'model' => 'hasab-1-lite',
]);use Hasab\HasabManager;
class MyController extends Controller
{
public function __construct(protected HasabManager $hasab)
{
}
public function index()
{
$response = $this->hasab->chat()->complete([
'message' => 'Hello, Hasab!',
]);
return view('chat', compact('response'));
}
}$hasab = app(Hasab\HasabManager::class);
$response = $hasab->chat()->complete([
'message' => 'Hello, Hasab!',
]);The Chat Service allows you to interact with Hasab AI's conversational models.
use Hasab\Facades\Hasab;
$response = Hasab::chat()->complete([
'message' => 'What is the capital of Ethiopia?',
'model' => 'hasab-1-lite', // Optional, defaults to 'hasab-1-lite'
]);
// Response format:
// [
// 'response' => 'The capital of Ethiopia is Addis Ababa.',
// 'model' => 'hasab-1-lite',
// ...
// ]$response = Hasab::chat()->complete([
'message' => 'What is in this image?',
'image' => storage_path('app/images/photo.jpg'),
'model' => 'hasab-vision', // Optional
]);$history = Hasab::chat()->history();
// Returns array of previous chat messages$response = Hasab::chat()->clear();
// Clears all chat history for the current session$title = Hasab::chat()->title();
// Returns the title of the current chat session$response = Hasab::chat()->updateTitle('My Important Conversation');
// Sets a custom title for the chat session
⚠️ ONGOING IMPLEMENTATION: This feature is currently under active development. The API interface may change in future releases.
The Transcription Service converts audio files to text. Supported formats: MP3, WAV, M4A.
Important: The service automatically includes required fields (
keyandis_meeting) when you upload. You typically only need to provide thefileorurlparameter.
use Hasab\Facades\Hasab;
$result = Hasab::transcription()->upload([
'file' => storage_path('app/audio/recording.mp3'),
// Optional: 'key' => 'unique-audio-id', // Auto-generated if not provided
// Optional: 'is_meeting' => false, // Default: false
]);
// Response includes:
// - transcription: The transcribed text
// - audio: Audio file details and metadata
// - tokens_used: Number of tokens consumedIf your audio file is already hosted online, you can provide a URL instead:
$result = Hasab::transcription()->upload([
'url' => 'https://example.com/audio/recording.mp3',
'key' => 'my-unique-audio-key', // Required when using URL
'is_meeting' => false, // Optional: mark as meeting recording
]);$result = Hasab::transcription()->upload([
'file' => storage_path('app/audio/recording.wav'),
// Identification (auto-generated if not provided)
'key' => 'interview-2024-01-15', // Unique identifier for this audio
'is_meeting' => false, // Is this a meeting recording?
// Processing options
'transcribe' => true, // Enable transcription (default: true)
'translate' => false, // Enable translation (default: false)
'summarize' => false, // Enable summarization (default: false)
'timestamps' => false, // Include timestamps (default: false)
// Language settings
'language' => 'auto', // Target language (default: 'auto')
'source_language' => 'amh', // Source language: 'amh', 'eng', 'orm', etc.
]);
// Response structure:
// [
// 'success' => true,
// 'message' => 'Audio uploaded and processed successfully',
// 'audio' => [
// 'id' => 8769,
// 'filename' => 'audio.mp3',
// 'transcription' => 'The transcribed text...',
// 'translation' => '',
// 'summary' => '',
// 'duration_in_seconds' => 23.98,
// 'audio_url' => 'https://hasab.s3.amazonaws.com/...',
// ...
// ],
// 'transcription' => 'The transcribed text...',
// 'timestamp' => [...], // If timestamps: true
// 'translation' => '',
// 'summary' => '',
// 'metadata' => [
// 'tokens_charged' => 6,
// 'remaining_tokens' => 150,
// 'charge_message' => 'Tokens charged successfully'
// ]
// ]$result = Hasab::transcription()->upload([
'file' => storage_path('app/audio/speech.mp3'),
'transcribe' => true,
'translate' => true,
'source_language' => 'amh', // Amharic audio
'language' => 'eng', // Translate to English
]);
// Access the translation
$translatedText = $result['translation'];$result = Hasab::transcription()->upload([
'file' => storage_path('app/audio/meeting.mp3'),
'key' => 'meeting-jan-2024', // Optional unique identifier
'transcribe' => true,
'summarize' => true,
'language' => 'auto',
]);
// Access the summary
$summary = $result['summary'];
$fullTranscript = $result['transcription'];$result = Hasab::transcription()->upload([
'file' => storage_path('app/audio/interview.wav'),
'transcribe' => true,
'timestamps' => true, // Get word-level timestamps
'source_language' => 'eng',
]);
// Access timestamps
foreach ($result['timestamp'] as $segment) {
echo "[$segment[start]s - $segment[end]s]: $segment[content]\n";
}
// Output example:
// [0s - 1.52s]: የፋሲልለደስ ቤተመንግስት እዚህ ጋር
// [1.6s - 3.36s]: እንደምታዩት በፊት ከነበረው ከለርMark audio files as meeting recordings for better processing:
$result = Hasab::transcription()->upload([
'file' => storage_path('app/meetings/team-standup.mp3'),
'key' => 'standup-2024-01-15',
'is_meeting' => true, // Mark as meeting recording
'transcribe' => true,
'summarize' => true, // Get meeting summary
'timestamps' => true, // Track who spoke when
]);
// Access meeting-specific data
$summary = $result['summary'];
$transcript = $result['transcription'];// Get first page
$transcriptions = Hasab::transcription()->history();
// Get specific page
$page2 = Hasab::transcription()->history(page: 2);
// Response structure:
// [
// 'status' => 'success',
// 'data' => [
// 'current_page' => 1,
// 'data' => [...], // Array of transcription records
// 'total' => 439,
// 'per_page' => 15,
// 'last_page' => 30,
// ...
// ]
// ]Retrieve a previously processed transcription by its ID:
$audio = Hasab::transcription()->get(8769);
// Returns:
// [
// 'id' => 8769,
// 'filename' => 'recording.mp3',
// 'transcription' => 'Full transcribed text...',
// 'translation' => '...',
// 'summary' => '...',
// 'duration_in_seconds' => 23.98,
// 'audio_url' => 'https://hasab.s3.amazonaws.com/...',
// 'created_at' => '2024-01-15T10:30:00Z',
// ...
// ]Remove a transcription from your history:
$result = Hasab::transcription()->delete(8769);
// Returns:
// [
// 'success' => true,
// 'message' => 'Audio file deleted successfully'
// ]
⚠️ ONGOING IMPLEMENTATION: This feature is currently under active development. The API interface may change in future releases.
The Translation Service provides text-to-text translation between supported languages.
use Hasab\Facades\Hasab;
// Translate a single text
$result = Hasab::translation()->translate([
'text' => 'Hello, how are you?',
'source_language' => 'eng', // Source: English
'target_language' => 'amh', // Target: Amharic
]);
// Access the translated text
$translatedText = $result['translated_text'];The translation API supports batch translation of multiple texts at once:
$result = Hasab::translation()->translate([
'text' => [
'Hello, how are you?',
'What\'s your name?',
'Nice to meet you',
'Have a great day!',
],
'source_language' => 'eng',
'target_language' => 'orm', // Afaan Oromo
]);
// Access the translated texts (array)
$translations = $result['translations'];
// Process each translation
foreach ($translations as $index => $translation) {
echo "Original: {$result['original'][$index]}\n";
echo "Translation: {$translation}\n\n";
}Common language codes:
eng- Englishamh- Amharic (አማርኛ)orm- Afaan Oromotir- Tigrinyasom- Somali
$result = Hasab::translation()->translate([
'text' => 'Welcome to Hasab AI. We provide powerful AI tools.',
'source_language' => 'eng',
'target_language' => 'amh',
]);
echo $result['translated_text'];
// Output: እንኳን ወደ ሃሳብ AI በደህና መጡ። ኃይለኛ የ AI መሣሪያዎችን እናቀርባለን።$result = Hasab::translation()->translate([
'text' => 'ጤና ይስጥልኝ። ስምህ ማን ይባላል?',
'source_language' => 'amh',
'target_language' => 'eng',
]);
echo $result['translated_text'];
// Output: Hello. What is your name?
// Get first page
$translations = Hasab::translation()->history();
// With pagination
$page2 = Hasab::translation()->history(page: 2);The TTS Service converts text to natural-sounding speech.
use Hasab\Facades\Hasab;
$result = Hasab::tts()->synthesize(
text: 'እንኳን ደህና መጣህ። Welcome to Hasab AI.',
language: 'am', // Language code
speaker: 'default' // Optional: specific speaker name
);
// Response includes audio URL or audio data// Get all speakers
$speakers = Hasab::tts()->speakers();
// Get speakers for specific language
$amharicSpeakers = Hasab::tts()->speakers(language: 'am');$history = Hasab::tts()->history();
// Returns list of previously synthesized audio files$result = Hasab::tts()->delete(id: 123);
// Deletes a specific TTS recording by IDThe SDK throws exceptions when API requests fail. Always wrap your calls in try-catch blocks:
use Hasab\Facades\Hasab;
use Illuminate\Http\Client\RequestException;
try {
$response = Hasab::chat()->complete([
'message' => 'Hello!',
]);
// Process successful response
return response()->json($response);
} catch (RequestException $e) {
// Handle HTTP errors (4xx, 5xx)
return response()->json([
'error' => 'API request failed',
'message' => $e->getMessage(),
'status' => $e->response->status() ?? 500,
], $e->response->status() ?? 500);
} catch (\Exception $e) {
// Handle general errors
return response()->json([
'error' => 'An unexpected error occurred',
'message' => $e->getMessage(),
], 500);
}try {
$result = Hasab::transcription()->upload([
'file' => $filePath,
'language' => 'invalid-lang',
]);
} catch (RequestException $e) {
if ($e->response->status() === 422) {
// Validation error
$errors = $e->response->json('errors');
return back()->withErrors($errors);
}
throw $e;
}use Illuminate\Support\Facades\Log;
try {
$response = Hasab::chat()->complete([
'message' => $message,
]);
Log::info('Hasab API call successful', [
'service' => 'chat',
'message' => $message,
]);
return $response;
} catch (\Exception $e) {
Log::error('Hasab API call failed', [
'service' => 'chat',
'error' => $e->getMessage(),
'trace' => $e->getTraceAsString(),
]);
throw $e;
}namespace App\Jobs;
use Hasab\Facades\Hasab;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
class ProcessAudioTranscription implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public function __construct(
protected string $filePath,
protected int $userId
) {}
public function handle(): void
{
try {
$result = Hasab::transcription()->upload([
'file' => $this->filePath,
'transcribe' => true,
'summarize' => true,
'language' => 'auto',
'timestamps' => true,
]);
// Store results in database
\App\Models\Transcription::create([
'user_id' => $this->userId,
'hasab_audio_id' => $result['audio']['id'],
'file_path' => $this->filePath,
'filename' => $result['audio']['filename'],
'transcription' => $result['transcription'] ?? '',
'summary' => $result['summary'] ?? '',
'duration' => $result['audio']['duration_in_seconds'],
'audio_url' => $result['audio']['audio_url'],
'timestamps' => json_encode($result['timestamp'] ?? []),
'tokens_used' => $result['metadata']['tokens_charged'],
'status' => 'completed',
]);
} catch (\Exception $e) {
\Log::error('Transcription failed', [
'error' => $e->getMessage(),
'file' => $this->filePath,
]);
throw $e;
}
}
}| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
file |
string | Yes | - | Path to audio file (MP3, WAV, M4A) |
transcribe |
boolean | No | true |
Enable transcription |
translate |
boolean | No | false |
Enable translation |
summarize |
boolean | No | false |
Generate summary |
language |
string | No | 'auto' |
Target language for output |
source_language |
string | No | null |
Source audio language (amh, eng, orm) |
timestamps |
boolean | No | false |
Include word-level timestamps |
amh- Amharic (አማርኛ)eng- Englishorm- Oromo (Afaan Oromoo)auto- Auto-detect (for transcription)
- Store API Keys Securely: Never commit your
.envfile or hardcode API keys - Use Queues: Process long-running operations (transcription, translation) in background jobs
- Cache Results: Cache frequently accessed data like TTS speakers list
- Error Handling: Always implement proper error handling and user feedback
- File Validation: Validate file types (MP3, WAV, M4A) and sizes before uploading
- Timestamps: Enable
timestamps: trueonly when needed as it increases processing time - Source Language: Specify
source_languagefor better accuracy when the language is known - Monitor Token Usage: Check
metadata.remaining_tokensin responses to track your usage
For issues, questions, or contributions, please visit:
- GitHub: kalebalebachew/hasab-laravel
- Email: kalebalebachew4@gmail.com