Skip to content

Commit

Permalink
Bug fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
ddebowczyk committed Jun 22, 2024
1 parent 47f1cf1 commit 5c9a058
Show file tree
Hide file tree
Showing 59 changed files with 668 additions and 407 deletions.
9 changes: 6 additions & 3 deletions examples/03_Techniques/ChainOfSummaries/run.php
Original file line number Diff line number Diff line change
Expand Up @@ -50,11 +50,11 @@
/** Executive level summary of the project */
class Summary {
/** current summary iteration, not bigger than 3 */
public int $iteration;
public int $iteration = 0;
/** @var string[] 1-3 facts most relevant from executive perspective and missing from the summary (avoid technical details) */
public array $missingFacts;
public array $missingFacts = [];
/** denser summary in 1-3 sentences, which covers every fact from the previous summary plus the missing ones */
public string $expandedSummary;
public string $expandedSummary = '';
}

/** Increasingly denser, expanded summaries */
Expand All @@ -69,6 +69,9 @@ class ChainOfSummaries {
->request(
messages: $report,
responseModel: ChainOfSummaries::class,
prompt: 'Generate a denser summary based on the provided content.',
toolTitle: 'summarizer',
toolDescription: 'Generates a summary based on the provided content.',
options: [
'max_tokens' => 4096,
])
Expand Down
2 changes: 1 addition & 1 deletion examples/03_Techniques/TranslateUIFields/run.php
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ public function validate(object $dataObject): ValidationResult {

$transformedModel = (new Instructor)
->wiretap(fn($e)=>$e->print())
->appendValidator($validator)
->addValidator($validator)
->respond(
input: $sourceModel,
responseModel: get_class($sourceModel),
Expand Down
11 changes: 8 additions & 3 deletions examples/05_APISupport/LLMSupportOllama/run.php
Original file line number Diff line number Diff line change
Expand Up @@ -58,14 +58,19 @@ class User {
$user = $instructor->respond(
messages: "Jason (@jxnlco) is 25 years old and is the admin of this project. He likes playing football and reading books.",
responseModel: User::class,
model: 'llama2:latest',
prompt: 'Parse the user data to JSON, respond using following JSON Schema: <|json_schema|>',
examples: [[
'input' => 'Ive got email Frank - their developer. He asked to come back to him [email protected]. Btw, he plays on drums!',
'output' => ['age' => null, 'name' => 'Frank', 'role' => 'developer', 'hobbies' => ['playing drums'],],
'input' => 'Ive got email Frank - their developer. Asked to connect via Twitter @frankch. Btw, he plays on drums!',
'output' => ['name' => 'Frank', 'role' => 'developer', 'hobbies' => ['playing drums'], 'username' => 'frankch', 'age' => null],
],[
'input' => 'We have a meeting with John, our new user. He is 30 years old - check his profile: @jx90.',
'output' => ['name' => 'John', 'role' => 'admin', 'hobbies' => [], 'username' => 'jx90', 'age' => 30],
]],
model: 'qwen2',
mode: Mode::Json,
);


print("Completed response model:\n\n");

dump($user);
Expand Down
7 changes: 4 additions & 3 deletions src/ApiClient/Enums/ClientType.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,6 @@
use Cognesy\Instructor\Clients\OpenRouter\OpenRouterClient;
use Cognesy\Instructor\Clients\TogetherAI\TogetherAIClient;
use Cognesy\Instructor\Clients\TogetherAI\TogetherApiRequest;
use Exception;
use Tests\MockLLM;

enum ClientType : string
{
Expand Down Expand Up @@ -63,8 +61,11 @@ public static function fromString(string $type) : self {
};
}

public static function fromRequestClass(string $class)
public static function fromRequestClass(string|object $class)
{
if (is_object($class)) {
$class = get_class($class);
}
return match($class) {
AnthropicApiRequest::class => self::Anthropic,
AnyscaleApiRequest::class => self::Anyscale,
Expand Down
24 changes: 13 additions & 11 deletions src/ApiClient/Requests/ApiRequest.php
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ protected function defaultBody(): array {
$this->requestBody,
[
'model' => $this->model(),
'messages' => $this->clientType->toNativeMessages($this->withMetaSections()->messages()),
'messages' => $this->messages(),
'tools' => $this->tools(),
'tool_choice' => $this->getToolChoice(),
'response_format' => $this->getResponseFormat(),
Expand All @@ -105,41 +105,43 @@ protected function defaultBody(): array {
return $body;
}

protected function withMetaSections() : static {
$this->script->section('pre-input')->appendMessageIfEmpty([
protected function withMetaSections(Script $script) : Script {
$result = Script::fromScript($script);

$result->section('pre-input')->appendMessageIfEmpty([
'role' => 'user',
'content' => "INPUT:",
]);

$this->script->section('pre-prompt')->appendMessageIfEmpty([
$result->section('pre-prompt')->appendMessageIfEmpty([
'role' => 'user',
'content' => "TASK:",
]);

if ($this->script->section('examples')->notEmpty()) {
$this->script->section('pre-examples')->appendMessageIfEmpty([
if ($result->section('examples')->notEmpty()) {
$result->section('pre-examples')->appendMessageIfEmpty([
'role' => 'user',
'content' => "EXAMPLES:",
]);
}

$this->script->section('post-examples')->appendMessageIfEmpty([
$result->section('post-examples')->appendMessageIfEmpty([
'role' => 'user',
'content' => "RESPONSE:",
]);

if ($this->script->section('retries')->notEmpty()) {
$this->script->section('pre-retries')->appendMessageIfEmpty([
if ($result->section('retries')->notEmpty()) {
$result->section('pre-retries')->appendMessageIfEmpty([
'role' => 'user',
'content' => "FEEDBACK:",
]);
$this->script->section('post-retries')->appendMessageIfEmpty([
$result->section('post-retries')->appendMessageIfEmpty([
'role' => 'user',
'content' => "CORRECTED RESPONSE:",
]);
}

return $this;
return $result;
}

protected function getData(string $name, mixed $defaultValue) : mixed {
Expand Down
7 changes: 5 additions & 2 deletions src/ApiClient/Requests/Traits/HandlesRequestBody.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@

// API REQUEST - DEFAULT IMPLEMENTATION

use Cognesy\Instructor\ApiClient\Enums\ClientType;

trait HandlesRequestBody
{
protected function model() : string {
Expand All @@ -14,7 +16,8 @@ public function messages(): array {
return $this->messages;
}

return $this->script
return $this
->withMetaSections($this->script)
->withContext($this->scriptContext)
->select([
'system',
Expand All @@ -23,7 +26,7 @@ public function messages(): array {
'pre-examples', 'examples', 'post-examples',
'pre-retries', 'retries', 'post-retries'
])
->toArray();
->toNativeArray(ClientType::fromRequestClass($this), mergePerRole: true);
}

public function tools(): array {
Expand Down
2 changes: 1 addition & 1 deletion src/Clients/Anthropic/AnthropicApiRequest.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ protected function defaultBody(): array {
[
'model' => $this->model(),
'system' => $this->system(),
'messages' => $this->clientType->toNativeMessages(Messages::mergedPerRole($this->withMetaSections()->messages())),
'messages' => $this->messages(),
'tools' => $this->tools(),
'tool_choice' => $this->getToolChoice(),
'max_tokens' => $this->maxTokens,
Expand Down
9 changes: 6 additions & 3 deletions src/Clients/Anthropic/Traits/HandlesRequestBody.php
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
<?php

namespace Cognesy\Instructor\Clients\Anthropic\Traits;

use Cognesy\Instructor\ApiClient\Enums\ClientType;
use Cognesy\Instructor\Enums\Mode;

// ANTHROPIC API

trait HandlesRequestBody {
public function messages(): array {
if ($this->noScript()) {
Expand All @@ -14,7 +16,8 @@ public function messages(): array {
unset($this->scriptContext['json_schema']);
}

return $this->script
return $this
->withMetaSections($this->script)
->withContext($this->scriptContext)
->select([
'system',
Expand All @@ -23,7 +26,7 @@ public function messages(): array {
'pre-examples', 'examples', 'post-examples',
'pre-retries', 'retries', 'post-retries'
])
->toArray();
->toNativeArray(ClientType::fromRequestClass($this), mergePerRole: true);
}

public function system(): string {
Expand Down
3 changes: 1 addition & 2 deletions src/Clients/Azure/AzureApiRequest.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,11 @@
use Cognesy\Instructor\ApiClient\RequestConfig\ApiRequestConfig;
use Cognesy\Instructor\ApiClient\Requests\ApiRequest;
use Cognesy\Instructor\ApiClient\Requests\Traits\HandlesResponse;
use Cognesy\Instructor\ApiClient\Requests\Traits\HandlesRequestBody;
use Saloon\Enums\Method;

class AzureApiRequest extends ApiRequest
{
use HandlesRequestBody;
use Traits\HandlesRequestBody;
use HandlesResponse;

public function __construct(
Expand Down
48 changes: 48 additions & 0 deletions src/Clients/Azure/Traits/HandlesRequestBody.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
<?php
namespace Cognesy\Instructor\Clients\Azure\Traits;

use Cognesy\Instructor\Enums\Mode;

trait HandlesRequestBody
{
public function messages(): array {
if ($this->noScript()) {
return $this->messages;
}

if($this->mode->is(Mode::Tools)) {
unset($this->scriptContext['json_schema']);
}

return $this
->withMetaSections($this->script)
->withContext($this->scriptContext)
->select([
'system',
'pre-input', 'messages', 'input', 'post-input',
'pre-prompt', 'prompt', 'post-prompt',
'pre-examples', 'examples', 'post-examples',
'pre-retries', 'retries', 'post-retries'
])
->toArray();
}

public function tools(): array {
return $this->tools;
}

public function getToolChoice(): string|array {
if (empty($this->tools)) {
return '';
}
return $this->toolChoice ?: 'auto';
}

protected function getResponseSchema() : array {
return $this->responseFormat['schema'] ?? [];
}

protected function getResponseFormat(): array {
return $this->responseFormat['format'] ?? [];
}
}
4 changes: 2 additions & 2 deletions src/Clients/Cohere/CohereApiRequest.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@ protected function defaultBody(): array {
[
'model' => $this->model(),
'preamble' => $this->preamble(),
'chat_history' => $this->clientType->toNativeMessages($this->chatHistory()),
'message' => Messages::asString($this->withMetaSections()->messages()),
'chat_history' => $this->chatHistory(),
'message' => Messages::asString($this->messages()),
'tools' => $this->tools(),
],
)
Expand Down
11 changes: 8 additions & 3 deletions src/Clients/Cohere/Traits/HandlesRequestBody.php
Original file line number Diff line number Diff line change
@@ -1,14 +1,19 @@
<?php
namespace Cognesy\Instructor\Clients\Cohere\Traits;

use Cognesy\Instructor\ApiClient\Enums\ClientType;

// COHERE API

trait HandlesRequestBody
{
public function messages(): array {
if ($this->noScript()) {
return $this->messages;
}

return $this->script
return $this
->withMetaSections($this->script)
->withContext($this->scriptContext)
->select([
'system',
Expand All @@ -17,7 +22,7 @@ public function messages(): array {
'pre-examples', 'examples', 'post-examples',
'pre-retries', 'retries', 'post-retries'
])
->toArray();
->toNativeArray(ClientType::fromRequestClass($this), mergePerRole: true);
}

public function preamble(): string {
Expand All @@ -29,7 +34,7 @@ public function preamble(): string {
}

public function chatHistory(): array {
return [];
return $this->clientType->toNativeMessages([]);
// return $this->script
// ->withContext($this->scriptContext)
// ->select(['messages', 'data-ack', 'prompt', 'examples'])
Expand Down
2 changes: 1 addition & 1 deletion src/Clients/Gemini/GeminiApiRequest.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ protected function defaultBody(): array {
$body = array_filter(
[
'systemInstruction' => empty($this->system()) ? [] : ['parts' => ['text' => Messages::asString($this->system())]],
'contents' => $this->clientType->toNativeMessages($this->withMetaSections()->messages()),
'contents' => $this->messages(),
'generationConfig' => $this->options(),
],
);
Expand Down
7 changes: 5 additions & 2 deletions src/Clients/Gemini/Traits/HandlesRequestBody.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@

// GEMINI API

use Cognesy\Instructor\ApiClient\Enums\ClientType;

trait HandlesRequestBody
{
protected function system() : array {
Expand All @@ -21,15 +23,16 @@ public function messages(): array {
return $this->messages;
}

return $this->script
return $this
->withMetaSections($this->script)
->withContext($this->scriptContext)
->select([
'pre-input', 'messages', 'input', 'post-input',
'pre-prompt', 'prompt', 'post-prompt',
'pre-examples', 'examples', 'post-examples',
'pre-retries', 'retries', 'post-retries'
])
->toArray();
->toNativeArray(ClientType::fromRequestClass($this), mergePerRole: true);
}

public function tools(): array {
Expand Down
3 changes: 2 additions & 1 deletion src/Clients/Groq/GroqApiRequest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,11 @@
namespace Cognesy\Instructor\Clients\Groq;

use Cognesy\Instructor\ApiClient\Requests\ApiRequest;
use Cognesy\Instructor\ApiClient\Requests\Traits\HandlesRequestBody;
use Cognesy\Instructor\ApiClient\Requests\Traits\HandlesResponse;

class GroqApiRequest extends ApiRequest
{
use Traits\HandlesRequestBody;
use HandlesRequestBody;
use HandlesResponse;
}
3 changes: 2 additions & 1 deletion src/Clients/Groq/Traits/HandlesRequestBody.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@ public function messages(): array {
return $this->messages;
}

return $this->script
return $this
->withMetaSections($this->script)
->withContext($this->scriptContext)
->select([
'system',
Expand Down
2 changes: 1 addition & 1 deletion src/Clients/Ollama/OllamaApiRequest.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ protected function defaultBody(): array {
$this->requestBody,
[
'model' => $this->model(),
'messages' => $this->clientType->toNativeMessages($this->withMetaSections()->messages()),
'messages' => $this->messages(),
'response_format' => $this->getResponseFormat(),
// TODO: Ollama does not support tool calling - add when supported
//'tools' => $this->tools(),
Expand Down
Loading

0 comments on commit 5c9a058

Please sign in to comment.