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

76 lines
1.7 KiB
PHP
Raw 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;
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('请输入问题');
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();
}
}
echo "\n";
}
}
}