xref: /plugin/aichat/cli/simulate.php (revision 87090e4beaf7085cdc8f751dac29ba2d15611b8d)
1c2b7a1f7SAndreas Gohr<?php
2c2b7a1f7SAndreas Gohr
30de7e020SAndreas Gohruse dokuwiki\plugin\aichat\AbstractCLI;
4c2b7a1f7SAndreas Gohruse splitbrain\phpcli\Colors;
5c2b7a1f7SAndreas Gohruse splitbrain\phpcli\Options;
6c2b7a1f7SAndreas Gohr
7c2b7a1f7SAndreas Gohr/**
8c2b7a1f7SAndreas Gohr * DokuWiki Plugin aichat (CLI Component)
9c2b7a1f7SAndreas Gohr *
10c2b7a1f7SAndreas Gohr * @license GPL 2 http://www.gnu.org/licenses/gpl-2.0.html
11c2b7a1f7SAndreas Gohr * @author  Andreas Gohr <gohr@cosmocode.de>
12c2b7a1f7SAndreas Gohr */
130de7e020SAndreas Gohrclass cli_plugin_aichat_simulate extends AbstractCLI
14c2b7a1f7SAndreas Gohr{
15c9f3c70cSAndreas Gohr    /** @inheritDoc */
16c9f3c70cSAndreas Gohr    public function getInfo()
17c9f3c70cSAndreas Gohr    {
18c9f3c70cSAndreas Gohr        $info = parent::getInfo();
19c9f3c70cSAndreas Gohr        $info['desc'] = 'Run a prepared chat session against multiple LLM models';
20c9f3c70cSAndreas Gohr        return $info;
21c9f3c70cSAndreas Gohr    }
22c2b7a1f7SAndreas Gohr
23c2b7a1f7SAndreas Gohr    /** @inheritDoc */
24c2b7a1f7SAndreas Gohr    protected function setup(Options $options)
25c2b7a1f7SAndreas Gohr    {
260de7e020SAndreas Gohr        parent::setup($options);
270de7e020SAndreas Gohr
280de7e020SAndreas Gohr        $options->setHelp('Run a prepared chat session against multiple models');
29c2b7a1f7SAndreas Gohr        $options->registerArgument('input', 'A file with the chat questions. Each question separated by two newlines');
30c2b7a1f7SAndreas Gohr        $options->registerArgument('output', 'Where to write the result CSV to');
31c2b7a1f7SAndreas Gohr
32c2b7a1f7SAndreas Gohr        $options->registerOption(
33c2b7a1f7SAndreas Gohr            'filter',
34c2b7a1f7SAndreas Gohr            'Use only models matching this case-insensitive regex (no delimiters)',
35c2b7a1f7SAndreas Gohr            'f',
36c2b7a1f7SAndreas Gohr            'regex'
37c2b7a1f7SAndreas Gohr        );
38c2b7a1f7SAndreas Gohr    }
39c2b7a1f7SAndreas Gohr
40c2b7a1f7SAndreas Gohr    /** @inheritDoc */
41c2b7a1f7SAndreas Gohr    protected function main(Options $options)
42c2b7a1f7SAndreas Gohr    {
430de7e020SAndreas Gohr        parent::main($options);
44c2b7a1f7SAndreas Gohr
45c2b7a1f7SAndreas Gohr        [$input, $output] = $options->getArgs();
46c2b7a1f7SAndreas Gohr        $questions = $this->readInputFile($input);
470de7e020SAndreas Gohr        $outFH = @fopen($output, 'w');
480de7e020SAndreas Gohr        if (!$outFH) throw new \Exception("Could not open $output for writing");
49c2b7a1f7SAndreas Gohr
50c2b7a1f7SAndreas Gohr        $models = $this->helper->factory->getModels(true, 'chat');
51c2b7a1f7SAndreas Gohr
52c2b7a1f7SAndreas Gohr        $results = [];
53c2b7a1f7SAndreas Gohr        foreach ($models as $name => $info) {
54c2b7a1f7SAndreas Gohr            if ($options->getOpt('filter') && !preg_match('/' . $options->getOpt('filter') . '/i', $name)) {
55c2b7a1f7SAndreas Gohr                continue;
56c2b7a1f7SAndreas Gohr            }
57c2b7a1f7SAndreas Gohr            $this->success("Running on $name...");
58c2b7a1f7SAndreas Gohr            $results[$name] = $this->simulate($questions, $info);
59c2b7a1f7SAndreas Gohr        }
60c2b7a1f7SAndreas Gohr
61c2b7a1f7SAndreas Gohr        foreach ($this->records2rows($results) as $row) {
620de7e020SAndreas Gohr            fputcsv($outFH, $row);
63c2b7a1f7SAndreas Gohr        }
640de7e020SAndreas Gohr        fclose($outFH);
65c2b7a1f7SAndreas Gohr        $this->success("Results written to $output");
66c2b7a1f7SAndreas Gohr    }
67c2b7a1f7SAndreas Gohr
68c2b7a1f7SAndreas Gohr    protected function simulate($questions, $model)
69c2b7a1f7SAndreas Gohr    {
70c2b7a1f7SAndreas Gohr        // override models
71c2b7a1f7SAndreas Gohr        $this->helper->factory->chatModel = $model['instance'];
72c2b7a1f7SAndreas Gohr        $this->helper->factory->rephraseModel = clone $model['instance'];
73c2b7a1f7SAndreas Gohr
74c2b7a1f7SAndreas Gohr        $records = [];
75c2b7a1f7SAndreas Gohr
76c2b7a1f7SAndreas Gohr        $history = [];
77c2b7a1f7SAndreas Gohr        foreach ($questions as $q) {
78c2b7a1f7SAndreas Gohr            $this->helper->getChatModel()->resetUsageStats();
79c2b7a1f7SAndreas Gohr            $this->helper->getRephraseModel()->resetUsageStats();
80c2b7a1f7SAndreas Gohr            $this->helper->getEmbeddingModel()->resetUsageStats();
81c2b7a1f7SAndreas Gohr
82c2b7a1f7SAndreas Gohr            $this->colors->ptln($q, Colors::C_LIGHTPURPLE);
83ab1f8ddeSAndreas Gohr            try {
84c2b7a1f7SAndreas Gohr                $result = $this->helper->askChatQuestion($q, $history);
85c2b7a1f7SAndreas Gohr                $history[] = [$result['question'], $result['answer']];
860de7e020SAndreas Gohr                $this->colors->ptln($result['question'], Colors::C_LIGHTBLUE);
87ab1f8ddeSAndreas Gohr            } catch (Exception $e) {
88ab1f8ddeSAndreas Gohr                $this->error($e->getMessage());
89ab1f8ddeSAndreas Gohr                $this->debug($e->getTraceAsString());
90ab1f8ddeSAndreas Gohr                $result = ['question' => $q, 'answer' => "ERROR\n" . $e->getMessage(), 'sources' => []];
91ab1f8ddeSAndreas Gohr            }
92c2b7a1f7SAndreas Gohr
93c2b7a1f7SAndreas Gohr            $record = [
94c2b7a1f7SAndreas Gohr                'question' => $q,
95*87090e4bSAndreas Gohr                'rephrased' => $result['contextQuestion'],
96c2b7a1f7SAndreas Gohr                'answer' => $result['answer'],
972071dcedSAndreas Gohr                'source.list' => implode("\n", $result['sources']),
98c2b7a1f7SAndreas Gohr                'source.time' => $this->helper->getEmbeddings()->timeSpent,
99c2b7a1f7SAndreas Gohr                ...$this->flattenStats('stats.embedding', $this->helper->getEmbeddingModel()->getUsageStats()),
100c2b7a1f7SAndreas Gohr                ...$this->flattenStats('stats.rephrase', $this->helper->getRephraseModel()->getUsageStats()),
101c2b7a1f7SAndreas Gohr                ...$this->flattenStats('stats.chat', $this->helper->getChatModel()->getUsageStats()),
102c2b7a1f7SAndreas Gohr            ];
103c2b7a1f7SAndreas Gohr            $records[] = $record;
104c2b7a1f7SAndreas Gohr            $this->colors->ptln($result['answer'], Colors::C_LIGHTCYAN);
105c2b7a1f7SAndreas Gohr        }
106c2b7a1f7SAndreas Gohr
107c2b7a1f7SAndreas Gohr        return $records;
108c2b7a1f7SAndreas Gohr    }
109c2b7a1f7SAndreas Gohr
110c2b7a1f7SAndreas Gohr    /**
111c2b7a1f7SAndreas Gohr     * Reformat the result array into a CSV friendly array
112c2b7a1f7SAndreas Gohr     */
113c2b7a1f7SAndreas Gohr    protected function records2rows(array $result): array
114c2b7a1f7SAndreas Gohr    {
115c2b7a1f7SAndreas Gohr        $rowkeys = [
116c2b7a1f7SAndreas Gohr            'question' => ['question', 'stats.embedding.cost', 'stats.embedding.time'],
117c2b7a1f7SAndreas Gohr            'rephrased' => ['rephrased', 'stats.rephrase.cost', 'stats.rephrase.time'],
118c2b7a1f7SAndreas Gohr            'sources' => ['source.list', '', 'source.time'],
119c2b7a1f7SAndreas Gohr            'answer' => ['answer', 'stats.chat.cost', 'stats.chat.time'],
120c2b7a1f7SAndreas Gohr        ];
121c2b7a1f7SAndreas Gohr
122c2b7a1f7SAndreas Gohr        $models = array_keys($result);
123c2b7a1f7SAndreas Gohr        $numberOfRecords = count($result[$models[0]]);
124c2b7a1f7SAndreas Gohr        $rows = [];
125c2b7a1f7SAndreas Gohr
126c2b7a1f7SAndreas Gohr        // write headers
127c2b7a1f7SAndreas Gohr        $row = [];
128c2b7a1f7SAndreas Gohr        $row[] = 'type';
129c2b7a1f7SAndreas Gohr        foreach ($models as $model) {
130c2b7a1f7SAndreas Gohr            $row[] = $model;
131c2b7a1f7SAndreas Gohr            $row[] = 'Cost USD';
132c2b7a1f7SAndreas Gohr            $row[] = 'Time s';
133c2b7a1f7SAndreas Gohr        }
134c2b7a1f7SAndreas Gohr        $rows[] = $row;
135c2b7a1f7SAndreas Gohr
136c2b7a1f7SAndreas Gohr        // write rows
137c2b7a1f7SAndreas Gohr        for ($i = 0; $i < $numberOfRecords; $i++) {
138c2b7a1f7SAndreas Gohr            foreach ($rowkeys as $type => $keys) {
139c2b7a1f7SAndreas Gohr                $row = [];
140c2b7a1f7SAndreas Gohr                $row[] = $type;
141c2b7a1f7SAndreas Gohr                foreach ($models as $model) {
142c2b7a1f7SAndreas Gohr                    foreach ($keys as $key) {
143c2b7a1f7SAndreas Gohr                        if ($key) {
144c2b7a1f7SAndreas Gohr                            $row[] = $result[$model][$i][$key];
145c2b7a1f7SAndreas Gohr                        } else {
146c2b7a1f7SAndreas Gohr                            $row[] = '';
147c2b7a1f7SAndreas Gohr                        }
148c2b7a1f7SAndreas Gohr                    }
149c2b7a1f7SAndreas Gohr                }
150c2b7a1f7SAndreas Gohr                $rows[] = $row;
151c2b7a1f7SAndreas Gohr            }
152c2b7a1f7SAndreas Gohr        }
153c2b7a1f7SAndreas Gohr
154c2b7a1f7SAndreas Gohr
155c2b7a1f7SAndreas Gohr        return $rows;
156c2b7a1f7SAndreas Gohr    }
157c2b7a1f7SAndreas Gohr
158c2b7a1f7SAndreas Gohr
159c2b7a1f7SAndreas Gohr    /**
160c2b7a1f7SAndreas Gohr     * Prefix each key in the given stats array to be merged with a larger array
161c2b7a1f7SAndreas Gohr     *
162c2b7a1f7SAndreas Gohr     * @param string $prefix
163c2b7a1f7SAndreas Gohr     * @param array $stats
164c2b7a1f7SAndreas Gohr     * @return array
165c2b7a1f7SAndreas Gohr     */
1662071dcedSAndreas Gohr    protected function flattenStats(string $prefix, array $stats)
1672071dcedSAndreas Gohr    {
168c2b7a1f7SAndreas Gohr        $result = [];
169c2b7a1f7SAndreas Gohr        foreach ($stats as $key => $value) {
170c2b7a1f7SAndreas Gohr            $result["$prefix.$key"] = $value;
171c2b7a1f7SAndreas Gohr        }
172c2b7a1f7SAndreas Gohr        return $result;
173c2b7a1f7SAndreas Gohr    }
174c2b7a1f7SAndreas Gohr
175c2b7a1f7SAndreas Gohr    /**
176c2b7a1f7SAndreas Gohr     * @param string $file
177c2b7a1f7SAndreas Gohr     * @return array
178c2b7a1f7SAndreas Gohr     * @throws Exception
179c2b7a1f7SAndreas Gohr     */
180c2b7a1f7SAndreas Gohr    protected function readInputFile(string $file): array
181c2b7a1f7SAndreas Gohr    {
182c2b7a1f7SAndreas Gohr        if (!file_exists($file)) throw new \Exception("File not found: $file");
183c2b7a1f7SAndreas Gohr        $lines = file_get_contents($file);
184c2b7a1f7SAndreas Gohr        $questions = explode("\n\n", $lines);
185c2b7a1f7SAndreas Gohr        $questions = array_map('trim', $questions);
186c2b7a1f7SAndreas Gohr        return $questions;
187c2b7a1f7SAndreas Gohr    }
188c2b7a1f7SAndreas Gohr}
189