amber-laravel/app/Console/Commands/TestLLM.php

86 lines
2.1 KiB
PHP
Raw Permalink Normal View History

2024-07-24 17:16:41 +00:00
<?php
namespace App\Console\Commands;
use App\LLM\Qwen;
use App\Models\Tool;
use App\Repositories\LLM\ChatEnum;
use App\Repositories\LLM\History;
use App\Repositories\LLM\HumanMessage;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Console\Command;
2024-07-24 18:53:47 +00:00
use Illuminate\Support\Facades\Storage;
2024-07-24 17:16:41 +00:00
class TestLLM extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'app:testllm';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Command description';
/**
* Execute the console command.
2024-07-24 17:26:40 +00:00
*
2024-07-24 17:16:41 +00:00
* @throws GuzzleException
*/
public function handle()
{
$llm = new Qwen();
$history = new History();
$tool = Tool::get();
$llm->setTools($tool);
$llm->setHistory($history);
while (true) {
2024-07-24 17:26:40 +00:00
// var_dump($history->getMessages());
2024-07-24 17:16:41 +00:00
$q = $this->ask('请输入问题');
2024-07-24 18:53:47 +00:00
if ($q == 'q') {
Storage::put('chat.json', json_encode($history->getMessages(), JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
return 0;
}
2024-07-24 17:16:41 +00:00
if (empty($q)) {
2024-07-24 17:26:40 +00:00
$q = '北京天气';
2024-07-24 17:16:41 +00:00
}
$history->addMessage(new HumanMessage($q));
$s = $llm->streamResponse();
// 循环输出
foreach ($s as $item) {
if ($item->role == ChatEnum::Tool) {
if ($item->processing) {
2024-07-24 17:26:40 +00:00
$this->info('正在执行: '.$item->content);
2024-07-24 17:16:41 +00:00
echo "\n";
} else {
2024-07-24 17:26:40 +00:00
$this->info('执行结果: '.$item->content);
2024-07-24 17:16:41 +00:00
}
2024-07-24 17:26:40 +00:00
} elseif ($item->role == ChatEnum::AssistantChunk) {
2024-07-24 17:16:41 +00:00
echo $item->getLastAppend();
2024-07-24 18:53:47 +00:00
} elseif ($item->role == ChatEnum::Assistant) {
echo "\n完整输出: ".$item->content;
2024-07-24 17:16:41 +00:00
}
2024-07-24 18:53:47 +00:00
2024-07-24 17:16:41 +00:00
}
echo "\n";
}
}
}