cohere-ai 1.0.0

Sign up to get free protection for your applications and to get access to all the features.
data/template.md ADDED
@@ -0,0 +1,728 @@
1
+ # Cohere AI
2
+
3
+ A Ruby gem for interacting with [Cohere AI](https://cohere.com).
4
+
5
+ ![The logo depicts a ruby with a liquid-like interior on a peach background. The gem has a flowing lava appearance, with swirls of red and pink suggesting movement, resembling molten rock. Darker red edges and a circular dark border frame this vibrant, fluid core.](https://raw.githubusercontent.com/gbaptista/assets/main/cohere-ai/cohere-ai-canvas.png)
6
+
7
+ > _This Gem is designed to provide low-level access to Cohere AI, enabling people to build abstractions on top of it. If you are interested in more high-level abstractions or more user-friendly tools, you may want to consider [Nano Bots](https://github.com/icebaker/ruby-nano-bots) 💎 🤖._
8
+
9
+ ## TL;DR and Quick Start
10
+
11
+ ```ruby
12
+ gem 'cohere-ai', '~> 1.0.0'
13
+ ```
14
+
15
+ ```ruby
16
+ require 'cohere-ai'
17
+
18
+ client = Cohere.new(
19
+ credentials: { api_key: ENV['COHERE_API_KEY'] },
20
+ options: { server_sent_events: true }
21
+ )
22
+
23
+ result = client.chat(
24
+ { model: 'command', message: 'Hi!' }
25
+ )
26
+ ```
27
+
28
+ Result:
29
+ ```ruby
30
+ { 'response_id' => '59aac3ec-74c8-4b65-a80c-d4c1916d2511',
31
+ 'text' =>
32
+ "Hi there! I'm Coral, an AI-assistant chatbot ready to help you with whatever you need. Is there anything I can assist you with today? \n" \
33
+ "\n" \
34
+ "If you'd like, I can also provide you with a list of some common topics that I can help with if you're looking for ideas. \n" \
35
+ "\n" \
36
+ "Just let me know if there's anything I can do to help make your day easier!",
37
+ 'generation_id' => '8a72b85c-ed29-4258-bd52-82b81be2353b',
38
+ 'token_count' => { 'prompt_tokens' => 64, 'response_tokens' => 82, 'total_tokens' => 146, 'billed_tokens' => 135 },
39
+ 'meta' => { 'api_version' => { 'version' => '1' },
40
+ 'billed_units' => { 'input_tokens' => 53, 'output_tokens' => 82 } },
41
+ 'tool_inputs' => nil }
42
+ ```
43
+
44
+ ## Index
45
+
46
+ {index}
47
+
48
+ ## Setup
49
+
50
+ ### Installing
51
+
52
+ ```sh
53
+ gem install cohere-ai -v 1.0.0
54
+ ```
55
+
56
+ ```sh
57
+ gem 'cohere-ai', '~> 1.0.0'
58
+ ```
59
+
60
+ ### Credentials
61
+
62
+ You can obtain your API key from the [Cohere AI Platform](https://dashboard.cohere.com).
63
+
64
+ ## Usage
65
+
66
+ ### Client
67
+
68
+ Ensure that you have an [API Key](#credentials) for authentication.
69
+
70
+ Create a new client:
71
+ ```ruby
72
+ require 'cohere-ai'
73
+
74
+ client = Cohere.new(
75
+ credentials: { api_key: ENV['COHERE_API_KEY'] },
76
+ options: { server_sent_events: true }
77
+ )
78
+ ```
79
+
80
+ #### Custom Address
81
+
82
+ You can use a custom address:
83
+
84
+ ```ruby
85
+ require 'cohere-ai'
86
+
87
+ client = Cohere.new(
88
+ credentials: {
89
+ address: 'https://api.cohere.ai',
90
+ api_key: ENV['COHERE_API_KEY']
91
+ },
92
+ options: { server_sent_events: true }
93
+ )
94
+ ```
95
+
96
+ ### Methods
97
+
98
+ #### chat
99
+
100
+ Documentation: https://docs.cohere.com/reference/chat
101
+
102
+ ##### Without Streaming Events
103
+
104
+ ```ruby
105
+ result = client.chat(
106
+ { model: 'command', message: 'Hi!' }
107
+ )
108
+ ```
109
+
110
+ Result:
111
+ ```ruby
112
+ { 'response_id' => '59aac3ec-74c8-4b65-a80c-d4c1916d2511',
113
+ 'text' =>
114
+ "Hi there! I'm Coral, an AI-assistant chatbot ready to help you with whatever you need. Is there anything I can assist you with today? \n" \
115
+ "\n" \
116
+ "If you'd like, I can also provide you with a list of some common topics that I can help with if you're looking for ideas. \n" \
117
+ "\n" \
118
+ "Just let me know if there's anything I can do to help make your day easier!",
119
+ 'generation_id' => '8a72b85c-ed29-4258-bd52-82b81be2353b',
120
+ 'token_count' => { 'prompt_tokens' => 64, 'response_tokens' => 82, 'total_tokens' => 146, 'billed_tokens' => 135 },
121
+ 'meta' => { 'api_version' => { 'version' => '1' },
122
+ 'billed_units' => { 'input_tokens' => 53, 'output_tokens' => 82 } },
123
+ 'tool_inputs' => nil }
124
+ ```
125
+
126
+ ##### Receiving Stream Events
127
+
128
+ Ensure that you have enabled [Server-Sent Events](#streaming-and-server-sent-events-sse) before using blocks for streaming. You also need to add `stream: true` in your payload:
129
+
130
+ ```ruby
131
+ client.chat(
132
+ { model: 'command', stream: true, message: 'Hi!' }
133
+ ) do |event, raw|
134
+ puts event
135
+ end
136
+ ```
137
+
138
+ Event:
139
+ ```ruby
140
+ { 'is_finished' => false,
141
+ 'event_type' => 'stream-start',
142
+ 'generation_id' => '0672df6f-736e-4536-8ad1-36bc808a114d' }
143
+ ```
144
+
145
+ ```ruby
146
+ { 'is_finished' => false,
147
+ 'event_type' => 'text-generation',
148
+ 'text' => 'Hi' }
149
+ ```
150
+
151
+ ```ruby
152
+ { 'is_finished' => true,
153
+ 'event_type' => 'stream-end',
154
+ 'response' => {
155
+ 'response_id' => '7dca6bf9-8a21-4f81-9e4e-2c5b8eb8c767',
156
+ 'text' => "Hi there! How can I help you today? I'm glad to assist you with any questions or tasks you have in mind, and I'm always happy to have a friendly conversation too. Go ahead and let me know how I can make your day better!",
157
+ 'generation_id' => '0672df6f-736e-4536-8ad1-36bc808a114d',
158
+ 'token_count' => {
159
+ 'prompt_tokens' => 64, 'response_tokens' => 52, 'total_tokens' => 116, 'billed_tokens' => 105
160
+ },
161
+ 'tool_inputs' => nil
162
+ },
163
+ 'finish_reason' => 'COMPLETE' }
164
+ ```
165
+
166
+ You can get all the receive events at once as an array:
167
+ ```ruby
168
+ result = client.chat(
169
+ { model: 'command', stream: true, message: 'Hi!' }
170
+ )
171
+ ```
172
+
173
+ Result:
174
+ ```ruby
175
+ [{ 'is_finished' => false, 'event_type' => 'stream-start', 'generation_id' => '7f0349ef-a823-4779-801a-6e0a56c016a9' },
176
+ { 'is_finished' => false, 'event_type' => 'text-generation', 'text' => 'Hi' },
177
+ # ...
178
+ { 'is_finished' => false, 'event_type' => 'text-generation', 'text' => '?' },
179
+ { 'is_finished' => true,
180
+ 'event_type' => 'stream-end',
181
+ 'response' =>
182
+ { 'response_id' => 'f4135de4-3631-4f7c-98be-deb50b7f986b',
183
+ 'text' =>
184
+ "Hi there! How can I assist you today? I'm programmed to provide helpful, fact-based responses and engage in conversations on a wide range of topics. Feel free to ask me anything, and we'll see how I can help you out! \n" \
185
+ "\n" \
186
+ 'Do you have any requests or questions that I can help with?',
187
+ 'generation_id' => '7f0349ef-a823-4779-801a-6e0a56c016a9',
188
+ 'token_count' => { 'prompt_tokens' => 64, 'response_tokens' => 65, 'total_tokens' => 129, 'billed_tokens' => 118 },
189
+ 'tool_inputs' => nil },
190
+ 'finish_reason' => 'COMPLETE' }]
191
+ ```
192
+
193
+ You can mix both as well:
194
+ ```ruby
195
+ result = client.chat(
196
+ { model: 'command', stream: true, message: 'Hi!' }
197
+ ) do |event, raw|
198
+ puts event
199
+ end
200
+ ```
201
+
202
+ #### generate
203
+
204
+ Documentation: https://docs.cohere.com/reference/generate
205
+
206
+ ```ruby
207
+ client.generate(
208
+ { stream: true,
209
+ truncate: 'END',
210
+ return_likelihoods: 'NONE',
211
+ prompt: 'Please explain to me how LLMs work' }
212
+ ) do |event, raw|
213
+ puts event
214
+ end
215
+ ```
216
+
217
+ ```ruby
218
+ result = client.generate(
219
+ { truncate: 'END',
220
+ return_likelihoods: 'NONE',
221
+ prompt: 'Please explain to me how LLMs work' }
222
+ )
223
+ ```
224
+
225
+ Result:
226
+ ```ruby
227
+ { 'id' => '9caef8a6-07fb-465c-a003-5fd7c7bbccbd',
228
+ 'generations' =>
229
+ [{ 'id' => '11b043ab-6d9c-415f-90b0-6a802a3807f7',
230
+ 'text' =>
231
+ " LLMs, or Large Language Models, are a type of neural network architecture designed to understand and generate human-like language. They are trained by feeding them massive amounts of text data and adjusting their internal parameters to predict the next word in a sequence accurately, given the words that came before it. This process is known as language modeling.\n" \
232
+ "\n" \
233
+ "There are two main types of LLMs: autoregressive and generative models. Autoregressive models, such as the long short-term memory (LSTM) network and the gated recurrent unit (GRU), predict the next word in a sequence by relying solely on the past context. On the other hand, generative models, such as the variational autoencoder (VAE) and the generative adversarial network (GAN), can generate new data similar to the training data.\n" \
234
+ "\n" \
235
+ "One of the key features of LLMs is their ability to capture long-range dependencies in text, which means they can understand and generate sentences that rely on information from words far away in the sequence. This is particularly useful for tasks like language translation, summarization, and question-answering, where understanding the context is crucial.\n" \
236
+ "\n" \
237
+ "To improve the accuracy and performance of LLMs, researchers and engineers often use techniques like pre-training and transfer learning. During pre-training, the LLM is trained on a large and diverse dataset, such as books, articles, and websites, to learn general language patterns and relationships. Once the LLM is pre-trained, it can be fine-tuned on specific tasks with smaller datasets related to the task, such as medical texts or legal documents. This way, the LLM can leverage its knowledge of language understanding while adapting to the specific domain or task at hand.\n" \
238
+ "\n" \
239
+ "Overall, LLMs have had a significant impact on the field of natural language processing, allowing researchers to build more sophisticated models that can understand and generate language in ways that were previously impossible. However, it is important to note that LLMs are sophisticated tools that require large amounts of data, computational power, and careful tuning to achieve their full potential. Moreover, they can also inherit the biases present in the training data, highlighting the importance of data diversity and responsible LLM development and usage. \n" \
240
+ "\n" \
241
+ 'Would you like me to go into more detail about any specific aspect of LLM functionality? ',
242
+ 'finish_reason' => 'COMPLETE' }],
243
+ 'prompt' => 'Please explain to me how LLMs work',
244
+ 'meta' => { 'api_version' => { 'version' => '1' },
245
+ 'billed_units' => { 'input_tokens' => 8, 'output_tokens' => 476 } } }
246
+ ```
247
+
248
+ #### embed
249
+
250
+ Documentation: https://docs.cohere.com/reference/embed
251
+
252
+ ```ruby
253
+ result = client.embed(
254
+ { texts: ['hello', 'goodbye'],
255
+ model: 'embed-english-v3.0',
256
+ input_type: 'classification' }
257
+ )
258
+ ```
259
+
260
+ Result:
261
+ ```ruby
262
+ { 'id' => '5d77f09a-3518-44d3-bac3-f868b3e036bc',
263
+ 'texts' => ['hello', 'goodbye'],
264
+ 'embeddings' =>
265
+ [[0.016296387,
266
+ -0.008354187,
267
+ # ...
268
+ -0.01802063,
269
+ 0.009765625],
270
+ [0.04663086,
271
+ -0.023239136,
272
+ # ...
273
+ 0.0023212433,
274
+ 0.0052719116]],
275
+ 'meta' =>
276
+ { 'api_version' => { 'version' => '1' }, 'billed_units' => { 'input_tokens' => 2 } },
277
+ 'response_type' => 'embeddings_floats' }
278
+ ```
279
+
280
+ #### rerank
281
+
282
+ Documentation: https://docs.cohere.com/reference/rerank
283
+
284
+ ```ruby
285
+ result = client.rerank(
286
+ { return_documents: false,
287
+ max_chunks_per_doc: 10,
288
+ model: 'rerank-english-v2.0',
289
+ query: 'What is the capital of the United States?',
290
+ documents: [
291
+ 'Carson City is the capital city of the American state of Nevada.',
292
+ 'The Commonwealth of the Northern Mariana Islands is a group of islands in the Pacific Ocean. Its capital is Saipan.',
293
+ 'Washington, D.C. (also known as simply Washington or D.C., and officially as the District of Columbia) is the capital of the United States. It is a federal district.',
294
+ 'Capital punishment (the death penalty) has existed in the United States since beforethe United States was a country. As of 2017, capital punishment is legal in 30 of the 50 states.'
295
+ ] }
296
+ )
297
+ ```
298
+
299
+ Result:
300
+ ```ruby
301
+ { 'id' => 'ba2100fe-69d2-41d6-8680-810948af872d',
302
+ 'results' =>
303
+ [{ 'index' => 2, 'relevance_score' => 0.98005307 },
304
+ { 'index' => 3, 'relevance_score' => 0.27904198 },
305
+ { 'index' => 0, 'relevance_score' => 0.10194652 },
306
+ { 'index' => 1, 'relevance_score' => 0.0721122 }],
307
+ 'meta' =>
308
+ { 'api_version' => { 'version' => '1' }, 'billed_units' => { 'search_units' => 1 } } }
309
+ ```
310
+
311
+ #### classify
312
+
313
+ Documentation: https://docs.cohere.com/reference/classify
314
+
315
+ ```ruby
316
+ result = client.classify(
317
+ {
318
+ truncate: 'END',
319
+ inputs: [
320
+ 'Confirm your email address',
321
+ 'hey i need u to send some $'
322
+ ],
323
+ examples: [
324
+ {
325
+ text: "Dermatologists don't like her!",
326
+ label: 'Spam'
327
+ },
328
+ {
329
+ text: 'Hello, open to this?',
330
+ label: 'Spam'
331
+ },
332
+ {
333
+ text: 'I need help please wire me $1000 right now',
334
+ label: 'Spam'
335
+ },
336
+ {
337
+ text: 'Nice to know you ;)',
338
+ label: 'Spam'
339
+ },
340
+ {
341
+ text: 'Please help me?',
342
+ label: 'Spam'
343
+ },
344
+ {
345
+ text: 'Your parcel will be delivered today',
346
+ label: 'Not spam'
347
+ },
348
+ {
349
+ text: 'Review changes to our Terms and Conditions',
350
+ label: 'Not spam'
351
+ },
352
+ {
353
+ text: 'Weekly sync notes',
354
+ label: 'Not spam'
355
+ },
356
+ {
357
+ text: 'Re: Follow up from today’s meeting',
358
+ label: 'Not spam'
359
+ },
360
+ {
361
+ text: 'Pre-read for tomorrow',
362
+ label: 'Not spam'
363
+ }
364
+ ]
365
+ }
366
+ )
367
+ ```
368
+
369
+ Result:
370
+ ```ruby
371
+ { 'id' => '1d0c322e-9ab7-4a80-b601-720e7592dde5',
372
+ 'classifications' =>
373
+ [{ 'classification_type' => 'single-label',
374
+ 'confidence' => 0.8082329,
375
+ 'confidences' => [0.8082329],
376
+ 'id' => '44b2e358-83f1-4b9b-a6f1-e8d9c823f0ba',
377
+ 'input' => 'Confirm your email address',
378
+ 'labels' =>
379
+ { 'Not spam' => { 'confidence' => 0.8082329 },
380
+ 'Spam' => { 'confidence' => 0.19176713 } },
381
+ 'prediction' => 'Not spam',
382
+ 'predictions' => ['Not spam'] },
383
+ { 'classification_type' => 'single-label',
384
+ 'confidence' => 0.9893421,
385
+ 'confidences' => [0.9893421],
386
+ 'id' => '53ad6d6e-872f-4185-b3d6-6d03fe55f4c4',
387
+ 'input' => 'hey i need u to send some $',
388
+ 'labels' =>
389
+ { 'Not spam' => { 'confidence' => 0.01065793 },
390
+ 'Spam' => { 'confidence' => 0.9893421 } },
391
+ 'prediction' => 'Spam',
392
+ 'predictions' => ['Spam'] }],
393
+ 'meta' =>
394
+ { 'api_version' => { 'version' => '1' }, 'billed_units' => { 'classifications' => 2 } } }
395
+ ```
396
+
397
+ #### detect_language
398
+
399
+ Documentation: https://docs.cohere.com/reference/detect-language
400
+
401
+ ```ruby
402
+ result = client.detect_language(
403
+ { texts: ['Hello world', "'Здравствуй, Мир'"] }
404
+ )
405
+ ```
406
+
407
+ Result:
408
+ ```ruby
409
+ { 'id' => '82b111d4-ba6d-4f60-9536-883b42f3d86d',
410
+ 'results' =>
411
+ [{ 'language_code' => 'en', 'language_name' => 'English' },
412
+ { 'language_code' => 'ru', 'language_name' => 'Russian' }],
413
+ 'meta' => { 'api_version' => { 'version' => '1' } } }
414
+ ```
415
+
416
+ #### summarize
417
+
418
+ Documentation: https://docs.cohere.com/reference/summarize
419
+
420
+ ```ruby
421
+ result = client.summarize(
422
+ { text: "Ice cream is a sweetened frozen food typically eaten as a snack or dessert. It may be made from milk or cream and is flavoured with a sweetener, either sugar or an alternative, and a spice, such as cocoa or vanilla, or with fruit such as strawberries or peaches. It can also be made by whisking a flavored cream base and liquid nitrogen together. Food coloring is sometimes added, in addition to stabilizers. The mixture is cooled below the freezing point of water and stirred to incorporate air spaces and to prevent detectable ice crystals from forming. The result is a smooth, semi-solid foam that is solid at very low temperatures (below 2 °C or 35 °F). It becomes more malleable as its temperature increases.\n\nThe meaning of the name \"ice cream\" varies from one country to another. In some countries, such as the United States, \"ice cream\" applies only to a specific variety, and most governments regulate the commercial use of the various terms according to the relative quantities of the main ingredients, notably the amount of cream. Products that do not meet the criteria to be called ice cream are sometimes labelled \"frozen dairy dessert\" instead. In other countries, such as Italy and Argentina, one word is used fo\r all variants. Analogues made from dairy alternatives, such as goat's or sheep's milk, or milk substitutes (e.g., soy, cashew, coconut, almond milk or tofu), are available for those who are lactose intolerant, allergic to dairy protein or vegan." }
423
+ )
424
+ ```
425
+
426
+ Result:
427
+ ```ruby
428
+ { 'id' => '5189bed8-2d12-47d8-8ae7-cf60788cf507',
429
+ 'summary' =>
430
+ 'Ice cream is a popular frozen dessert made from milk or cream, sweeteners, and spices like vanilla or cocoa, or fruit like strawberries. It is cooled below the freezing point of water and stirred to incorporate air spaces, resulting in a smooth semi-solid foam. While the name applies to just one variety in some countries, like the US, it refers to all variants in others, like Italy. Additionally, there are dairy alternatives available for those who are lactose intolerant or vegan. Ice cream is regulated by governments based on the quantities of its main ingredients.',
431
+ 'meta' =>
432
+ { 'api_version' => { 'version' => '1' },
433
+ 'billed_units' => { 'input_tokens' => 321, 'output_tokens' => 111 } } }
434
+ ```
435
+
436
+ #### tokenize
437
+
438
+ Documentation: https://docs.cohere.com/reference/tokenize
439
+
440
+ ```ruby
441
+ result = client.tokenize(
442
+ { text: 'tokenize me! :D', model: 'command' }
443
+ )
444
+ ```
445
+
446
+ Result:
447
+ ```ruby
448
+ { 'tokens' => [10_002, 2261, 2012, 8, 2792, 43],
449
+ 'token_strings' => ['token', 'ize', ' me', '!', ' :', 'D'],
450
+ 'meta' => { 'api_version' => { 'version' => '1' } } }
451
+ ```
452
+
453
+ #### detokenize
454
+
455
+ Documentation: https://docs.cohere.com/reference/detokenize
456
+
457
+ ```ruby
458
+ result = client.detokenize(
459
+ { tokens: [10_104, 12_221, 1315, 34, 1420, 69], model: 'command' }
460
+ )
461
+ ```
462
+
463
+ Result:
464
+ ```ruby
465
+ { 'text' => ' Anton Mun🟣;🥭^', 'meta' => { 'api_version' => { 'version' => '1' } } }
466
+ ```
467
+
468
+ ### Datasets
469
+
470
+ Documentation: https://docs.cohere.com/reference/create-dataset
471
+
472
+ ```ruby
473
+ result = client.request(
474
+ 'v1/dataset',
475
+ request_method: 'GET', server_sent_events: false
476
+ )
477
+ ```
478
+
479
+ ```ruby
480
+ result = client.request(
481
+ 'v1/dataset',
482
+ { name: 'prompt-completion-dataset',
483
+ data: File.read('./prompt-completion.jsonl'),
484
+ dataset_type: 'prompt-completion-finetune-input' },
485
+ request_method: 'POST', server_sent_events: false
486
+ )
487
+ ```
488
+
489
+ ### Connectors
490
+
491
+ Documentation: https://docs.cohere.com/reference/list-connectors
492
+
493
+ ```ruby
494
+ result = client.request(
495
+ 'v1/connectors',
496
+ request_method: 'GET', server_sent_events: false
497
+ )
498
+ ```
499
+
500
+ ```ruby
501
+ result = client.request(
502
+ 'v1/connectors',
503
+ { name: 'test-connector',
504
+ url: 'https://example.com/search',
505
+ description: 'A test connector' },
506
+ request_method: 'POST', server_sent_events: false
507
+ )
508
+ ```
509
+
510
+ ### Streaming and Server-Sent Events (SSE)
511
+
512
+ [Server-Sent Events (SSE)](https://en.wikipedia.org/wiki/Server-sent_events) is a technology that allows certain endpoints to offer streaming capabilities, such as creating the impression that "the model is typing along with you," rather than delivering the entire answer all at once.
513
+
514
+ You can set up the client to use Server-Sent Events (SSE) for all supported endpoints:
515
+ ```ruby
516
+ client = Cohere.new(
517
+ credentials: { api_key: ENV['COHERE_API_KEY'] },
518
+ options: { server_sent_events: true }
519
+ )
520
+ ```
521
+
522
+ Or, you can decide on a request basis:
523
+ ```ruby
524
+ client.chat(
525
+ { model: 'command', stream: true, message: 'Hi!' }
526
+ server_sent_events: true
527
+ ) do |event, raw|
528
+ puts event
529
+ end
530
+ ```
531
+
532
+ With Server-Sent Events (SSE) enabled, you can use a block to receive partial results via events. This feature is particularly useful for methods that offer streaming capabilities, such as `chat`: [Receiving Stream Events](#receiving-stream-events)
533
+
534
+ #### Server-Sent Events (SSE) Hang
535
+
536
+ Method calls will _hang_ until the server-sent events finish, so even without providing a block, you can obtain the final results of the received events: [Receiving Stream Events](#receiving-stream-events)
537
+
538
+
539
+ ### Back-and-Forth Conversations
540
+
541
+ To maintain a back-and-forth conversation, you need to append the received responses and build a history for your requests:
542
+
543
+ ```rb
544
+ result = client.chat(
545
+ { model: 'command',
546
+ chat_history: [
547
+ { role: 'USER', message: 'Hi, my name is Purple.' },
548
+ { role: 'CHATBOT', message: "Hi Purple! It's nice to meet you." }
549
+ ],
550
+ message: "What's my name?" }
551
+ )
552
+ ```
553
+
554
+ Result:
555
+ ```ruby
556
+ { 'response_id' => 'a2009c24-fee3-465e-9945-a85edcdcb3cf',
557
+ 'text' =>
558
+ "Your name is Purple. Isn't it an enchanting name? \n" \
559
+ "\n" \
560
+ "Would you like me to help you with anything else? If you have any questions or need assistance with a particular task, feel free to let me know. I'm here to help!",
561
+ 'generation_id' => 'e1630c10-f773-4ced-8760-19199004653a',
562
+ 'token_count' => { 'prompt_tokens' => 91, 'response_tokens' => 51, 'total_tokens' => 142, 'billed_tokens' => 124 },
563
+ 'meta' => { 'api_version' => { 'version' => '1' },
564
+ 'billed_units' => { 'input_tokens' => 73, 'output_tokens' => 51 } },
565
+ 'tool_inputs' => nil }
566
+
567
+ ```
568
+
569
+ ### New Functionalities and APIs
570
+
571
+ Cohere may launch a new endpoint that we haven't covered in the Gem yet. If that's the case, you may still be able to use it through the `request` method. For example, `chat` is just a wrapper for `v1/chat`, which you can call directly like this:
572
+
573
+ ```ruby
574
+ result = client.request(
575
+ 'v1/chat',
576
+ { model: 'command', message: 'Hi!' },
577
+ request_method: 'POST', server_sent_events: true
578
+ )
579
+ ```
580
+
581
+ ### Request Options
582
+
583
+ #### Timeout
584
+
585
+ You can set the maximum number of seconds to wait for the request to complete with the `timeout` option:
586
+
587
+ ```ruby
588
+ client = Cohere.new(
589
+ credentials: { api_key: ENV['COHERE_API_KEY'] },
590
+ options: { connection: { request: { timeout: 5 } } }
591
+ )
592
+ ```
593
+
594
+ You can also have more fine-grained control over [Faraday's Request Options](https://lostisland.github.io/faraday/#/customization/request-options?id=request-options) if you prefer:
595
+
596
+ ```ruby
597
+ client = Cohere.new(
598
+ credentials: { api_key: ENV['COHERE_API_KEY'] },
599
+ options: {
600
+ connection: {
601
+ request: {
602
+ timeout: 5,
603
+ open_timeout: 5,
604
+ read_timeout: 5,
605
+ write_timeout: 5
606
+ }
607
+ }
608
+ }
609
+ )
610
+ ```
611
+
612
+ ### Error Handling
613
+
614
+ #### Rescuing
615
+
616
+ ```ruby
617
+ require 'cohere-ai'
618
+
619
+ begin
620
+ client.chat(
621
+ { model: 'command', message: 'Hi!' }
622
+ )
623
+ rescue Cohere::Errors::CohereError => error
624
+ puts error.class # Cohere::Errors::RequestError
625
+ puts error.message # 'the server responded with status 500'
626
+
627
+ puts error.payload
628
+ # { model: 'command',
629
+ # message: 'Hi!'
630
+ # ...
631
+ # }
632
+
633
+ puts error.request
634
+ # #<Faraday::ServerError response={:status=>500, :headers...
635
+ end
636
+ ```
637
+
638
+ #### For Short
639
+
640
+ ```ruby
641
+ require 'cohere-ai/errors'
642
+
643
+ begin
644
+ client.chat(
645
+ { model: 'command',
646
+ messages: [{ role: 'user', content: 'hi!' }] }
647
+ )
648
+ rescue CohereError => error
649
+ puts error.class # Cohere::Errors::RequestError
650
+ end
651
+ ```
652
+
653
+ #### Errors
654
+
655
+ ```ruby
656
+ CohereError
657
+
658
+ MissingAPIKeyError
659
+ BlockWithoutServerSentEventsError
660
+
661
+ RequestError
662
+ ```
663
+
664
+ ## Development
665
+
666
+ ```bash
667
+ bundle
668
+ rubocop -A
669
+ ```
670
+
671
+ ### Purpose
672
+
673
+ This Gem is designed to provide low-level access to Cohere, enabling people to build abstractions on top of it. If you are interested in more high-level abstractions or more user-friendly tools, you may want to consider [Nano Bots](https://github.com/icebaker/ruby-nano-bots) 💎 🤖.
674
+
675
+ ### Publish to RubyGems
676
+
677
+ ```bash
678
+ gem build cohere-ai.gemspec
679
+
680
+ gem signin
681
+
682
+ gem push cohere-ai-1.0.0.gem
683
+ ```
684
+
685
+ ### Updating the README
686
+
687
+ Install [Babashka](https://babashka.org):
688
+
689
+ ```sh
690
+ curl -s https://raw.githubusercontent.com/babashka/babashka/master/install | sudo bash
691
+ ```
692
+
693
+ Update the `template.md` file and then:
694
+
695
+ ```sh
696
+ bb tasks/generate-readme.clj
697
+ ```
698
+
699
+ Trick for automatically updating the `README.md` when `template.md` changes:
700
+
701
+ ```sh
702
+ sudo pacman -S inotify-tools # Arch / Manjaro
703
+ sudo apt-get install inotify-tools # Debian / Ubuntu / Raspberry Pi OS
704
+ sudo dnf install inotify-tools # Fedora / CentOS / RHEL
705
+
706
+ while inotifywait -e modify template.md; do bb tasks/generate-readme.clj; done
707
+ ```
708
+
709
+ Trick for Markdown Live Preview:
710
+ ```sh
711
+ pip install -U markdown_live_preview
712
+
713
+ mlp README.md -p 8076
714
+ ```
715
+
716
+ ## Resources and References
717
+
718
+ These resources and references may be useful throughout your learning process.
719
+
720
+ - [Cohere AI Official Website](https://cohere.com)
721
+ - [Cohere AI Documentation](https://docs.cohere.com/docs)
722
+ - [Cohere AI API Reference](https://docs.cohere.com/reference/about)
723
+
724
+ ## Disclaimer
725
+
726
+ This is not an official Cohere project, nor is it affiliated with Cohere in any way.
727
+
728
+ This software is distributed under the [MIT License](https://github.com/gbaptista/cohere-ai/blob/main/LICENSE). This license includes a disclaimer of warranty. Moreover, the authors assume no responsibility for any damage or costs that may result from using this project. Use the Cohere AI Ruby Gem at your own risk.