Download the PHP package moe-mizrak/laravel-openrouter without Composer

On this page you can find all versions of the php package moe-mizrak/laravel-openrouter. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.

FAQ

After the download, you have to make one include require_once('vendor/autoload.php');. After that you have to import the classes with use statements.

Example:
If you use only one package a project is not needed. But if you use more then one package, without a project it is not possible to import the classes with use statements.

In general, it is recommended to use always a project to download your libraries. In an application normally there is more than one library needed.
Some PHP packages are not free to download and because of that hosted in private repositories. In this case some credentials are needed to access such packages. Please use the auth.json textarea to insert credentials, if a package is coming from a private repository. You can look here for more information.

  • Some hosting areas are not accessible by a terminal or SSH. Then it is not possible to use Composer.
  • To use Composer is sometimes complicated. Especially for beginners.
  • Composer needs much resources. Sometimes they are not available on a simple webspace.
  • If you are using private repositories you don't need to share your credentials. You can set up everything on our site and then you provide a simple download link to your team member.
  • Simplify your Composer build process. Use our own command line tool to download the vendor folder as binary. This makes your build process faster and you don't need to expose your credentials for private repositories.
Please rate this library. Is it a good library?

Informations about the package laravel-openrouter

Laravel OpenRouter


Latest Version on Packagist OpenRouter Discord Total Downloads

reboosty

This Laravel package provides an easy-to-use interface for integrating OpenRouter into your Laravel applications. OpenRouter is a unified interface for Large Language Models (LLMs) that allows you to interact with various AI models through a single API.

Table of Contents

🤖 Requirements

🏁 Get Started

You can install the package via composer:

You can publish the config file with:

This is the contents of the published config file:

🧩 Configuration

After publishing the package configuration file, you'll need to add the following environment variables to your .env file:

[!NOTE]

  • OPENROUTER_API_ENDPOINT: The endpoint URL for the OpenRouter API (default: https://openrouter.ai/api/v1/).
  • OPENROUTER_API_KEY: Your API key for accessing the OpenRouter API. You can obtain this key from the OpenRouter dashboard.
  • OPENROUTER_API_TIMEOUT: Request timeout in seconds. Increase value to 120 - 180 if you use long-thinking models like openai/o1 (default: 20)
  • OPENROUTER_API_TITLE: Optional - Site URL for rankings on openrouter.ai
  • OPENROUTER_API_REFERER: Optional - Site referer for rankings on openrouter.ai

🎨 Usage

This package provides two ways to interact with the OpenRouter API:

Both methods utilize the ChatData DTO class to structure the data sent to the API.

Understanding ChatData DTO

The ChatData class is used to encapsulate the data required for making chat requests to the OpenRouter API. Here's a breakdown of the key properties:

LLM Parameters

These properties control various aspects of the generated response (more info):

Tool-calling Parameters

Only natively suported by OpenAI models. For others, we submit a YAML-formatted string with these tools at the end of the prompt.

Additional optional parameters

OpenRouter-only parameters

Provider Preferences

The OpenRouter Provider Selection.

Property Type Description
allow_fallbacks bool\|null Whether to allow backup providers when the primary is unavailable (default: true).
require_parameters bool\|null Only use providers that support all parameters in your request.
data_collection string\|null DataCollectionType::ALLOW (default) or DataCollectionType::DENY.
order array\|null Ordered list of provider slugs to prefer.
zdr bool\|null Restrict routing to only Zero Data Retention endpoints.
enforce_distillable_text bool\|null Restrict routing to only models that allow text distillation.
only array\|null List of provider slugs to allow for this request.
ignore array\|null List of provider slugs to skip for this request.
quantizations array\|null Filter by quantization levels (see QuantizationType).
sort string\|ProviderSortData\|null Sort providers by "price", "throughput", or "latency". Can also be a ProviderSortData object with by and partition fields.
preferred_min_throughput float\|PercentileData\|null Preferred minimum throughput (tokens/sec). Can be a number or PercentileData with percentile cutoffs (p50, p75, p90, p99).
preferred_max_latency float\|PercentileData\|null Preferred maximum latency (seconds). Can be a number or PercentileData with percentile cutoffs.
max_price MaxPriceData\|null Maximum acceptable pricing with prompt, completion, request, and image fields (in USD).

Example with advanced provider preferences:

Creating a ChatData Instance

This is a sample chat data instance (Refer to spatie laravel-data how to create, use DTOs):

Using Facade

The LaravelOpenRouter facade offers a convenient way to make OpenRouter API requests.

Chat Request

To send a chat request, create an instance of ChatData and pass it to the chatRequest method:

You do not need to specify 'stream' = true in ChatData since chatStreamRequest does it for you.

Streaming usage example:
Sample rawResponse: This is the expected sample rawResponse (raw response returned from OpenRouter stream chunk) `$rawResponse`: Last `data:` carries usage information of streaming. `data: [DONE]\n` returned from OpenRouter server when streaming is over. This is the sample response after filterStreamingResponse:

Expected response:

Tool calls (also known as function calls) give an LLM access to external tools. The LLM does not call the tools directly. Instead, it suggests the tool to call.

[!NOTE] The user then calls the tool separately and provides the results back to the LLM. Finally, the LLM formats the response into an answer to the user’s original question.

This is an example of how to use tool calling with OpenRouter:

Basically it follows these steps:

  1. Define the tools and send the initial chat request including the tools and tool_choice optional parameters.
  2. If the LLM suggests a tool call, extract the tool call information from the response and make the actual tool call separately.
  3. Provide the tool result back to the LLM by creating a new chat request that includes the original user message, the assistant's tool call message, and the tool response message including the tool_call_id which is the ID generated by the model/LLM for the tool call.
  4. Send the new chat request to get the final response from the LLM.

If you want to receive the response in a structured format, you can specify the type property for response_format (ChatData object.

Additionally, it's recommended to set the require_parameters property for provider (ChatData object.

[!CAUTION] When using structured outputs, you may encounter these scenarios:

  • Model doesn’t support structured outputs
  • Invalid schema

Also: If you face an error, remove require_parameters property of provider to see the result.

Check out Requiring Providers to Support All Parameters for more details.

You can also specify the response_format as json_schema to receive the response in a specified schema format (Advisable to set 'strict' => true in json_schema array for strict schema):

[!TIP] You can also use prompt engineering to obtain structured output and control the format of responses.

Web Search feature works on any model on OpenRouter.

You can incorporate relevant web search results for any model on OpenRouter by activating and customizing the web plugin, or by appending :online to the model slug. e.g., model: "openai/gpt-4o:online" or model: "openai/gpt-oss-20b:free:online".

web_search_options parameter in ChatData is optional, where you can customize the web search behavior as search_context_size can be set to low, medium, or high depending on how much web search context you want to include in the response.

:online is a shortcut for using the web plugin, and is exactly equivalent to:

engine parameter in PluginData is optional, where you can specify the web search engine to be used:

And here is how annotations are included in the response when using web search where annotations contains type: url_citation and url_citation: {url, title, content, start_index, end_index}:

You can provide file input by using the FileContentData DTO class as following:

[!NOTE]

  • plugins parameter in ChatData is optional.
  • If you don’t explicitly specify an engine, OpenRouter will default first to the model’s native file processing capabilities, and if that’s not available, it will use the "mistral-ocr" engine.

Using base64-encoded files:

[!TIP]

  • File input feature works on any model on OpenRouter.
  • The filename parameter is optional but recommended for context.

Audio input is supported by some models in OpenRouter. You can provide audio input by using the AudioContentData DTO class as following:

[!NOTE] Only mp3 and wav formats are supported for audio inputs.

And make sure to provide valid base64-encoded audio data.

OpenRouter supports prompt caching on supported providers/models to decrease cost and latency on repeated requests. This package supports both approaches described in OpenRouter docs:

OpenRouter docs: Prompt Caching

Top-level example (automatic caching):

Explicit breakpoint example (cache a large text block):

Cost Request

To retrieve the cost of a generation, first make a chat request and obtain the generationId. Then, pass the generationId to the costRequest method:

Limit Request

To retrieve rate limit and credits left on the API key:

Using OpenRouterRequest Class

You can also inject the OpenRouterRequest class in the constructor of your class and use its methods directly.

💫 Contributing

We welcome contributions! If you'd like to improve this package, simply create a pull request with your changes. Your efforts help enhance its functionality and documentation.

Please read our Contributing Guide for details on our development process, commit conventions, and how to submit pull requests.

📜 License

Laravel OpenRouter is an open-sourced software licensed under the MIT license.


All versions of laravel-openrouter with dependencies

PHP Build Version
Package Version
Requires php Version ^8.2
ext-json Version *
spatie/laravel-data Version ^4.13
guzzlehttp/guzzle Version ^7.9
caseyamcl/guzzle_retry_middleware Version ^2.12
Composer command for our command line client (download client) This client runs in each environment. You don't need a specific PHP version etc. The first 20 API calls are free. Standard composer command

The package moe-mizrak/laravel-openrouter contains the following files

Loading the files please wait ...