1<?php
2
3namespace dokuwiki\plugin\aichat\Model\Ollama;
4
5use dokuwiki\plugin\aichat\Model\AbstractModel;
6
7/**
8 * Abstract Ollama Model
9 *
10 * This class provides a basic interface to the Ollama API
11 */
12abstract class AbstractOllama extends AbstractModel
13{
14    protected $apiurl = 'http://localhost:11434/api/';
15
16    /** @inheritdoc */
17    public function __construct(string $name, array $config)
18    {
19        parent::__construct($name, $config);
20        $this->apiurl = rtrim($config['ollama_baseurl'] ?? '', '/');
21        if ($this->apiurl === '') {
22            throw new \Exception('Ollama base URL not configured', 3001);
23        }
24    }
25
26    /** @inheritdoc */
27    function loadUnknownModelInfo(): array
28    {
29        $info = parent::loadUnknownModelInfo();
30
31        $url = $this->apiurl . 'show';
32
33        $result = $this->sendAPIRequest('POST', $url, ['model' => $this->modelName]);
34        foreach($result['model_info'] as $key => $value) {
35            if(str_ends_with($key, '.context_length')) {
36                $info['inputTokens'] = $value;
37            }
38            if(str_ends_with($key, '.embedding_length')) {
39                $info['dimensions'] = $value;
40            }
41
42        }
43
44        return $info;
45    }
46
47    /**
48     * Send a request to the Ollama API
49     *
50     * @param string $endpoint
51     * @param array $data Payload to send
52     * @return array API response
53     * @throws \Exception
54     */
55    protected function request($endpoint, $data)
56    {
57        $url = $this->apiurl . '/' . ltrim($endpoint, '/');
58        return $this->sendAPIRequest('POST', $url, $data);
59    }
60
61    /** @inheritdoc */
62    protected function parseAPIResponse($response)
63    {
64        if (isset($response['eval_count'])) {
65            $this->inputTokensUsed += $response['eval_count'];
66        }
67
68        if (isset($response['error'])) {
69            $error = is_array($response['error']) ? $response['error']['message'] : $response['error'];
70            throw new \Exception('Ollama API error: ' . $error, 3002);
71        }
72
73        return $response;
74    }
75}
76