ovos-openai-plugin 2.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- ovos_openai_plugin-2.0.0.dist-info/LICENSE +203 -0
- ovos_openai_plugin-2.0.0.dist-info/METADATA +92 -0
- ovos_openai_plugin-2.0.0.dist-info/RECORD +12 -0
- ovos_openai_plugin-2.0.0.dist-info/WHEEL +5 -0
- ovos_openai_plugin-2.0.0.dist-info/entry_points.txt +11 -0
- ovos_openai_plugin-2.0.0.dist-info/top_level.txt +1 -0
- ovos_openai_plugin-2.0.0.dist-info/zip-safe +1 -0
- ovos_solver_openai_persona/__init__.py +66 -0
- ovos_solver_openai_persona/dialog_transformers.py +27 -0
- ovos_solver_openai_persona/engines.py +283 -0
- ovos_solver_openai_persona/summarizer.py +41 -0
- ovos_solver_openai_persona/version.py +6 -0
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
|
203
|
+
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
Metadata-Version: 2.1
|
|
2
|
+
Name: ovos-openai-plugin
|
|
3
|
+
Version: 2.0.0
|
|
4
|
+
Summary: A question solver plugin for ovos
|
|
5
|
+
Home-page: https://github.com/OpenVoiceOS/ovos-solver-plugin-openai-persona
|
|
6
|
+
Author: jarbasai
|
|
7
|
+
Author-email: jarbasai@mailfence.com
|
|
8
|
+
License: MIT
|
|
9
|
+
Keywords: ovos plugin utterance fallback query
|
|
10
|
+
Description-Content-Type: text/markdown
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Requires-Dist: requests
|
|
13
|
+
Requires-Dist: ovos-plugin-manager<1.0.0,>=0.0.26
|
|
14
|
+
|
|
15
|
+
# <img src='https://raw.githack.com/FortAwesome/Font-Awesome/master/svgs/solid/robot.svg' card_color='#40DBB0' width='50' height='50' style='vertical-align:bottom'/> OVOS OpenAI Plugin
|
|
16
|
+
|
|
17
|
+
Leverages [OpenAI Completions API](https://platform.openai.com/docs/api-reference/completions/create) to provide the following ovos plugins:
|
|
18
|
+
- `ovos-solver-openai-plugin` for usage with [ovos-persona](https://github.com/OpenVoiceOS/ovos-persona) (and in older ovos releases with [ovos-skill-fallback-chatgpt]())
|
|
19
|
+
- `ovos-dialog-transformer-openai-plugin` to rewrite OVOS dialogs just before TTS executes in [ovos-audio](https://github.com/OpenVoiceOS/ovos-audio)
|
|
20
|
+
- `ovos-summarizer-openai-plugin` to summarize text, not used directly but provided for consumption by other plugins/skills
|
|
21
|
+
|
|
22
|
+
## Install
|
|
23
|
+
|
|
24
|
+
`pip install ovos-openai-plugin`
|
|
25
|
+
|
|
26
|
+
## Persona Usage
|
|
27
|
+
|
|
28
|
+
To create your own persona using a OpenAI compatible server create a .json in `~/.config/ovos_persona/llm.json`:
|
|
29
|
+
```json
|
|
30
|
+
{
|
|
31
|
+
"name": "My Local LLM",
|
|
32
|
+
"solvers": [
|
|
33
|
+
"ovos-solver-openai-plugin"
|
|
34
|
+
],
|
|
35
|
+
"ovos-openai-plugin": {
|
|
36
|
+
"api_url": "https://llama.smartgic.io/v1",
|
|
37
|
+
"key": "sk-xxxx",
|
|
38
|
+
"persona": "helpful, creative, clever, and very friendly."
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
Then say "Chat with {name_from_json}" to enable it, more details can be found in [ovos-persona](https://github.com/OpenVoiceOS/ovos-persona) README
|
|
44
|
+
|
|
45
|
+
This plugins also provides a default "Remote LLama" demo persona, it points to a public server hosted by @goldyfruit.
|
|
46
|
+
|
|
47
|
+
## Dialog Transformer
|
|
48
|
+
|
|
49
|
+
you can rewrite text dynamically based on specific personas, such as simplifying explanations or mimicking a specific tone.
|
|
50
|
+
|
|
51
|
+
#### Example Usage:
|
|
52
|
+
- **Persona:** `"rewrite the text as if you were explaining it to a 5-year-old"`
|
|
53
|
+
- **Input:** `"Quantum mechanics is a branch of physics that describes the behavior of particles at the smallest scales."`
|
|
54
|
+
- **Output:** `"Quantum mechanics is like a special kind of science that helps us understand really tiny things."`
|
|
55
|
+
|
|
56
|
+
Examples of `persona` Values:
|
|
57
|
+
- `"rewrite the text as if it was an angry old man speaking"`
|
|
58
|
+
- `"Add more 'dude'ness to it"`
|
|
59
|
+
- `"Explain it like you're teaching a child"`
|
|
60
|
+
|
|
61
|
+
To enable this plugin, add the following to your `mycroft.conf`:
|
|
62
|
+
|
|
63
|
+
```json
|
|
64
|
+
"dialog_transformers": {
|
|
65
|
+
"ovos-dialog-transformer-openai-plugin": {
|
|
66
|
+
"rewrite_prompt": "rewrite the text as if you were explaining it to a 5-year-old"
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
## Direct Usage
|
|
72
|
+
|
|
73
|
+
```python
|
|
74
|
+
from ovos_solver_openai_persona import OpenAIPersonaSolver
|
|
75
|
+
|
|
76
|
+
bot = OpenAIPersonaSolver({"key": "sk-XXX",
|
|
77
|
+
"persona": "helpful, creative, clever, and very friendly"})
|
|
78
|
+
print(bot.get_spoken_answer("describe quantum mechanics in simple terms"))
|
|
79
|
+
# Quantum mechanics is a branch of physics that deals with the behavior of particles on a very small scale, such as atoms and subatomic particles. It explores the idea that particles can exist in multiple states at once and that their behavior is not predictable in the traditional sense.
|
|
80
|
+
print(bot.spoken_answer("Quem encontrou o caminho maritimo para o Brazil", lang="pt-pt"))
|
|
81
|
+
# Explorador português Pedro Álvares Cabral é creditado com a descoberta do Brasil em 1500
|
|
82
|
+
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
## Remote Persona / Proxies
|
|
86
|
+
|
|
87
|
+
You can run any persona behind a OpenAI compatible server via [ovos-persona-server](https://github.com/OpenVoiceOS/ovos-persona-server).
|
|
88
|
+
|
|
89
|
+
This allows you to offload the workload to a standalone server, either for performance reasons or to keep api keys in a single safe place.
|
|
90
|
+
|
|
91
|
+
Then just configure this plugin to point to your persona server like it was OpenAI
|
|
92
|
+
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
ovos_solver_openai_persona/__init__.py,sha256=dspLxf5gUeYh5FguxHh5E1QoYal69xpLk8UXV9a2Y3U,3185
|
|
2
|
+
ovos_solver_openai_persona/dialog_transformers.py,sha256=oE2-yyisVzwfPu0nCWYSik-tp-5qkmpMvaWmO_V9FV4,1206
|
|
3
|
+
ovos_solver_openai_persona/engines.py,sha256=sMRlJw1Nw9SR0ejVFdvvmTOi67EAHDQtkzU1OL4YAHk,13434
|
|
4
|
+
ovos_solver_openai_persona/summarizer.py,sha256=PI7If0EJuowsMrON0X1hwr95gp3FJuz29F41aokwJk0,2018
|
|
5
|
+
ovos_solver_openai_persona/version.py,sha256=X6PLJ7Dt-K2Z64dAW4czxS4mFv6wCg9efwbIRR2Ap9Y,114
|
|
6
|
+
ovos_openai_plugin-2.0.0.dist-info/LICENSE,sha256=jG2zQEdRNt88EgHUWPpXVWmOrOduUQRx7MnYV9YIPaw,11359
|
|
7
|
+
ovos_openai_plugin-2.0.0.dist-info/METADATA,sha256=SLKApogXRySsR0gkOIeGOqGSIQex4SM4Upx-yiHgFNk,3998
|
|
8
|
+
ovos_openai_plugin-2.0.0.dist-info/WHEEL,sha256=tZoeGjtWxWRfdplE7E3d45VPlLNQnvbKiYnx7gwAy8A,92
|
|
9
|
+
ovos_openai_plugin-2.0.0.dist-info/entry_points.txt,sha256=4E2wtVfyQvS1JwONkiFIJA4bt9-WWSPQe-JT5Pb95_Y,423
|
|
10
|
+
ovos_openai_plugin-2.0.0.dist-info/top_level.txt,sha256=K5l5fn2bnwRnMQB66jMz8GSC1yYP2-NPwslt6Wlhd3M,27
|
|
11
|
+
ovos_openai_plugin-2.0.0.dist-info/zip-safe,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1
|
|
12
|
+
ovos_openai_plugin-2.0.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
[neon.plugin.solver]
|
|
2
|
+
ovos-solver-openai-plugin = ovos_solver_openai_persona:OpenAIPersonaSolver
|
|
3
|
+
|
|
4
|
+
[opm.plugin.persona]
|
|
5
|
+
Remote Llama = ovos_solver_openai_persona:LLAMA_DEMO
|
|
6
|
+
|
|
7
|
+
[opm.solver.summarization]
|
|
8
|
+
ovos-summarizer-openai-plugin = ovos_solver_openai_persona.summarizer:OpenAISummarizer
|
|
9
|
+
|
|
10
|
+
[opm.transformer.dialog]
|
|
11
|
+
ovos-dialog-transformer-openai-plugin = ovos_solver_openai_persona.dialog_transformers:OpenAIDialogTransformer
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
ovos_solver_openai_persona
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
from typing import Optional
|
|
2
|
+
|
|
3
|
+
from ovos_solver_openai_persona.engines import OpenAIChatCompletionsSolver
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class OpenAIPersonaSolver(OpenAIChatCompletionsSolver):
|
|
7
|
+
"""default "Persona" engine"""
|
|
8
|
+
|
|
9
|
+
def __init__(self, config=None):
|
|
10
|
+
# defaults to gpt-3.5-turbo
|
|
11
|
+
super().__init__(config=config)
|
|
12
|
+
self.default_persona = config.get("persona") or "helpful, creative, clever, and very friendly."
|
|
13
|
+
|
|
14
|
+
def get_chat_history(self, persona=None):
|
|
15
|
+
persona = persona or self.default_persona
|
|
16
|
+
initial_prompt = f"You are a helpful assistant. " \
|
|
17
|
+
f"You give short and factual answers. " \
|
|
18
|
+
f"You are {persona}"
|
|
19
|
+
return super().get_chat_history(initial_prompt)
|
|
20
|
+
|
|
21
|
+
# officially exported Solver methods
|
|
22
|
+
def get_spoken_answer(self, query: str,
|
|
23
|
+
lang: Optional[str] = None,
|
|
24
|
+
units: Optional[str] = None) -> Optional[str]:
|
|
25
|
+
"""
|
|
26
|
+
Obtain the spoken answer for a given query.
|
|
27
|
+
|
|
28
|
+
Args:
|
|
29
|
+
query (str): The query text.
|
|
30
|
+
lang (Optional[str]): Optional language code. Defaults to None.
|
|
31
|
+
units (Optional[str]): Optional units for the query. Defaults to None.
|
|
32
|
+
|
|
33
|
+
Returns:
|
|
34
|
+
str: The spoken answer as a text response.
|
|
35
|
+
"""
|
|
36
|
+
answer = super().get_spoken_answer(query, lang, units)
|
|
37
|
+
if not answer or not answer.strip("?") or not answer.strip("_"):
|
|
38
|
+
return None
|
|
39
|
+
return answer
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
# for ovos-persona
|
|
43
|
+
LLAMA_DEMO = {
|
|
44
|
+
"name": "Remote LLama",
|
|
45
|
+
"solvers": [
|
|
46
|
+
"ovos-solver-openai-plugin"
|
|
47
|
+
],
|
|
48
|
+
"ovos-solver-openai-plugin": {
|
|
49
|
+
"api_url": "https://llama.smartgic.io/v1",
|
|
50
|
+
"key": "sk-xxxx"
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
if __name__ == "__main__":
|
|
56
|
+
bot = OpenAIPersonaSolver(LLAMA_DEMO["ovos-solver-openai-plugin"])
|
|
57
|
+
#for utt in bot.stream_utterances("describe quantum mechanics in simple terms"):
|
|
58
|
+
# print(utt)
|
|
59
|
+
# Quantum mechanics is a branch of physics that studies the behavior of atoms and particles at the smallest scales.
|
|
60
|
+
# It describes how these particles interact with each other, move, and change energy levels.
|
|
61
|
+
# Think of it like playing with toy building blocks that represent particles.
|
|
62
|
+
# Instead of rigid structures, these particles can be in different energy levels or "states." Quantum mechanics helps scientists understand and predict these states, making it crucial for many fields like chemistry, materials science, and engineering.
|
|
63
|
+
|
|
64
|
+
# Quantum mechanics is a branch of physics that deals with the behavior of particles on a very small scale, such as atoms and subatomic particles. It explores the idea that particles can exist in multiple states at once and that their behavior is not predictable in the traditional sense.
|
|
65
|
+
print(bot.spoken_answer("what is the definition of computer", lang="en-US"))
|
|
66
|
+
# O português Pedro Álvares Cabral encontrou o caminho marítimo para o Brasil em 1500. Ele foi o responsável por descobrir o litoral brasileiro, embora Cristóvão Colombo tenha chegado à América do Sul em 1498, cinco anos antes. Cabral desembarcou na atual costa de Alagoas, no Nordeste do Brasil.
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
from typing import Tuple
|
|
2
|
+
|
|
3
|
+
from ovos_plugin_manager.templates.transformers import DialogTransformer
|
|
4
|
+
|
|
5
|
+
from ovos_solver_openai_persona import OpenAIChatCompletionsSolver
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class OpenAIDialogTransformer(DialogTransformer):
|
|
9
|
+
def __init__(self, name="ovos-dialog-transformer-openai-plugin", priority=10, config=None):
|
|
10
|
+
super().__init__(name, priority, config)
|
|
11
|
+
self.solver = OpenAIChatCompletionsSolver({
|
|
12
|
+
"key": self.config.get("key"),
|
|
13
|
+
'api_url': self.config.get('api_url', 'https://api.openai.com/v1'),
|
|
14
|
+
"enable_memory": False,
|
|
15
|
+
"initial_prompt": "your task is to rewrite text as if it was spoken by a different character"
|
|
16
|
+
})
|
|
17
|
+
|
|
18
|
+
def transform(self, dialog: str, context: dict = None) -> Tuple[str, dict]:
|
|
19
|
+
"""
|
|
20
|
+
Optionally transform passed dialog and/or return additional context
|
|
21
|
+
:param dialog: str utterance to mutate before TTS
|
|
22
|
+
:returns: str mutated dialog
|
|
23
|
+
"""
|
|
24
|
+
prompt = context.get("prompt") or self.config.get("rewrite_prompt")
|
|
25
|
+
if not prompt:
|
|
26
|
+
return dialog, context
|
|
27
|
+
return self.solver.get_spoken_answer(f"{prompt} : {dialog}", lang=context.get("lang")), context
|
|
@@ -0,0 +1,283 @@
|
|
|
1
|
+
import json
|
|
2
|
+
from typing import Optional, Iterable, List, Dict
|
|
3
|
+
|
|
4
|
+
import requests
|
|
5
|
+
|
|
6
|
+
from ovos_plugin_manager.templates.solvers import ChatMessageSolver
|
|
7
|
+
from ovos_plugin_manager.templates.solvers import QuestionSolver
|
|
8
|
+
from ovos_plugin_manager.templates.language import LanguageTranslator, LanguageDetector
|
|
9
|
+
from ovos_utils.log import LOG
|
|
10
|
+
|
|
11
|
+
MessageList = List[Dict[str, str]] # for typing
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class OpenAICompletionsSolver(QuestionSolver):
|
|
15
|
+
def __init__(self, config=None,
|
|
16
|
+
translator: Optional[LanguageTranslator] = None,
|
|
17
|
+
detector: Optional[LanguageDetector] = None,
|
|
18
|
+
priority: int = 50,
|
|
19
|
+
enable_tx: bool = False,
|
|
20
|
+
enable_cache: bool = False,
|
|
21
|
+
internal_lang: Optional[str] = None):
|
|
22
|
+
super().__init__(config=config, translator=translator,
|
|
23
|
+
detector=detector, priority=priority,
|
|
24
|
+
enable_tx=enable_tx, enable_cache=enable_cache,
|
|
25
|
+
internal_lang=internal_lang)
|
|
26
|
+
self.api_url = f"{self.config.get('api_url', 'https://api.openai.com/v1')}/completions"
|
|
27
|
+
self.engine = self.config.get("model", "text-davinci-002") # "ada" cheaper and faster, "davinci" better
|
|
28
|
+
self.stop_token = "<|im_end|>"
|
|
29
|
+
self.key = self.config.get("key")
|
|
30
|
+
if not self.key:
|
|
31
|
+
LOG.error("key not set in config")
|
|
32
|
+
raise ValueError("key must be set")
|
|
33
|
+
|
|
34
|
+
# OpenAI API integration
|
|
35
|
+
def _do_api_request(self, prompt):
|
|
36
|
+
headers = {
|
|
37
|
+
"Content-Type": "application/json",
|
|
38
|
+
"Authorization": "Bearer " + self.key
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
# TODO - params from config
|
|
42
|
+
# https://platform.openai.com/docs/api-reference/completions/create
|
|
43
|
+
payload = {
|
|
44
|
+
"model": self.engine,
|
|
45
|
+
"prompt": prompt,
|
|
46
|
+
"max_tokens": 300,
|
|
47
|
+
"temperature": 1,
|
|
48
|
+
# between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic.
|
|
49
|
+
"top_p": 1,
|
|
50
|
+
# nucleus sampling alternative to temperature, the model considers the results of the tokens with top_p probability mass. 0.1 means only tokens comprising top 10% probability mass are considered.
|
|
51
|
+
"n": 1, # How many completions to generate for each prompt.
|
|
52
|
+
"frequency_penalty": 0,
|
|
53
|
+
# Number between -2.0 and 2.0. Positive values penalize new tokens based on their existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim.
|
|
54
|
+
"presence_penalty": 0,
|
|
55
|
+
# Number between -2.0 and 2.0. Positive values penalize new tokens based on whether they appear in the text so far, increasing the model's likelihood to talk about new topics.
|
|
56
|
+
"stop": self.stop_token
|
|
57
|
+
}
|
|
58
|
+
response = requests.post(self.api_url, headers=headers, data=json.dumps(payload)).json()
|
|
59
|
+
return response["choices"][0]["text"]
|
|
60
|
+
|
|
61
|
+
# officially exported Solver methods
|
|
62
|
+
def get_spoken_answer(self, query: str,
|
|
63
|
+
lang: Optional[str] = None,
|
|
64
|
+
units: Optional[str] = None) -> Optional[str]:
|
|
65
|
+
"""
|
|
66
|
+
Obtain the spoken answer for a given query.
|
|
67
|
+
|
|
68
|
+
Args:
|
|
69
|
+
query (str): The query text.
|
|
70
|
+
lang (Optional[str]): Optional language code. Defaults to None.
|
|
71
|
+
units (Optional[str]): Optional units for the query. Defaults to None.
|
|
72
|
+
|
|
73
|
+
Returns:
|
|
74
|
+
str: The spoken answer as a text response.
|
|
75
|
+
"""
|
|
76
|
+
response = self._do_api_request(query)
|
|
77
|
+
answer = response.strip()
|
|
78
|
+
if not answer or not answer.strip("?") or not answer.strip("_"):
|
|
79
|
+
return None
|
|
80
|
+
return answer
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def post_process_sentence(text: str) -> str:
|
|
84
|
+
text = text.replace("*", "") # TTS often literally reads "asterisk"
|
|
85
|
+
return text.strip()
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
class OpenAIChatCompletionsSolver(ChatMessageSolver):
|
|
89
|
+
def __init__(self, config=None,
|
|
90
|
+
translator: Optional[LanguageTranslator] = None,
|
|
91
|
+
detector: Optional[LanguageDetector] = None,
|
|
92
|
+
priority: int = 25,
|
|
93
|
+
enable_tx: bool = False,
|
|
94
|
+
enable_cache: bool = False,
|
|
95
|
+
internal_lang: Optional[str] = None):
|
|
96
|
+
super().__init__(config=config, translator=translator,
|
|
97
|
+
detector=detector, priority=priority,
|
|
98
|
+
enable_tx=enable_tx, enable_cache=enable_cache,
|
|
99
|
+
internal_lang=internal_lang)
|
|
100
|
+
self.api_url = f"{self.config.get('api_url', 'https://api.openai.com/v1')}/chat/completions"
|
|
101
|
+
self.engine = self.config.get("model", "gpt-4o-mini") # "ada" cheaper and faster, "davinci" better
|
|
102
|
+
self.stop_token = "<|im_end|>"
|
|
103
|
+
self.key = self.config.get("key")
|
|
104
|
+
if not self.key:
|
|
105
|
+
LOG.error("key not set in config")
|
|
106
|
+
raise ValueError("key must be set")
|
|
107
|
+
self.memory = config.get("enable_memory", True)
|
|
108
|
+
self.max_utts = config.get("memory_size", 5)
|
|
109
|
+
self.qa_pairs = [] # tuple of q+a
|
|
110
|
+
self.initial_prompt = config.get("initial_prompt", "You are a helpful assistant.")
|
|
111
|
+
|
|
112
|
+
# OpenAI API integration
|
|
113
|
+
def _do_api_request(self, messages):
|
|
114
|
+
s = requests.Session()
|
|
115
|
+
headers = {
|
|
116
|
+
"Content-Type": "application/json",
|
|
117
|
+
"Authorization": "Bearer " + self.key
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
# TODO - params from config
|
|
121
|
+
# https://platform.openai.com/docs/api-reference/completions/create
|
|
122
|
+
payload = {
|
|
123
|
+
"model": self.engine,
|
|
124
|
+
"messages": messages,
|
|
125
|
+
"max_tokens": 300,
|
|
126
|
+
"temperature": 1,
|
|
127
|
+
# between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic.
|
|
128
|
+
"top_p": 1,
|
|
129
|
+
# nucleus sampling alternative to temperature, the model considers the results of the tokens with top_p probability mass. 0.1 means only tokens comprising top 10% probability mass are considered.
|
|
130
|
+
"n": 1, # How many completions to generate for each prompt.
|
|
131
|
+
"frequency_penalty": 0,
|
|
132
|
+
# Number between -2.0 and 2.0. Positive values penalize new tokens based on their existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim.
|
|
133
|
+
"presence_penalty": 0,
|
|
134
|
+
# Number between -2.0 and 2.0. Positive values penalize new tokens based on whether they appear in the text so far, increasing the model's likelihood to talk about new topics.
|
|
135
|
+
"stop": self.stop_token
|
|
136
|
+
}
|
|
137
|
+
response = s.post(self.api_url, headers=headers, data=json.dumps(payload)).json()
|
|
138
|
+
return response["choices"][0]["message"]["content"]
|
|
139
|
+
|
|
140
|
+
def _do_streaming_api_request(self, messages):
|
|
141
|
+
|
|
142
|
+
s = requests.Session()
|
|
143
|
+
headers = {
|
|
144
|
+
"Content-Type": "application/json",
|
|
145
|
+
"Authorization": "Bearer " + self.key
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
# TODO - params from config
|
|
149
|
+
# https://platform.openai.com/docs/api-reference/completions/create
|
|
150
|
+
payload = {
|
|
151
|
+
"model": self.engine,
|
|
152
|
+
"messages": messages,
|
|
153
|
+
"max_tokens": 300,
|
|
154
|
+
"temperature": 1,
|
|
155
|
+
# between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic.
|
|
156
|
+
"top_p": 1,
|
|
157
|
+
# nucleus sampling alternative to temperature, the model considers the results of the tokens with top_p probability mass. 0.1 means only tokens comprising top 10% probability mass are considered.
|
|
158
|
+
"n": 1, # How many completions to generate for each prompt.
|
|
159
|
+
"frequency_penalty": 0,
|
|
160
|
+
# Number between -2.0 and 2.0. Positive values penalize new tokens based on their existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim.
|
|
161
|
+
"presence_penalty": 0,
|
|
162
|
+
# Number between -2.0 and 2.0. Positive values penalize new tokens based on whether they appear in the text so far, increasing the model's likelihood to talk about new topics.
|
|
163
|
+
"stop": self.stop_token,
|
|
164
|
+
"stream": True
|
|
165
|
+
}
|
|
166
|
+
for chunk in s.post(self.api_url, headers=headers,
|
|
167
|
+
stream=True, data=json.dumps(payload)).iter_lines():
|
|
168
|
+
if chunk:
|
|
169
|
+
chunk = chunk.decode("utf-8")
|
|
170
|
+
chunk = json.loads(chunk.split("data: ", 1)[-1])
|
|
171
|
+
if "error" in chunk and "message" in chunk["error"]:
|
|
172
|
+
LOG.error("API returned an error: " + chunk["error"]["message"])
|
|
173
|
+
break
|
|
174
|
+
if chunk["choices"][0].get("finish_reason"):
|
|
175
|
+
break
|
|
176
|
+
if "content" not in chunk["choices"][0]["delta"]:
|
|
177
|
+
continue
|
|
178
|
+
yield chunk["choices"][0]["delta"]["content"]
|
|
179
|
+
|
|
180
|
+
def get_chat_history(self, initial_prompt=None):
|
|
181
|
+
qa = self.qa_pairs[-1 * self.max_utts:]
|
|
182
|
+
initial_prompt = initial_prompt or self.initial_prompt or "You are a helpful assistant."
|
|
183
|
+
messages = [
|
|
184
|
+
{"role": "system", "content": initial_prompt},
|
|
185
|
+
]
|
|
186
|
+
for q, a in qa:
|
|
187
|
+
messages.append({"role": "user", "content": q})
|
|
188
|
+
messages.append({"role": "assistant", "content": a})
|
|
189
|
+
return messages
|
|
190
|
+
|
|
191
|
+
def get_messages(self, utt, initial_prompt=None) -> MessageList:
|
|
192
|
+
messages = self.get_chat_history(initial_prompt)
|
|
193
|
+
messages.append({"role": "user", "content": utt})
|
|
194
|
+
return messages
|
|
195
|
+
|
|
196
|
+
# asbtract Solver methods
|
|
197
|
+
def continue_chat(self, messages: MessageList,
|
|
198
|
+
lang: Optional[str],
|
|
199
|
+
units: Optional[str] = None) -> Optional[str]:
|
|
200
|
+
"""Generate a response based on the chat history.
|
|
201
|
+
|
|
202
|
+
Args:
|
|
203
|
+
messages (List[Dict[str, str]]): List of chat messages, each containing 'role' and 'content'.
|
|
204
|
+
lang (Optional[str]): The language code for the response. If None, will be auto-detected.
|
|
205
|
+
units (Optional[str]): Optional unit system for numerical values.
|
|
206
|
+
|
|
207
|
+
Returns:
|
|
208
|
+
Optional[str]: The generated response or None if no response could be generated.
|
|
209
|
+
"""
|
|
210
|
+
response = self._do_api_request(messages)
|
|
211
|
+
answer = post_process_sentence(response)
|
|
212
|
+
if not answer or not answer.strip("?") or not answer.strip("_"):
|
|
213
|
+
return None
|
|
214
|
+
if self.memory:
|
|
215
|
+
query = messages[-1]["content"]
|
|
216
|
+
self.qa_pairs.append((query, answer))
|
|
217
|
+
return answer
|
|
218
|
+
|
|
219
|
+
def stream_chat_utterances(self, messages: List[Dict[str, str]],
|
|
220
|
+
lang: Optional[str] = None,
|
|
221
|
+
units: Optional[str] = None) -> Iterable[str]:
|
|
222
|
+
"""
|
|
223
|
+
Stream utterances for the given chat history as they become available.
|
|
224
|
+
|
|
225
|
+
Args:
|
|
226
|
+
messages: The chat messages.
|
|
227
|
+
lang (Optional[str]): Optional language code. Defaults to None.
|
|
228
|
+
units (Optional[str]): Optional units for the query. Defaults to None.
|
|
229
|
+
|
|
230
|
+
Returns:
|
|
231
|
+
Iterable[str]: An iterable of utterances.
|
|
232
|
+
"""
|
|
233
|
+
answer = ""
|
|
234
|
+
query = messages[-1]["content"]
|
|
235
|
+
if self.memory:
|
|
236
|
+
self.qa_pairs.append((query, answer))
|
|
237
|
+
|
|
238
|
+
for chunk in self._do_streaming_api_request(messages):
|
|
239
|
+
answer += chunk
|
|
240
|
+
if any(chunk.endswith(p) for p in [".", "!", "?", "\n", ":"]):
|
|
241
|
+
if len(chunk) >= 2 and chunk[-2].isdigit() and chunk[-1] == ".":
|
|
242
|
+
continue # dont split numbers
|
|
243
|
+
if answer.strip():
|
|
244
|
+
if self.memory:
|
|
245
|
+
full_ans = f"{self.qa_pairs[-1][-1]}\n{answer}".strip()
|
|
246
|
+
self.qa_pairs[-1] = (query, full_ans)
|
|
247
|
+
yield post_process_sentence(answer)
|
|
248
|
+
answer = ""
|
|
249
|
+
|
|
250
|
+
def stream_utterances(self, query: str,
|
|
251
|
+
lang: Optional[str] = None,
|
|
252
|
+
units: Optional[str] = None) -> Iterable[str]:
|
|
253
|
+
"""
|
|
254
|
+
Stream utterances for the given query as they become available.
|
|
255
|
+
|
|
256
|
+
Args:
|
|
257
|
+
query (str): The query text.
|
|
258
|
+
lang (Optional[str]): Optional language code. Defaults to None.
|
|
259
|
+
units (Optional[str]): Optional units for the query. Defaults to None.
|
|
260
|
+
|
|
261
|
+
Returns:
|
|
262
|
+
Iterable[str]: An iterable of utterances.
|
|
263
|
+
"""
|
|
264
|
+
messages = self.get_messages(query)
|
|
265
|
+
yield from self.stream_chat_utterances(messages, lang, units)
|
|
266
|
+
|
|
267
|
+
def get_spoken_answer(self, query: str,
|
|
268
|
+
lang: Optional[str] = None,
|
|
269
|
+
units: Optional[str] = None) -> Optional[str]:
|
|
270
|
+
"""
|
|
271
|
+
Obtain the spoken answer for a given query.
|
|
272
|
+
|
|
273
|
+
Args:
|
|
274
|
+
query (str): The query text.
|
|
275
|
+
lang (Optional[str]): Optional language code. Defaults to None.
|
|
276
|
+
units (Optional[str]): Optional units for the query. Defaults to None.
|
|
277
|
+
|
|
278
|
+
Returns:
|
|
279
|
+
str: The spoken answer as a text response.
|
|
280
|
+
"""
|
|
281
|
+
messages = self.get_messages(query)
|
|
282
|
+
# just for api compat since it's a subclass, shouldn't be directly used
|
|
283
|
+
return self.continue_chat(messages=messages, lang=lang, units=units)
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
from ovos_solver_openai_persona.engines import OpenAIChatCompletionsSolver
|
|
2
|
+
from ovos_plugin_manager.templates.solvers import TldrSolver
|
|
3
|
+
from ovos_plugin_manager.templates.language import LanguageTranslator, LanguageDetector
|
|
4
|
+
from typing import Dict, Optional
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class OpenAISummarizer(TldrSolver):
|
|
8
|
+
TEMPLATE = """Your task is to summarize the text into a suitable format.
|
|
9
|
+
Answer in plaintext with no formatting, 2 paragraphs long at most.
|
|
10
|
+
Focus on the most important information.
|
|
11
|
+
---------------------
|
|
12
|
+
{content}
|
|
13
|
+
"""
|
|
14
|
+
def __init__(self, config: Optional[Dict] = None,
|
|
15
|
+
translator: Optional[LanguageTranslator] = None,
|
|
16
|
+
detector: Optional[LanguageDetector] = None,
|
|
17
|
+
priority: int = 50,
|
|
18
|
+
enable_tx: bool = False,
|
|
19
|
+
enable_cache: bool = False,
|
|
20
|
+
internal_lang: Optional[str] = None):
|
|
21
|
+
super().__init__(config=config, translator=translator,
|
|
22
|
+
detector=detector, priority=priority,
|
|
23
|
+
enable_tx=enable_tx, enable_cache=enable_cache,
|
|
24
|
+
internal_lang=internal_lang)
|
|
25
|
+
self.llm = OpenAIChatCompletionsSolver(config=config, translator=translator,
|
|
26
|
+
detector=detector, priority=priority,
|
|
27
|
+
enable_tx=enable_tx, enable_cache=enable_cache,
|
|
28
|
+
internal_lang=internal_lang)
|
|
29
|
+
self.prompt_template = self.config.get("prompt_template") or self.TEMPLATE
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def get_tldr(self, document: str, lang: Optional[str] = None) -> str:
|
|
33
|
+
"""
|
|
34
|
+
Summarize the provided document.
|
|
35
|
+
|
|
36
|
+
:param document: The text of the document to summarize, assured to be in the default language.
|
|
37
|
+
:param lang: Optional language code.
|
|
38
|
+
:return: A summary of the provided document.
|
|
39
|
+
"""
|
|
40
|
+
prompt = self.prompt_template.format(content=document)
|
|
41
|
+
return self.llm.get_spoken_answer(prompt, lang)
|