navi-ai/php-sdk
Composer 安装命令:
composer require navi-ai/php-sdk
包简介
Official PHP SDK for Navi AI Agent Platform - Build AI-powered conversations with ease
README 文档
README
Official PHP SDK for the Navi AI Agent Platform.
Requirements
- PHP 8.1 or higher
- Composer
Installation
composer require navi-ai/php-sdk
Or add to your composer.json:
{
"require": {
"navi-ai/php-sdk": "^1.0"
}
}
Quick Start
<?php require 'vendor/autoload.php'; use Navi\NaviClient; // Initialize the client $navi = new NaviClient('navi_sk_your_api_key', [ 'base_url' => 'https://your-navi-instance.com' ]); // Create a conversation $conversation = $navi->conversations->create([ 'agentId' => 'your-agent-uuid', 'contactId' => 'contact-123', 'title' => 'Support Request' ]); // Send a message with streaming response $navi->conversations->chat($conversation->id, 'Hello, I need help!', function($event) { if ($event->isTextDelta()) { echo $event->getText(); flush(); } }); // Close the conversation when done $navi->conversations->close($conversation->id);
Configuration
$navi = new NaviClient('navi_sk_your_api_key', [ 'base_url' => 'https://your-navi-instance.com', // Required 'api_path' => '/api/integration', // API path (default: /api/integration) 'timeout' => 30, // Request timeout in seconds 'verify_ssl' => true, // SSL verification ]);
API Reference
Check API Status
$status = $navi->status(); echo $status->integrationName; // "My Integration" echo $status->status; // "active" echo $status->rateLimitPerMinute; // 60 or null echo $status->defaultAgentId; // "agent-uuid" or null
Agents
List Available Agents
$agents = $navi->agents->list([ 'search' => 'support', // Optional: search by name 'limit' => 20, // Optional: max results (default: 50) 'offset' => 0 // Optional: pagination offset ]); foreach ($agents as $agent) { echo "{$agent->id}: {$agent->name}"; if ($agent->isDefault) { echo " (default)"; } echo "\n"; }
Get a Specific Agent
$agent = $navi->agents->get('agent-uuid'); echo $agent->name; echo $agent->description; echo $agent->isDefault ? 'Default agent' : 'Not default';
Conversations
Create a Conversation
$conversation = $navi->conversations->create([ 'agentId' => 'agent-uuid', // Required 'contactId' => 'contact-123', // Optional: identify the contact 'contactName' => 'John Doe', // Optional: display name 'contactMetadata' => [ // Optional: custom metadata (flat key-value pairs) 'customerId' => 'CUS-123', 'tier' => 'premium', 'region' => 'us-east' ], 'title' => 'Order Inquiry', // Optional: conversation title 'context' => [ // Optional: additional context 'orderId' => '12345', 'customerTier' => 'premium' ] ]); echo $conversation->id; // Conversation UUID echo $conversation->status; // "active"
Contact Metadata: Flat key-value pairs stored with the contact for additional information and search capabilities. Values can be strings, numbers, booleans, or null. Metadata is merged on updates (new values override existing).
List Conversations
$conversations = $navi->conversations->list([ 'contactId' => 'contact-123', // Optional: filter by contact 'status' => 'active', // Optional: "active", "closed", "archived" 'limit' => 20, // Optional: max results (default: 50) 'offset' => 0 // Optional: pagination offset ]); foreach ($conversations as $conv) { echo "{$conv->id}: {$conv->title}\n"; }
Get a Conversation
$conversation = $navi->conversations->get('conversation-uuid'); echo $conversation->title; echo $conversation->status; echo $conversation->messageCount; // Messages are included foreach ($conversation->messages as $message) { echo "[{$message->role}]: {$message->content}\n"; }
With contact filtering (to ensure contacts only access their own conversations):
$conversation = $navi->conversations->get('conversation-uuid', [ 'contactId' => 'contact-123' // Only return if conversation belongs to this contact ]);
Update a Conversation
$conversation = $navi->conversations->update('conversation-uuid', [ 'title' => 'Updated Title' ]); echo $conversation->title; // "Updated Title"
With contact filtering for authorization:
$conversation = $navi->conversations->update('conversation-uuid', ['title' => 'New Title'], ['contactId' => 'contact-123'] // Only update if conversation belongs to this contact );
List Messages with Pagination
$page = $navi->conversations->messages('conversation-uuid', [ 'contactId' => 'contact-123', // Optional: filter by contact for authorization 'limit' => 20, 'offset' => 0, 'order' => 'desc' // 'asc' (oldest first) or 'desc' (newest first) ]); foreach ($page->messages as $message) { echo "[{$message->role}]: {$message->content}\n"; } echo "Total: {$page->total}"; echo "Has more: " . ($page->hasMore ? 'yes' : 'no'); // Get next page if ($page->hasMore) { $nextPage = $navi->conversations->messages('conversation-uuid', [ 'contactId' => 'contact-123', 'limit' => 20, 'offset' => $page->getNextOffset() ]); }
Close a Conversation
$navi->conversations->close('conversation-uuid'); // With contact filtering for authorization $navi->conversations->close('conversation-uuid', [ 'contactId' => 'contact-123' // Only close if conversation belongs to this contact ]);
Chat
Streaming with Callback
Best for real-time output in CLI or streaming HTTP responses:
$navi->conversations->chat($conversationId, 'Hello!', function($event) { match($event->type) { 'message_created' => null, // User message saved 'reasoning_delta' => null, // Agent thinking (optional to display) 'tool_start' => print("Using tool: {$event->getToolName()}...\n"), 'tool_complete' => print("Tool completed\n"), 'response_delta' => print($event->getText()), 'complete' => print("\n[Done]\n"), 'error' => print("Error: {$event->getError()}\n"), default => null }; });
Streaming with Generator
For more control over the stream processing:
$fullResponse = ''; foreach ($navi->conversations->chatStream($conversationId, 'Hello!') as $event) { if ($event->type === 'response_delta') { $fullResponse .= $event->getText(); echo $event->getText(); } if ($event->isError()) { throw new Exception($event->getError()); } }
Synchronous (Non-Streaming)
Wait for the complete response:
$response = $navi->conversations->chatSync($conversationId, 'Hello!'); if ($response->success) { echo $response->content; echo "Tokens used: {$response->tokensUsed}"; echo "Duration: {$response->durationMs}ms"; } else { echo "Error: {$response->error}"; }
With Contact Identification
You can specify the contact sending the message. This creates or retrieves a contact to associate with the message:
$navi->conversations->chat($conversationId, 'Hello!', function($event) { /* ... */ }, [ 'contactId' => 'contact-123', // Identifier for the contact 'contactName' => 'John Doe', // Display name (used for new contacts or updates) 'contactMetadata' => [ // Custom metadata (flat key-value pairs) 'customerId' => 'CUS-123', 'tier' => 'premium' ] ] );
This is useful when:
- Multiple contacts share the same conversation (e.g., group support)
- You want to track which contact sent each message
- You need to associate messages with specific contacts in the system
- You want to store searchable metadata with contacts
With Context
Pass additional context with your message:
$navi->conversations->chat($conversationId, 'What is the status of my order?', function($event) { /* ... */ }, [ 'context' => [ 'orderId' => '12345', 'orderStatus' => 'shipped', 'trackingNumber' => 'ABC123' ] ] );
With Runtime Parameters
Runtime parameters are dynamic values that can be injected at execution time and referenced
in agent configurations using ${params.key} syntax. Use them for user tokens, API keys,
and other per-execution values:
$navi->conversations->chat($conversationId, 'Get my account balance', function($event) { /* ... */ }, [ 'runtimeParams' => [ 'user_token' => 'jwt-abc123xyz', // Used in: ${params.user_token} 'api_key' => 'sk-secret-key', // Used in: ${params.api_key} 'user_id' => 42, // Used in: ${params.user_id} 'organization_id' => 'org-123' // Used in: ${params.organization_id} ] ] );
Where runtime parameters can be used in agent configuration:
- MCP server headers:
Authorization: Bearer ${params.user_token} - HTTP request headers:
X-API-Key: ${params.api_key} - Custom functions:
tools.getParam('user_id') - Agent instructions:
You are helping user ${params.user_id}
Built-in parameters (automatically available):
| Parameter | Description |
|---|---|
params.current_date |
Current date (YYYY-MM-DD) |
params.current_datetime |
Full ISO datetime |
params.current_timestamp |
Unix timestamp in ms |
params.execution_id |
Unique execution identifier |
Example combining contact identification, metadata, context, and runtime parameters:
$navi->conversations->chat($conversationId, 'Check my order status', function($event) { if ($event->isTextDelta()) { echo $event->getText(); } }, [ 'contactId' => $_SESSION['user_id'], 'contactName' => $_SESSION['user_name'], 'contactMetadata' => [ 'customerId' => $_SESSION['customer_id'], 'tier' => $_SESSION['subscription_tier'] ], 'context' => [ 'orderId' => '12345' ], 'runtimeParams' => [ 'user_token' => $_SESSION['user_token'], 'user_id' => $_SESSION['user_id'] ] ] );
Stream Events
| Event | Description | Data |
|---|---|---|
message_created |
User message saved | userMessageId, conversationId |
reasoning_start |
Agent started thinking | - |
reasoning_delta |
Agent thinking text | text |
reasoning_complete |
Agent finished thinking | action, confidence |
tool_start |
Tool execution started | tool, args |
tool_complete |
Tool execution finished | tool, result |
response_start |
Response generation started | - |
response_delta |
Response text chunk | text |
response_complete |
Response finished | response |
complete |
Execution complete | success, executionId, assistantMessageId, stats |
error |
Error occurred | error |
Error Handling
use Navi\Exceptions\AuthenticationException; use Navi\Exceptions\NotFoundException; use Navi\Exceptions\RateLimitException; use Navi\Exceptions\ValidationException; use Navi\Exceptions\NaviException; try { $conversation = $navi->conversations->get('invalid-uuid'); } catch (AuthenticationException $e) { // Invalid API key echo "Auth error: " . $e->getMessage(); } catch (NotFoundException $e) { // Resource not found echo "Not found: " . $e->getMessage(); } catch (RateLimitException $e) { // Rate limit exceeded echo "Rate limited. Retry after: " . $e->getRetryAfter() . " seconds"; } catch (ValidationException $e) { // Validation error echo "Validation error: " . $e->getMessage(); print_r($e->getErrors()); } catch (NaviException $e) { // Other API error echo "Error: " . $e->getMessage(); echo "Status: " . $e->getStatusCode(); }
Complete Example
<?php require 'vendor/autoload.php'; use Navi\NaviClient; use Navi\Exceptions\NaviException; $navi = new NaviClient('navi_sk_your_api_key', [ 'base_url' => 'https://your-navi-instance.com' ]); // Simulated contact session $currentContactId = 'customer-456'; $currentContactName = 'Jane Smith'; try { // Check API status $status = $navi->status(); if (!$status->isActive()) { die("Integration is disabled"); } // Create or get existing conversation $conversation = $navi->conversations->create([ 'agentId' => $status->defaultAgentId ?? 'your-agent-uuid', 'contactId' => $currentContactId, 'contactName' => $currentContactName, 'title' => 'Product Inquiry' ]); echo "Conversation started: {$conversation->id}\n\n"; // Chat loop while (true) { echo "You: "; $input = trim(fgets(STDIN)); if ($input === 'quit' || $input === 'exit') { break; } echo "Agent: "; $navi->conversations->chat($conversation->id, $input, function($event) { if ($event->type === 'response_delta') { echo $event->getText(); } }, [ 'contactId' => $currentContactId, 'contactName' => $currentContactName ] ); echo "\n\n"; } // Close conversation (with contact verification) $navi->conversations->close($conversation->id, [ 'contactId' => $currentContactId ]); echo "Conversation closed.\n"; } catch (NaviException $e) { echo "Error: " . $e->getMessage() . "\n"; exit(1); }
License
MIT
navi-ai/php-sdk 适用场景与选型建议
navi-ai/php-sdk 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 383 次下载、GitHub Stars 达 0, 最近一次更新时间为 2025 年 11 月 27 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「sdk」 「API-Client」 「Agent」 「ai」 「navi」 「chatbot」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 navi-ai/php-sdk 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 navi-ai/php-sdk 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 navi-ai/php-sdk 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Custom laravel monolog logger for datadog logs management, both api and agent ways
Skolkovo API Client
The Message Submission Agent Diagnostics tool (msadiag) facilitates testing the compatibility of third party message submission agents.
Standalone replacement for php's native get_browser() function
A PHP desktop/mobile user agent parser with support for Laravel, based on Mobiledetect
A client library for the OpenPLZ API project
统计信息
- 总下载量: 383
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 21
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2025-11-27