Skip to content

Commit

Permalink
Merge pull request #57 from miamibc/openai-gpt-4.5-turbo
Browse files Browse the repository at this point in the history
Openai gpt 4.5 turbo
  • Loading branch information
miamibc authored Nov 18, 2023
2 parents ceb2a8d + d3fa4a6 commit bb09b94
Show file tree
Hide file tree
Showing 4 changed files with 125 additions and 65 deletions.
64 changes: 64 additions & 0 deletions src/Helper/Strings.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
<?php

namespace Joker\Helper;

class Strings
{

/**
* @param \DateTime|string $datetime
* @param false $full short or long version
*
* @return string
*/
public static function timeElapsed( $datetime, $full = false)
{
$now = new \DateTime;
$ago = is_string($datetime) ? new \DateTime($datetime) : $datetime;
$diff = $now->diff($ago);

$diff->w = floor($diff->d / 7);
$diff->d -= $diff->w * 7;

$string = array(
'y' => 'year',
'm' => 'month',
'w' => 'week',
'd' => 'day',
'h' => 'hour',
'i' => 'minute',
's' => 'second',
);
foreach ($string as $k => &$v) {
if ($diff->$k) {
$v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : '');
} else {
unset($string[$k]);
}
}

if (!$full) $string = array_slice($string, 0, 1);
return $string ? implode(', ', $string) . ' ago' : 'just now';
}

/**
* Returns time difference in words
* @param $from
* @param $to
*
* @return string
*/
public static function diffTimeInWords($from,$to)
{
$date1 = new \DateTime("@$from");
$date2 = new \DateTime("@$to");
$interval = date_diff($date1, $date2);
$result = [];
foreach (['%y'=>'years', '%m' => 'months', '%d' => 'days', '%h' => 'hours', '%i' => 'minutes', '%s' => 'seconds'] as $key => $value)
if ($num = $interval->format($key))
$result[] = "$num $value";

return implode(" ", $result);
}

}
63 changes: 57 additions & 6 deletions src/Plugin/OpenAi.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,13 +31,22 @@

use GuzzleHttp\Client;
use Joker\Exception;
use Joker\Helper\Strings;
use Joker\Parser\Update;

class OpenAi extends Base
{

private $client;
private $context = [];
private $started;
private $stats = [
'requests_count' => 0,
'last_activity' => 0,
'prompt_tokens' => 0,
'completion_tokens' => 0,
'total_tokens' => 0,
];

protected $options = [
// joker options
Expand Down Expand Up @@ -71,10 +80,43 @@ public function init()
],
'timeout' => 20,
]);

$this->started = time();
}

public function onPublicText(Update $update)
{

$text = $update->message()->text();
// som commands
if ($text->trigger() == 'openai')
{
switch($text->token(1,1))
{
case 'parameters':
$update->replyMessage(implode(PHP_EOL, [
"model => " . $this->getOption("model"),
"temperature => " . $this->getOption("temperature"),
"max_tokens => " . $this->getOption("max_tokens"),
"top_p => " . $this->getOption("top_p"),
"frequency_penalty => " . $this->getOption("frequency_penalty"),
"presence_penalty => " . $this->getOption("presence_penalty"),
]));
return false;
case 'usage':
$update->replyMessage(implode(PHP_EOL, [
"started => " . Strings::timeElapsed(date('Y-m-d', $this->started)),
"last_activity => " . ($this->stats['last_activity'] ? Strings::diffTimeInWords($this->stats['last_activity'], time()).' ago' : 'Never'),
"requests_count => " . $this->stats['requests_count'],
"prompt_tokens => " . $this->stats['prompt_tokens'],
"completion_tokens => " . $this->stats['completion_tokens'],
"total_tokens => " . $this->stats['total_tokens'],
]));
return false;
}

}

// answer only to premium users
if ( $this->getOption('premium_only') && !$update->message()->from()->is_premium()) return;

Expand Down Expand Up @@ -118,7 +160,8 @@ public function onPublicText(Update $update)
// combine bio with messages in reverse order
$messages = array_merge($bio, array_reverse( $messages ));

$this->bot()->console( $messages );
// debug
$this->bot()->log( $messages );

// check size of request
$size = array_sum(array_map(function ($item){
Expand All @@ -128,24 +171,25 @@ public function onPublicText(Update $update)
{
$update->replyMessage("Многовато вопросов, сорян, закрываем лавочку :p");
// ideas:
// Многовато вопросов, сорян, закрываем лавочку :p"
// Многобукв! Автор выпей йаду :p
// Многовато вопросов, сорян, закрываем лавочку :p"
// Многобукв! Автор выпей йаду :p
return false;
}

$response = $this->client->post('/v1/chat/completions', ['json' => [
'model' => $this->getOption('model'),
'messages' => $messages,
'temperature' => $this->getOption('temperature', 0.5),
'max_tokens' => $this->getOption('max_tokens', 500),
'temperature' => $this->getOption('temperature'),
'max_tokens' => $this->getOption('max_tokens'),
'top_p' => $this->getOption('top_p'),
'frequency_penalty' => $this->getOption('frequency_penalty'),
'presence_penalty' => $this->getOption('presence_penalty'),
]])->getBody()->getContents();

$response = json_decode($response);

$update->bot()->console($response);
// debug
$update->bot()->log($response);

// no answer, nothing to do
if (!isset($response->choices[0]->message->content)) return;
Expand All @@ -158,6 +202,13 @@ public function onPublicText(Update $update)
$this->context[$update->message()->id()] = $update->message();
$this->context[$reply->id()] = $reply;

// save stats
$this->stats['requests_count']++;
$this->stats['last_activity'] = time();
$this->stats['prompt_tokens'] += $response->usage->prompt_tokens;
$this->stats['completion_tokens'] += $response->usage->completion_tokens;
$this->stats['total_tokens'] += $response->usage->total_tokens;

return false;

}
Expand Down
40 changes: 2 additions & 38 deletions src/Plugin/Twitch.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@

namespace Joker\Plugin;

use Joker\Helper\Strings;
use Joker\Parser\Update;

class Twitch extends Base
Expand Down Expand Up @@ -67,7 +68,7 @@ public function searchChannels( $query )
// title and a link
"<a href=\"https://www.twitch.tv/{$item['display_name']}\">" . trim($item['title']) . "</a>",
// started time
$item['started_at'] ? ' started '.self::time_elapsed($item['started_at']) : ''
$item['started_at'] ? ' started '. Strings::diffTimeInWords($item['started_at'], time()) . ' ago' : ''
]));
}

Expand Down Expand Up @@ -124,41 +125,4 @@ private function _request( string $method = 'GET', string $url = '/', array $par
return json_decode( $json, true );
}

/**
* @param $datetime
* @param false $full
*
* @return string
* @throws \Exception
*/
public static function time_elapsed($datetime, $full = false)
{
$now = new \DateTime;
$ago = new \DateTime($datetime);
$diff = $now->diff($ago);

$diff->w = floor($diff->d / 7);
$diff->d -= $diff->w * 7;

$string = array(
'y' => 'year',
'm' => 'month',
'w' => 'week',
'd' => 'day',
'h' => 'hour',
'i' => 'minute',
's' => 'second',
);
foreach ($string as $k => &$v) {
if ($diff->$k) {
$v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : '');
} else {
unset($string[$k]);
}
}

if (!$full) $string = array_slice($string, 0, 1);
return $string ? implode(', ', $string) . ' ago' : 'just now';
}

}
23 changes: 2 additions & 21 deletions src/Plugin/Uptime.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
namespace Joker\Plugin;

use DateTime;
use Joker\Helper\Strings;
use Joker\Parser\Update;

class Uptime extends Base
Expand All @@ -32,30 +33,10 @@ public function onPublicText( Update $update )
if ($update->message()->text()->trigger() === 'uptime')
{
$me = $update->bot()->getMe();
$uptime = self::diffTimeInWords($this->started, time() );
$uptime = Strings::diffTimeInWords($this->started, time() );
$update->answerMessage( "$me uptime is $uptime" );
return false;
}
}

/**
* Returns time difference in words
* @param $from
* @param $to
*
* @return string
*/
public static function diffTimeInWords($from,$to)
{
$date1 = new DateTime("@$from");
$date2 = new DateTime("@$to");
$interval = date_diff($date1, $date2);
$result = [];
foreach (['%y'=>'years', '%m' => 'months', '%d' => 'days', '%h' => 'hours', '%i' => 'minutes', '%s' => 'seconds'] as $key => $value)
if ($num = $interval->format($key))
$result[] = "$num $value";

return implode(" ", $result);
}

}

0 comments on commit bb09b94

Please sign in to comment.