No description
  • PHP 96.6%
  • Shell 3.4%
Find a file
Joris Schelfhout 9e7da6efac refactor: update composer dependencies and improve tool execution handling
- Remove deprecated dependencies from `composer.json`, including `illuminate/support` and `orchestra/testbench`, to streamline the project and reduce unnecessary complexity.
- Introduce `mockery/mockery` as a new development dependency for enhanced testing capabilities.
- Refactor the `LMStudioFactory` and related classes to improve the management of non-streaming and streaming turn handlers, ensuring better separation of concerns and clearer code structure.
- Update the `Tool` and `ToolDefinition` classes to enhance validation and error handling for tool parameters, improving robustness.
- Remove the `LMStudioServiceProvider` and related Laravel components to simplify the codebase and focus on core functionalities.
- This refactor enhances the maintainability and usability of the LMStudio API, promoting better practices in dependency management and tool execution.
2025-04-02 03:01:15 +02:00
.github/workflows chore: prepare for v1 release 2025-02-24 01:25:50 +01:00
bin feat: enhance LMStudio CLI with new commands and environment variable support 2025-03-14 23:38:16 +01:00
docs/lmstudio feat: restructure LM Studio documentation and enhance API references 2025-03-16 20:16:15 +01:00
scripts feat: restructure LM Studio documentation and enhance API references 2025-03-16 20:16:15 +01:00
src refactor: update composer dependencies and improve tool execution handling 2025-04-02 03:01:15 +02:00
tests refactor: update composer dependencies and improve tool execution handling 2025-04-02 03:01:15 +02:00
.gitignore feat: enhance LMStudio CLI with new commands and environment variable support 2025-03-14 23:38:16 +01:00
CHANGELOG.md feat: update project configuration and dependencies 2025-03-11 01:56:56 +01:00
composer.json refactor: update composer dependencies and improve tool execution handling 2025-04-02 03:01:15 +02:00
composer.lock refactor: update composer dependencies and improve tool execution handling 2025-04-02 03:01:15 +02:00
CONTRIBUTING.md chore: prepare for v1 release 2025-02-24 01:25:50 +01:00
LICENSE chore: prepare for v1 release 2025-02-24 01:25:50 +01:00
phpstan.neon feat: enhance dependency management and improve documentation 2025-03-31 02:16:57 +02:00
phpunit.xml refactor: update PHPUnit configuration and introduce individual test execution script 2025-04-02 01:54:09 +02:00
pint.json Refactor project structure and add type safety with DTOs and enums 2025-02-23 23:48:48 +01:00
README.md feat: enhance dependency management and improve documentation 2025-03-31 02:16:57 +02:00
run_tests_individually.sh refactor: update PHPUnit configuration and introduce individual test execution script 2025-04-02 01:54:09 +02:00
SECURITY.md docs: add security policy and guidelines 2025-02-24 01:26:30 +01:00

LMStudio PHP Client

A PHP client for interacting with LMStudio and OpenAI-compatible APIs.

Installation

composer require shelfwood/lmstudio

Basic Usage

<?php

require 'vendor/autoload.php';

use Shelfwood\LMStudio\LMStudioFactory;

// Assuming LMSTUDIO_API_BASE is set in your environment or .env
$factory = new LMStudioFactory();

// --- Non-Streaming Chat ---
$conversation = $factory->createConversation('your-model-id');
$conversation->addSystemMessage('You are helpful.');
$conversation->addUserMessage('What is the capital of Spain?');

$response = $conversation->getResponse(); // Handles the API call
echo "Assistant: {$response}\n";

// --- Streaming Chat ---
$streamingConversation = $factory->createStreamingConversation('your-model-id');
$streamingConversation->addSystemMessage('You are helpful.');
$streamingConversation->addUserMessage('Explain black holes simply.');

// Optional: Add listeners to observe the stream
$handler = $streamingConversation->streamingHandler;
if ($handler) {
    $handler->on('stream_content', fn(string $content) => print($content));
    $handler->on('stream_end', fn() => print("\n"));
}

// handleStreamingTurn manages the entire process
$finalResponse = $streamingConversation->handleStreamingTurn();
echo "\nFinal Response (after stream): {$finalResponse}\n";

Usage with Tools

Tools allow the model to call predefined PHP functions.

<?php

require 'vendor/autoload.php';

use Shelfwood\LMStudio\LMStudioFactory;

$factory = new LMStudioFactory();

// --- Non-Streaming Chat with Tools ---
$conversationWithTools = $factory->createConversation('your-model-id');

// Register tools (manually or load from config service)
$toolRegistry = $conversationWithTools->toolRegistry;
$toolRegistry->registerTool(
    'calculate',
    fn(string $expression) => ['result' => eval("return {$expression};")], // Basic eval - CAUTION in production!
    [
        'type' => 'object',
        'properties' => [
            'expression' => ['type' => 'string', 'description' => 'Math expression']
        ],
        'required' => ['expression']
    ],
    'Calculate a math expression.'
);

$conversationWithTools->addUserMessage('What is 5 * 8?');

// getResponse handles the tool call automatically if the model decides to use it
$responseWithTools = $conversationWithTools->getResponse();
echo "Assistant (Tools): {$responseWithTools}\n";

// --- Streaming Chat with Tools ---
$streamingConvWithTools = $factory->createStreamingConversation('your-model-id');

// Register tools (same as above)
$toolRegistryStream = $streamingConvWithTools->toolRegistry;
$toolRegistryStream->registerTool('calculate', /* ... same definition ... */ );

$streamingConvWithTools->addUserMessage('Calculate 100 / 4 please.');

// Optional: Listen for tool events
$handlerTools = $streamingConvWithTools->streamingHandler;
if ($handlerTools) {
    $handlerTools->on('stream_content', fn(string $content) => print($content));
    $handlerTools->on('stream_tool_call', fn($toolCall) => print("\n[Tool Call: {$toolCall->name}]\n"));
    $handlerTools->on('stream_end', fn() => print("\n"));
}
$streamingConvWithTools->eventHandler->on('tool_executed', fn($id, $name, $result) => print("[Tool Executed: {$name} -> ".json_encode($result)."]\n"));

// handleStreamingTurn manages the stream, tool execution, and final response
$finalResponseToolsStream = $streamingConvWithTools->handleStreamingTurn();
echo "\nFinal Response (Tools, Stream): {$finalResponseToolsStream}\n";

Console Commands

The library provides commands for interacting with the API via the console (useful for testing and demonstration).

Setup (if using Laravel):

  1. Publish the configuration:
    php artisan vendor:publish --tag="lmstudio-config"
    
  2. Set your LMSTUDIO_API_BASE and optionally LMSTUDIO_DEFAULT_MODEL in your .env file.

Available Commands:

  • php <your_console_runner> sequence: Runs a predefined sequence of API calls (list models, chat, streaming chat, tools) to demonstrate functionality.
    • --model=<model_id>: Specify a model to use.
  • php <your_console_runner> chat: Starts an interactive, non-streaming chat session in your terminal. Supports tool use.
    • --model=<model_id>: Specify a model to use.
    • --system="Your prompt": Set a custom system prompt.
    • Type /quit to exit the chat.

Replace <your_console_runner> with artisan for Laravel or your specific entry point (e.g., bin/lmstudio if you set up a custom runner).

License

MIT