Skip to content

Commit

Permalink
refactored existing class. Added an example.
Browse files Browse the repository at this point in the history
  • Loading branch information
namankumar80510 committed Sep 23, 2024
1 parent 65850a9 commit 5a97512
Show file tree
Hide file tree
Showing 4 changed files with 186 additions and 46 deletions.
18 changes: 18 additions & 0 deletions example/hello.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
#! /usr/bin/php env
<?php

/**
* Run this file in CLI and see the response.
*
* `php hello.php`
*
* Ensure that you create a .env file in root and add your CLAUDE_API.
*/

use Dikki\Claude\Claude;

require_once dirname(__DIR__) . '/vendor/autoload.php';

$claude = new Claude(parse_ini_file(dirname(__DIR__) . '/.env')['CLAUDE_API']);

var_dump($claude->getResponse("Define AI in one sentence."));
13 changes: 13 additions & 0 deletions phpcs.xml.dist
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<ruleset name="ClaudeSDK">
<description>PHP CodeSniffer rules for ClaudeSDK</description>

<rule ref="PSR12"/>

<rule ref="Generic.WhiteSpace.DisallowTabIndent" severity="error"/>
<rule ref="Squiz.WhiteSpace.FunctionSpacing" severity="warning"/>

<file>src/</file>

<exclude-pattern>vendor/*</exclude-pattern>
</ruleset>
65 changes: 57 additions & 8 deletions readme.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
# Claude API PHP SDK

This is a simple but useful PHP Class that you can use to communicate with Anthropic's Claude via API.

## Installation

```bash
Expand All @@ -8,21 +10,68 @@ composer require dikki/claude-sdk

## Usage

First create an instance of Claude class. Pass the api key as first parameter.
### Creating an Instance

You can pass the model name as second parameter or keep it empty to use default model (claude-instant-1.2).
First, create an instance of the `Claude` class. Pass the API key as the first parameter. You can pass the model name as the second parameter or keep it empty to use the default model (`claude-2.1`).

```php

$claude = new \Dikki\Claude\Claude($apiKey, 'claude-2.1');
```

### Methods

#### getResponse

To get the whole response from Claude, use the `getResponse()` method. It accepts the following parameters:

- **string $prompt**: The prompt to send to the API.
- **array $messages**: Optional. The messages to send to the API.
- **string|null $model**: Optional. The model to use for the API request.
- **int $maxTokens**: Optional. The maximum number of tokens to generate (default is 4000).
- **string $method**: Optional. The HTTP method to use for the request (default is 'POST').

Returns an array containing the full response, including text, model used, etc.

```php
$response = $claude->getResponse("Write an essay on AI.");
```

Next, pass a prompt to getResponse() method to get the whole response from claude, or to getTextResponse() to get only
string response.
#### getTextResponse

To get only the string response, use the `getTextResponse()` method. It accepts the same parameters as `getResponse()`.

Returns a string response.

```php
$response = $claude->getResponse("Write an essay on AI."); // returns an array as response containing, text, model used, etc.
$response = $claude->getTextResponse("Write an essay on AI.");
```

### Example Usage

```php
// Create an instance of Claude
$claude = new \Dikki\Claude\Claude($apiKey, 'claude-2.1');

// Get full response
$response = $claude->getResponse("Write an essay on AI.");

// Get only text response
$textResponse = $claude->getTextResponse("Write an essay on AI.");
```

### Class Overview

- **Class**: `Claude`
- **Namespace**: `Dikki\Claude`
- **Constructor Parameters**:
- `string $apiKey`: The API key for authentication.
- `string $model`: The model to use for the API requests (default is 'claude-2.1').
- `string $modelVersion`: The version of the model to use (default is '2023-06-01').

### Additional Information

- **getEndpoint()**: Returns the API endpoint URL.
- **prepareMessages()**: Prepares the messages for the API request.
- **getHeaders()**: Returns the headers for the API request.
- **getRequestBody()**: Returns the request body for the API request.

$response = $claude->getTextResponse("Write an essay on AI."); // returns only string response
```
136 changes: 98 additions & 38 deletions src/Claude.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,36 +8,55 @@
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;

/**
* Class Claude
*
* This class provides methods to interact with the Claude API.
*
* @package Dikki\Claude
*/
class Claude
{
/**
* @var Client
*/
private Client $client;


/**
* Claude constructor.
*
* @param string $apiKey The API key for authentication.
* @param string $model The model to use for the API requests.
* @param string $modelVersion The version of the model to use.
* @throws Exception
*/
public function __construct(
private readonly string $apiKey,
private readonly string $model = 'claude-instant-1.2',
private readonly string $model = 'claude-2.1',
private readonly string $modelVersion = '2023-06-01'
) {
$this->client = new Client();
}


/**
* Get the API endpoint URL.
*
* @return string The API endpoint URL.
*/
public function getEndpoint(): string
{
return "https://api.anthropic.com/v1/messages";
}


/**
* @param string $prompt
* @param array<mixed> $messages
* @param string|null $model
* @param int $maxTokens
* @param string $method
* @return array<mixed>
* Get the response from the Claude API.
*
* @param string $prompt The prompt to send to the API.
* @param array<mixed> $messages The messages to send to the API.
* @param string|null $model The model to use for the API request.
* @param int $maxTokens The maximum number of tokens to generate.
* @param string $method The HTTP method to use for the request.
* @return array<mixed> The response from the API.
* @throws GuzzleException
*/
public function getResponse(
Expand All @@ -47,47 +66,32 @@ public function getResponse(
int $maxTokens = 4000,
string $method = 'POST'
): array {

if (empty($messages)) {
$messages = [
[
'role' => 'user',
'content' => $prompt
]
];
}
if (empty($model)) {
$model = $this->model;
}
$messages = $this->prepareMessages($prompt, $messages);
$model = $model ?? $this->model;

$response = $this->client->request(
$method,
$this->getEndpoint(),
[
'headers' => [
'x-api-key' => $this->apiKey,
'content-type' => 'application/json',
'anthropic-version' => $this->modelVersion
],
'json' => [
'model' => $model,
'max_tokens' => $maxTokens,
'messages' => $messages
],
'headers' => $this->getHeaders(),
'json' => $this->getRequestBody($model, $maxTokens, $messages),
'verify' => false,
]
);

return json_decode($response->getBody()->getContents(), true);
}


/**
* @param string $prompt
* @param array<mixed> $messages
* @param string|null $model
* @param int $maxTokens
* @param string $method
* @return string
* Get the text response from the Claude API.
*
* @param string $prompt The prompt to send to the API.
* @param array<mixed> $messages The messages to send to the API.
* @param string|null $model The model to use for the API request.
* @param int $maxTokens The maximum number of tokens to generate.
* @param string $method The HTTP method to use for the request.
* @return string The text response from the API.
* @throws GuzzleException
*/
public function getTextResponse(
Expand All @@ -99,4 +103,60 @@ public function getTextResponse(
): string {
return $this->getResponse($prompt, $messages, $model, $maxTokens, $method)['content'][0]['text'];
}


/**
* Prepare the messages for the API request.
*
* @param string $prompt The prompt to send to the API.
* @param array<mixed> $messages The messages to send to the API.
* @return array<mixed> The prepared messages.
*/
private function prepareMessages(string $prompt, array $messages): array
{
if (empty($messages)) {
$messages = [
[
'role' => 'user',
'content' => $prompt
]
];
}
return $messages;
}


/**
* Get the headers for the API request.
*
* @return array<string, string> The headers for the API request.
*/
private function getHeaders(): array
{
return [
'x-api-key' => $this->apiKey,
'content-type' => 'application/json',
'anthropic-version' => $this->modelVersion
];
}


/**
* Get the request body for the API request.
*
* @param string $model The model to use for the API request.
* @param int $maxTokens The maximum number of tokens to generate.
* @param array<mixed> $messages The messages to send to the API.
* @return array<string, mixed> The request body for the API request.
*/
private function getRequestBody(string $model, int $maxTokens, array $messages): array
{
return [
'model' => $model,
'max_tokens' => $maxTokens,
'messages' => $messages
];
}


}

0 comments on commit 5a97512

Please sign in to comment.