Proyectos de Subversion Moodle

Rev

| Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1441 ariadna 1
<?php
2
// This file is part of Moodle - http://moodle.org/
3
//
4
// Moodle is free software: you can redistribute it and/or modify
5
// it under the terms of the GNU General Public License as published by
6
// the Free Software Foundation, either version 3 of the License, or
7
// (at your option) any later version.
8
//
9
// Moodle is distributed in the hope that it will be useful,
10
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
// GNU General Public License for more details.
13
//
14
// You should have received a copy of the GNU General Public License
15
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
16
 
17
namespace aiprovider_ollama;
18
 
19
use core\http_client;
20
use core_ai\process_base;
21
use GuzzleHttp\Exception\RequestException;
22
use GuzzleHttp\Psr7\Uri;
23
use GuzzleHttp\RequestOptions;
24
use Psr\Http\Message\RequestInterface;
25
use Psr\Http\Message\ResponseInterface;
26
use Psr\Http\Message\UriInterface;
27
 
28
/**
29
 * Class process text generation.
30
 *
31
 * @package    aiprovider_ollama
32
 * @copyright  2024 Matt Porritt <matt.porritt@moodle.com>
33
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
34
 */
35
abstract class abstract_processor extends process_base {
36
    /**
37
     * Get the endpoint URI.
38
     *
39
     * @return UriInterface
40
     */
41
    protected function get_endpoint(): UriInterface {
42
        $url = rtrim($this->provider->config['endpoint'], '/')
43
            . '/api/generate';
44
 
45
        return new Uri($url);
46
    }
47
 
48
    /**
49
     * Get the name of the model to use.
50
     *
51
     * @return string
52
     */
53
    protected function get_model(): string {
54
        return $this->provider->actionconfig[$this->action::class]['settings']['model'];
55
    }
56
 
57
    /**
58
     * Get the model settings.
59
     *
60
     * @return array
61
     */
62
    protected function get_model_settings(): array {
63
        $settings = $this->provider->actionconfig[$this->action::class]['settings'];
64
        if (!empty($settings['modelextraparams'])) {
65
            // Custom model settings.
66
            $params = json_decode($settings['modelextraparams'], true);
67
            foreach ($params as $key => $param) {
68
                $settings[$key] = $param;
69
            }
70
        }
71
 
72
        // Unset unnecessary settings.
73
        unset(
74
            $settings['model'],
75
            $settings['systeminstruction'],
76
            $settings['providerid'],
77
            $settings['modelextraparams'],
78
        );
79
        return $settings;
80
    }
81
 
82
    /**
83
     * Get the system instructions.
84
     *
85
     * @return string
86
     */
87
    protected function get_system_instruction(): string {
88
        return $this->action::get_system_instruction();
89
    }
90
 
91
    /**
92
     * Create the request object to send to the Ollama API.
93
     * This object contains all the required parameters for the request.
94
     *
95
     * @param string $userid The user id.
96
     * @return RequestInterface The request object to send to the Ollama API.
97
     */
98
    abstract protected function create_request_object(string $userid): RequestInterface;
99
 
100
    /**
101
     * Handle a successful response from the external AI api.
102
     *
103
     * @param ResponseInterface $response The response object.
104
     * @return array The response.
105
     */
106
    abstract protected function handle_api_success(ResponseInterface $response): array;
107
 
108
    #[\Override]
109
    protected function query_ai_api(): array {
110
        $request = $this->create_request_object($this->provider->generate_userid($this->action->get_configuration('userid')));
111
        $request = $this->provider->add_authentication_headers($request);
112
 
113
        $client = \core\di::get(http_client::class);
114
        try {
115
            // Call the external AI service.
116
            $response = $client->send($request, [
117
                'base_uri' => $this->get_endpoint(),
118
                RequestOptions::HTTP_ERRORS => false,
119
            ]);
120
        } catch (RequestException $e) {
121
            // Handle any exceptions.
122
            return [
123
                'success' => false,
124
                'errorcode' => $e->getCode(),
125
                'errormessage' => $e->getMessage(),
126
            ];
127
        }
128
 
129
        // Double-check the response codes, in case of a non 200 that didn't throw an error.
130
        $status = $response->getStatusCode();
131
        if ($status === 200) {
132
            return $this->handle_api_success($response);
133
        } else {
134
            return $this->handle_api_error($response);
135
        }
136
    }
137
 
138
    /**
139
     * Handle an error from the external AI api.
140
     *
141
     * @param ResponseInterface $response The response object.
142
     * @return array The error response.
143
     */
144
    protected function handle_api_error(ResponseInterface $response): array {
145
        $responsearr = [
146
            'success' => false,
147
            'errorcode' => $response->getStatusCode(),
148
        ];
149
 
150
        $status = $response->getStatusCode();
151
        if ($status >= 500 && $status < 600) {
152
            $responsearr['errormessage'] = $response->getReasonPhrase();
153
        } else {
154
            $bodyobj = json_decode($response->getBody()->getContents());
155
            $responsearr['errormessage'] = $bodyobj->error->message;
156
        }
157
 
158
        return $responsearr;
159
    }
160
}