forked from cohere-ai/cohere-python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbase_client.py
4414 lines (3693 loc) · 225 KB
/
base_client.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# This file was auto-generated by Fern from our API Definition.
import json
import os
import typing
from json.decoder import JSONDecodeError
import httpx
from .connectors.client import AsyncConnectorsClient, ConnectorsClient
from .core.api_error import ApiError
from .core.client_wrapper import AsyncClientWrapper, SyncClientWrapper
from .core.request_options import RequestOptions
from .core.unchecked_base_model import construct_type
from .datasets.client import AsyncDatasetsClient, DatasetsClient
from .embed_jobs.client import AsyncEmbedJobsClient, EmbedJobsClient
from .environment import ClientEnvironment
from .errors.bad_request_error import BadRequestError
from .errors.client_closed_request_error import ClientClosedRequestError
from .errors.forbidden_error import ForbiddenError
from .errors.gateway_timeout_error import GatewayTimeoutError
from .errors.internal_server_error import InternalServerError
from .errors.not_found_error import NotFoundError
from .errors.not_implemented_error import NotImplementedError
from .errors.service_unavailable_error import ServiceUnavailableError
from .errors.too_many_requests_error import TooManyRequestsError
from .errors.unauthorized_error import UnauthorizedError
from .errors.unprocessable_entity_error import UnprocessableEntityError
from .finetuning.client import AsyncFinetuningClient, FinetuningClient
from .models.client import AsyncModelsClient, ModelsClient
from .types.chat_connector import ChatConnector
from .types.chat_document import ChatDocument
from .types.chat_request_citation_quality import ChatRequestCitationQuality
from .types.chat_request_prompt_truncation import ChatRequestPromptTruncation
from .types.chat_stream_request_citation_quality import ChatStreamRequestCitationQuality
from .types.chat_stream_request_prompt_truncation import ChatStreamRequestPromptTruncation
from .types.check_api_key_response import CheckApiKeyResponse
from .types.classify_example import ClassifyExample
from .types.classify_request_truncate import ClassifyRequestTruncate
from .types.classify_response import ClassifyResponse
from .types.client_closed_request_error_body import ClientClosedRequestErrorBody
from .types.detokenize_response import DetokenizeResponse
from .types.embed_input_type import EmbedInputType
from .types.embed_request_truncate import EmbedRequestTruncate
from .types.embed_response import EmbedResponse
from .types.embedding_type import EmbeddingType
from .types.gateway_timeout_error_body import GatewayTimeoutErrorBody
from .types.generate_request_return_likelihoods import GenerateRequestReturnLikelihoods
from .types.generate_request_truncate import GenerateRequestTruncate
from .types.generate_stream_request_return_likelihoods import GenerateStreamRequestReturnLikelihoods
from .types.generate_stream_request_truncate import GenerateStreamRequestTruncate
from .types.generate_streamed_response import GenerateStreamedResponse
from .types.generation import Generation
from .types.message import Message
from .types.non_streamed_chat_response import NonStreamedChatResponse
from .types.not_implemented_error_body import NotImplementedErrorBody
from .types.rerank_request_documents_item import RerankRequestDocumentsItem
from .types.rerank_response import RerankResponse
from .types.response_format import ResponseFormat
from .types.streamed_chat_response import StreamedChatResponse
from .types.summarize_request_extractiveness import SummarizeRequestExtractiveness
from .types.summarize_request_format import SummarizeRequestFormat
from .types.summarize_request_length import SummarizeRequestLength
from .types.summarize_response import SummarizeResponse
from .types.tokenize_response import TokenizeResponse
from .types.too_many_requests_error_body import TooManyRequestsErrorBody
from .types.tool import Tool
from .types.tool_result import ToolResult
from .types.unprocessable_entity_error_body import UnprocessableEntityErrorBody
from .v2.client import AsyncV2Client, V2Client
# this is used as the default value for optional parameters
OMIT = typing.cast(typing.Any, ...)
class BaseCohere:
"""
Use this class to access the different functions within the SDK. You can instantiate any number of clients with different configuration that will propagate to these functions.
Parameters
----------
base_url : typing.Optional[str]
The base url to use for requests from the client.
environment : ClientEnvironment
The environment to use for requests from the client. from .environment import ClientEnvironment
Defaults to ClientEnvironment.PRODUCTION
client_name : typing.Optional[str]
token : typing.Optional[typing.Union[str, typing.Callable[[], str]]]
timeout : typing.Optional[float]
The timeout to be used, in seconds, for requests. By default the timeout is 300 seconds, unless a custom httpx client is used, in which case this default is not enforced.
follow_redirects : typing.Optional[bool]
Whether the default httpx client follows redirects or not, this is irrelevant if a custom httpx client is passed in.
httpx_client : typing.Optional[httpx.Client]
The httpx client to use for making requests, a preconfigured client is used by default, however this is useful should you want to pass in any custom httpx configuration.
Examples
--------
from cohere.client import Client
client = Client(
client_name="YOUR_CLIENT_NAME",
token="YOUR_TOKEN",
)
"""
def __init__(
self,
*,
base_url: typing.Optional[str] = None,
environment: ClientEnvironment = ClientEnvironment.PRODUCTION,
client_name: typing.Optional[str] = None,
token: typing.Optional[typing.Union[str, typing.Callable[[], str]]] = os.getenv("CO_API_KEY"),
timeout: typing.Optional[float] = None,
follow_redirects: typing.Optional[bool] = True,
httpx_client: typing.Optional[httpx.Client] = None
):
_defaulted_timeout = timeout if timeout is not None else 300 if httpx_client is None else None
if token is None:
raise ApiError(body="The client must be instantiated be either passing in token or setting CO_API_KEY")
self._client_wrapper = SyncClientWrapper(
base_url=_get_base_url(base_url=base_url, environment=environment),
client_name=client_name,
token=token,
httpx_client=httpx_client
if httpx_client is not None
else httpx.Client(timeout=_defaulted_timeout, follow_redirects=follow_redirects)
if follow_redirects is not None
else httpx.Client(timeout=_defaulted_timeout),
timeout=_defaulted_timeout,
)
self.v2 = V2Client(client_wrapper=self._client_wrapper)
self.embed_jobs = EmbedJobsClient(client_wrapper=self._client_wrapper)
self.datasets = DatasetsClient(client_wrapper=self._client_wrapper)
self.connectors = ConnectorsClient(client_wrapper=self._client_wrapper)
self.models = ModelsClient(client_wrapper=self._client_wrapper)
self.finetuning = FinetuningClient(client_wrapper=self._client_wrapper)
def chat_stream(
self,
*,
message: str,
model: typing.Optional[str] = OMIT,
preamble: typing.Optional[str] = OMIT,
chat_history: typing.Optional[typing.Sequence[Message]] = OMIT,
conversation_id: typing.Optional[str] = OMIT,
prompt_truncation: typing.Optional[ChatStreamRequestPromptTruncation] = OMIT,
connectors: typing.Optional[typing.Sequence[ChatConnector]] = OMIT,
search_queries_only: typing.Optional[bool] = OMIT,
documents: typing.Optional[typing.Sequence[ChatDocument]] = OMIT,
citation_quality: typing.Optional[ChatStreamRequestCitationQuality] = OMIT,
temperature: typing.Optional[float] = OMIT,
max_tokens: typing.Optional[int] = OMIT,
max_input_tokens: typing.Optional[int] = OMIT,
k: typing.Optional[int] = OMIT,
p: typing.Optional[float] = OMIT,
seed: typing.Optional[int] = OMIT,
stop_sequences: typing.Optional[typing.Sequence[str]] = OMIT,
frequency_penalty: typing.Optional[float] = OMIT,
presence_penalty: typing.Optional[float] = OMIT,
raw_prompting: typing.Optional[bool] = OMIT,
return_prompt: typing.Optional[bool] = OMIT,
tools: typing.Optional[typing.Sequence[Tool]] = OMIT,
tool_results: typing.Optional[typing.Sequence[ToolResult]] = OMIT,
force_single_step: typing.Optional[bool] = OMIT,
response_format: typing.Optional[ResponseFormat] = OMIT,
request_options: typing.Optional[RequestOptions] = None
) -> typing.Iterator[StreamedChatResponse]:
"""
Generates a text response to a user message.
To learn how to use the Chat API with Streaming and RAG follow our [Text Generation guides](https://docs.cohere.com/docs/chat-api).
Parameters
----------
message : str
Text input for the model to respond to.
Compatible Deployments: Cohere Platform, Azure, AWS Sagemaker/Bedrock, Private Deployments
model : typing.Optional[str]
Defaults to `command-r-plus`.
The name of a compatible [Cohere model](https://docs.cohere.com/docs/models) or the ID of a [fine-tuned](https://docs.cohere.com/docs/chat-fine-tuning) model.
Compatible Deployments: Cohere Platform, Private Deployments
preamble : typing.Optional[str]
When specified, the default Cohere preamble will be replaced with the provided one. Preambles are a part of the prompt used to adjust the model's overall behavior and conversation style, and use the `SYSTEM` role.
The `SYSTEM` role is also used for the contents of the optional `chat_history=` parameter. When used with the `chat_history=` parameter it adds content throughout a conversation. Conversely, when used with the `preamble=` parameter it adds content at the start of the conversation only.
Compatible Deployments: Cohere Platform, Azure, AWS Sagemaker/Bedrock, Private Deployments
chat_history : typing.Optional[typing.Sequence[Message]]
A list of previous messages between the user and the model, giving the model conversational context for responding to the user's `message`.
Each item represents a single message in the chat history, excluding the current user turn. It has two properties: `role` and `message`. The `role` identifies the sender (`CHATBOT`, `SYSTEM`, or `USER`), while the `message` contains the text content.
The chat_history parameter should not be used for `SYSTEM` messages in most cases. Instead, to add a `SYSTEM` role message at the beginning of a conversation, the `preamble` parameter should be used.
Compatible Deployments: Cohere Platform, Azure, AWS Sagemaker/Bedrock, Private Deployments
conversation_id : typing.Optional[str]
An alternative to `chat_history`.
Providing a `conversation_id` creates or resumes a persisted conversation with the specified ID. The ID can be any non empty string.
Compatible Deployments: Cohere Platform
prompt_truncation : typing.Optional[ChatStreamRequestPromptTruncation]
Defaults to `AUTO` when `connectors` are specified and `OFF` in all other cases.
Dictates how the prompt will be constructed.
With `prompt_truncation` set to "AUTO", some elements from `chat_history` and `documents` will be dropped in an attempt to construct a prompt that fits within the model's context length limit. During this process the order of the documents and chat history will be changed and ranked by relevance.
With `prompt_truncation` set to "AUTO_PRESERVE_ORDER", some elements from `chat_history` and `documents` will be dropped in an attempt to construct a prompt that fits within the model's context length limit. During this process the order of the documents and chat history will be preserved as they are inputted into the API.
With `prompt_truncation` set to "OFF", no elements will be dropped. If the sum of the inputs exceeds the model's context length limit, a `TooManyTokens` error will be returned.
Compatible Deployments: Cohere Platform Only AUTO_PRESERVE_ORDER: Azure, AWS Sagemaker/Bedrock, Private Deployments
connectors : typing.Optional[typing.Sequence[ChatConnector]]
Accepts `{"id": "web-search"}`, and/or the `"id"` for a custom [connector](https://docs.cohere.com/docs/connectors), if you've [created](https://docs.cohere.com/docs/creating-and-deploying-a-connector) one.
When specified, the model's reply will be enriched with information found by querying each of the connectors (RAG).
Compatible Deployments: Cohere Platform
search_queries_only : typing.Optional[bool]
Defaults to `false`.
When `true`, the response will only contain a list of generated search queries, but no search will take place, and no reply from the model to the user's `message` will be generated.
Compatible Deployments: Cohere Platform, Azure, AWS Sagemaker/Bedrock, Private Deployments
documents : typing.Optional[typing.Sequence[ChatDocument]]
A list of relevant documents that the model can cite to generate a more accurate reply. Each document is a string-string dictionary.
Example:
`[
{ "title": "Tall penguins", "text": "Emperor penguins are the tallest." },
{ "title": "Penguin habitats", "text": "Emperor penguins only live in Antarctica." },
]`
Keys and values from each document will be serialized to a string and passed to the model. The resulting generation will include citations that reference some of these documents.
Some suggested keys are "text", "author", and "date". For better generation quality, it is recommended to keep the total word count of the strings in the dictionary to under 300 words.
An `id` field (string) can be optionally supplied to identify the document in the citations. This field will not be passed to the model.
An `_excludes` field (array of strings) can be optionally supplied to omit some key-value pairs from being shown to the model. The omitted fields will still show up in the citation object. The "_excludes" field will not be passed to the model.
See ['Document Mode'](https://docs.cohere.com/docs/retrieval-augmented-generation-rag#document-mode) in the guide for more information.
Compatible Deployments: Cohere Platform, Azure, AWS Sagemaker/Bedrock, Private Deployments
citation_quality : typing.Optional[ChatStreamRequestCitationQuality]
Defaults to `"accurate"`.
Dictates the approach taken to generating citations as part of the RAG flow by allowing the user to specify whether they want `"accurate"` results, `"fast"` results or no results.
Compatible Deployments: Cohere Platform, Azure, AWS Sagemaker/Bedrock, Private Deployments
temperature : typing.Optional[float]
Defaults to `0.3`.
A non-negative float that tunes the degree of randomness in generation. Lower temperatures mean less random generations, and higher temperatures mean more random generations.
Randomness can be further maximized by increasing the value of the `p` parameter.
Compatible Deployments: Cohere Platform, Azure, AWS Sagemaker/Bedrock, Private Deployments
max_tokens : typing.Optional[int]
The maximum number of tokens the model will generate as part of the response. Note: Setting a low value may result in incomplete generations.
Compatible Deployments: Cohere Platform, Azure, AWS Sagemaker/Bedrock, Private Deployments
max_input_tokens : typing.Optional[int]
The maximum number of input tokens to send to the model. If not specified, `max_input_tokens` is the model's context length limit minus a small buffer.
Input will be truncated according to the `prompt_truncation` parameter.
Compatible Deployments: Cohere Platform
k : typing.Optional[int]
Ensures only the top `k` most likely tokens are considered for generation at each step.
Defaults to `0`, min value of `0`, max value of `500`.
Compatible Deployments: Cohere Platform, Azure, AWS Sagemaker/Bedrock, Private Deployments
p : typing.Optional[float]
Ensures that only the most likely tokens, with total probability mass of `p`, are considered for generation at each step. If both `k` and `p` are enabled, `p` acts after `k`.
Defaults to `0.75`. min value of `0.01`, max value of `0.99`.
Compatible Deployments: Cohere Platform, Azure, AWS Sagemaker/Bedrock, Private Deployments
seed : typing.Optional[int]
If specified, the backend will make a best effort to sample tokens
deterministically, such that repeated requests with the same
seed and parameters should return the same result. However,
determinism cannot be totally guaranteed.
Compatible Deployments: Cohere Platform, Azure, AWS Sagemaker/Bedrock, Private Deployments
stop_sequences : typing.Optional[typing.Sequence[str]]
A list of up to 5 strings that the model will use to stop generation. If the model generates a string that matches any of the strings in the list, it will stop generating tokens and return the generated text up to that point not including the stop sequence.
Compatible Deployments: Cohere Platform, Azure, AWS Sagemaker/Bedrock, Private Deployments
frequency_penalty : typing.Optional[float]
Defaults to `0.0`, min value of `0.0`, max value of `1.0`.
Used to reduce repetitiveness of generated tokens. The higher the value, the stronger a penalty is applied to previously present tokens, proportional to how many times they have already appeared in the prompt or prior generation.
Compatible Deployments: Cohere Platform, Azure, AWS Sagemaker/Bedrock, Private Deployments
presence_penalty : typing.Optional[float]
Defaults to `0.0`, min value of `0.0`, max value of `1.0`.
Used to reduce repetitiveness of generated tokens. Similar to `frequency_penalty`, except that this penalty is applied equally to all tokens that have already appeared, regardless of their exact frequencies.
Compatible Deployments: Cohere Platform, Azure, AWS Sagemaker/Bedrock, Private Deployments
raw_prompting : typing.Optional[bool]
When enabled, the user's prompt will be sent to the model without
any pre-processing.
Compatible Deployments: Cohere Platform, Azure, AWS Sagemaker/Bedrock, Private Deployments
return_prompt : typing.Optional[bool]
The prompt is returned in the `prompt` response field when this is enabled.
tools : typing.Optional[typing.Sequence[Tool]]
A list of available tools (functions) that the model may suggest invoking before producing a text response.
When `tools` is passed (without `tool_results`), the `text` field in the response will be `""` and the `tool_calls` field in the response will be populated with a list of tool calls that need to be made. If no calls need to be made, the `tool_calls` array will be empty.
Compatible Deployments: Cohere Platform, Azure, AWS Sagemaker/Bedrock, Private Deployments
tool_results : typing.Optional[typing.Sequence[ToolResult]]
A list of results from invoking tools recommended by the model in the previous chat turn. Results are used to produce a text response and will be referenced in citations. When using `tool_results`, `tools` must be passed as well.
Each tool_result contains information about how it was invoked, as well as a list of outputs in the form of dictionaries.
**Note**: `outputs` must be a list of objects. If your tool returns a single object (eg `{"status": 200}`), make sure to wrap it in a list.
```
tool_results = [
{
"call": {
"name": <tool name>,
"parameters": {
<param name>: <param value>
}
},
"outputs": [{
<key>: <value>
}]
},
...
]
```
**Note**: Chat calls with `tool_results` should not be included in the Chat history to avoid duplication of the message text.
Compatible Deployments: Cohere Platform, Azure, AWS Sagemaker/Bedrock, Private Deployments
force_single_step : typing.Optional[bool]
Forces the chat to be single step. Defaults to `false`.
response_format : typing.Optional[ResponseFormat]
request_options : typing.Optional[RequestOptions]
Request-specific configuration.
Yields
------
typing.Iterator[StreamedChatResponse]
Examples
--------
from cohere import (
ChatConnector,
ChatStreamRequestConnectorsSearchOptions,
Message_Chatbot,
ResponseFormat_Text,
Tool,
ToolCall,
ToolParameterDefinitionsValue,
ToolResult,
)
from cohere.client import Client
client = Client(
client_name="YOUR_CLIENT_NAME",
token="YOUR_TOKEN",
)
response = client.chat_stream(
message="string",
model="string",
preamble="string",
chat_history=[
Message_Chatbot(
message="string",
tool_calls=[
ToolCall(
name="string",
parameters={"string": {"key": "value"}},
)
],
)
],
conversation_id="string",
prompt_truncation="OFF",
connectors=[
ChatConnector(
id="string",
user_access_token="string",
continue_on_failure=True,
options={"string": {"key": "value"}},
)
],
search_queries_only=True,
documents=[{"string": {"key": "value"}}],
citation_quality="fast",
temperature=1.1,
max_tokens=1,
max_input_tokens=1,
k=1,
p=1.1,
seed=1,
stop_sequences=["string"],
connectors_search_options=ChatStreamRequestConnectorsSearchOptions(
seed=1,
),
frequency_penalty=1.1,
presence_penalty=1.1,
raw_prompting=True,
return_prompt=True,
tools=[
Tool(
name="string",
description="string",
parameter_definitions={
"string": ToolParameterDefinitionsValue(
description="string",
type="string",
required=True,
)
},
)
],
tool_results=[
ToolResult(
call=ToolCall(
name="string",
parameters={"string": {"key": "value"}},
),
outputs=[{"string": {"key": "value"}}],
)
],
force_single_step=True,
response_format=ResponseFormat_Text(),
)
for chunk in response:
yield chunk
"""
with self._client_wrapper.httpx_client.stream(
"v1/chat",
method="POST",
json={
"message": message,
"model": model,
"preamble": preamble,
"chat_history": chat_history,
"conversation_id": conversation_id,
"prompt_truncation": prompt_truncation,
"connectors": connectors,
"search_queries_only": search_queries_only,
"documents": documents,
"citation_quality": citation_quality,
"temperature": temperature,
"max_tokens": max_tokens,
"max_input_tokens": max_input_tokens,
"k": k,
"p": p,
"seed": seed,
"stop_sequences": stop_sequences,
"frequency_penalty": frequency_penalty,
"presence_penalty": presence_penalty,
"raw_prompting": raw_prompting,
"return_prompt": return_prompt,
"tools": tools,
"tool_results": tool_results,
"force_single_step": force_single_step,
"response_format": response_format,
"stream": True,
},
request_options=request_options,
omit=OMIT,
) as _response:
try:
if 200 <= _response.status_code < 300:
for _text in _response.iter_lines():
try:
if len(_text) == 0:
continue
yield typing.cast(StreamedChatResponse, construct_type(type_=StreamedChatResponse, object_=json.loads(_text))) # type: ignore
except:
pass
return
_response.read()
if _response.status_code == 400:
raise BadRequestError(
typing.cast(typing.Any, construct_type(type_=typing.Any, object_=_response.json())) # type: ignore
)
if _response.status_code == 401:
raise UnauthorizedError(
typing.cast(typing.Any, construct_type(type_=typing.Any, object_=_response.json())) # type: ignore
)
if _response.status_code == 403:
raise ForbiddenError(
typing.cast(typing.Any, construct_type(type_=typing.Any, object_=_response.json())) # type: ignore
)
if _response.status_code == 404:
raise NotFoundError(
typing.cast(typing.Any, construct_type(type_=typing.Any, object_=_response.json())) # type: ignore
)
if _response.status_code == 422:
raise UnprocessableEntityError(
typing.cast(UnprocessableEntityErrorBody, construct_type(type_=UnprocessableEntityErrorBody, object_=_response.json())) # type: ignore
)
if _response.status_code == 429:
raise TooManyRequestsError(
typing.cast(TooManyRequestsErrorBody, construct_type(type_=TooManyRequestsErrorBody, object_=_response.json())) # type: ignore
)
if _response.status_code == 499:
raise ClientClosedRequestError(
typing.cast(ClientClosedRequestErrorBody, construct_type(type_=ClientClosedRequestErrorBody, object_=_response.json())) # type: ignore
)
if _response.status_code == 500:
raise InternalServerError(
typing.cast(typing.Any, construct_type(type_=typing.Any, object_=_response.json())) # type: ignore
)
if _response.status_code == 501:
raise NotImplementedError(
typing.cast(NotImplementedErrorBody, construct_type(type_=NotImplementedErrorBody, object_=_response.json())) # type: ignore
)
if _response.status_code == 503:
raise ServiceUnavailableError(
typing.cast(typing.Any, construct_type(type_=typing.Any, object_=_response.json())) # type: ignore
)
if _response.status_code == 504:
raise GatewayTimeoutError(
typing.cast(GatewayTimeoutErrorBody, construct_type(type_=GatewayTimeoutErrorBody, object_=_response.json())) # type: ignore
)
_response_json = _response.json()
except JSONDecodeError:
raise ApiError(status_code=_response.status_code, body=_response.text)
raise ApiError(status_code=_response.status_code, body=_response_json)
def chat(
self,
*,
message: str,
model: typing.Optional[str] = OMIT,
preamble: typing.Optional[str] = OMIT,
chat_history: typing.Optional[typing.Sequence[Message]] = OMIT,
conversation_id: typing.Optional[str] = OMIT,
prompt_truncation: typing.Optional[ChatRequestPromptTruncation] = OMIT,
connectors: typing.Optional[typing.Sequence[ChatConnector]] = OMIT,
search_queries_only: typing.Optional[bool] = OMIT,
documents: typing.Optional[typing.Sequence[ChatDocument]] = OMIT,
citation_quality: typing.Optional[ChatRequestCitationQuality] = OMIT,
temperature: typing.Optional[float] = OMIT,
max_tokens: typing.Optional[int] = OMIT,
max_input_tokens: typing.Optional[int] = OMIT,
k: typing.Optional[int] = OMIT,
p: typing.Optional[float] = OMIT,
seed: typing.Optional[int] = OMIT,
stop_sequences: typing.Optional[typing.Sequence[str]] = OMIT,
frequency_penalty: typing.Optional[float] = OMIT,
presence_penalty: typing.Optional[float] = OMIT,
raw_prompting: typing.Optional[bool] = OMIT,
return_prompt: typing.Optional[bool] = OMIT,
tools: typing.Optional[typing.Sequence[Tool]] = OMIT,
tool_results: typing.Optional[typing.Sequence[ToolResult]] = OMIT,
force_single_step: typing.Optional[bool] = OMIT,
response_format: typing.Optional[ResponseFormat] = OMIT,
request_options: typing.Optional[RequestOptions] = None
) -> NonStreamedChatResponse:
"""
Generates a text response to a user message.
To learn how to use the Chat API with Streaming and RAG follow our [Text Generation guides](https://docs.cohere.com/docs/chat-api).
Parameters
----------
message : str
Text input for the model to respond to.
Compatible Deployments: Cohere Platform, Azure, AWS Sagemaker/Bedrock, Private Deployments
model : typing.Optional[str]
Defaults to `command-r-plus`.
The name of a compatible [Cohere model](https://docs.cohere.com/docs/models) or the ID of a [fine-tuned](https://docs.cohere.com/docs/chat-fine-tuning) model.
Compatible Deployments: Cohere Platform, Private Deployments
preamble : typing.Optional[str]
When specified, the default Cohere preamble will be replaced with the provided one. Preambles are a part of the prompt used to adjust the model's overall behavior and conversation style, and use the `SYSTEM` role.
The `SYSTEM` role is also used for the contents of the optional `chat_history=` parameter. When used with the `chat_history=` parameter it adds content throughout a conversation. Conversely, when used with the `preamble=` parameter it adds content at the start of the conversation only.
Compatible Deployments: Cohere Platform, Azure, AWS Sagemaker/Bedrock, Private Deployments
chat_history : typing.Optional[typing.Sequence[Message]]
A list of previous messages between the user and the model, giving the model conversational context for responding to the user's `message`.
Each item represents a single message in the chat history, excluding the current user turn. It has two properties: `role` and `message`. The `role` identifies the sender (`CHATBOT`, `SYSTEM`, or `USER`), while the `message` contains the text content.
The chat_history parameter should not be used for `SYSTEM` messages in most cases. Instead, to add a `SYSTEM` role message at the beginning of a conversation, the `preamble` parameter should be used.
Compatible Deployments: Cohere Platform, Azure, AWS Sagemaker/Bedrock, Private Deployments
conversation_id : typing.Optional[str]
An alternative to `chat_history`.
Providing a `conversation_id` creates or resumes a persisted conversation with the specified ID. The ID can be any non empty string.
Compatible Deployments: Cohere Platform
prompt_truncation : typing.Optional[ChatRequestPromptTruncation]
Defaults to `AUTO` when `connectors` are specified and `OFF` in all other cases.
Dictates how the prompt will be constructed.
With `prompt_truncation` set to "AUTO", some elements from `chat_history` and `documents` will be dropped in an attempt to construct a prompt that fits within the model's context length limit. During this process the order of the documents and chat history will be changed and ranked by relevance.
With `prompt_truncation` set to "AUTO_PRESERVE_ORDER", some elements from `chat_history` and `documents` will be dropped in an attempt to construct a prompt that fits within the model's context length limit. During this process the order of the documents and chat history will be preserved as they are inputted into the API.
With `prompt_truncation` set to "OFF", no elements will be dropped. If the sum of the inputs exceeds the model's context length limit, a `TooManyTokens` error will be returned.
Compatible Deployments: Cohere Platform Only AUTO_PRESERVE_ORDER: Azure, AWS Sagemaker/Bedrock, Private Deployments
connectors : typing.Optional[typing.Sequence[ChatConnector]]
Accepts `{"id": "web-search"}`, and/or the `"id"` for a custom [connector](https://docs.cohere.com/docs/connectors), if you've [created](https://docs.cohere.com/docs/creating-and-deploying-a-connector) one.
When specified, the model's reply will be enriched with information found by querying each of the connectors (RAG).
Compatible Deployments: Cohere Platform
search_queries_only : typing.Optional[bool]
Defaults to `false`.
When `true`, the response will only contain a list of generated search queries, but no search will take place, and no reply from the model to the user's `message` will be generated.
Compatible Deployments: Cohere Platform, Azure, AWS Sagemaker/Bedrock, Private Deployments
documents : typing.Optional[typing.Sequence[ChatDocument]]
A list of relevant documents that the model can cite to generate a more accurate reply. Each document is a string-string dictionary.
Example:
`[
{ "title": "Tall penguins", "text": "Emperor penguins are the tallest." },
{ "title": "Penguin habitats", "text": "Emperor penguins only live in Antarctica." },
]`
Keys and values from each document will be serialized to a string and passed to the model. The resulting generation will include citations that reference some of these documents.
Some suggested keys are "text", "author", and "date". For better generation quality, it is recommended to keep the total word count of the strings in the dictionary to under 300 words.
An `id` field (string) can be optionally supplied to identify the document in the citations. This field will not be passed to the model.
An `_excludes` field (array of strings) can be optionally supplied to omit some key-value pairs from being shown to the model. The omitted fields will still show up in the citation object. The "_excludes" field will not be passed to the model.
See ['Document Mode'](https://docs.cohere.com/docs/retrieval-augmented-generation-rag#document-mode) in the guide for more information.
Compatible Deployments: Cohere Platform, Azure, AWS Sagemaker/Bedrock, Private Deployments
citation_quality : typing.Optional[ChatRequestCitationQuality]
Defaults to `"accurate"`.
Dictates the approach taken to generating citations as part of the RAG flow by allowing the user to specify whether they want `"accurate"` results, `"fast"` results or no results.
Compatible Deployments: Cohere Platform, Azure, AWS Sagemaker/Bedrock, Private Deployments
temperature : typing.Optional[float]
Defaults to `0.3`.
A non-negative float that tunes the degree of randomness in generation. Lower temperatures mean less random generations, and higher temperatures mean more random generations.
Randomness can be further maximized by increasing the value of the `p` parameter.
Compatible Deployments: Cohere Platform, Azure, AWS Sagemaker/Bedrock, Private Deployments
max_tokens : typing.Optional[int]
The maximum number of tokens the model will generate as part of the response. Note: Setting a low value may result in incomplete generations.
Compatible Deployments: Cohere Platform, Azure, AWS Sagemaker/Bedrock, Private Deployments
max_input_tokens : typing.Optional[int]
The maximum number of input tokens to send to the model. If not specified, `max_input_tokens` is the model's context length limit minus a small buffer.
Input will be truncated according to the `prompt_truncation` parameter.
Compatible Deployments: Cohere Platform
k : typing.Optional[int]
Ensures only the top `k` most likely tokens are considered for generation at each step.
Defaults to `0`, min value of `0`, max value of `500`.
Compatible Deployments: Cohere Platform, Azure, AWS Sagemaker/Bedrock, Private Deployments
p : typing.Optional[float]
Ensures that only the most likely tokens, with total probability mass of `p`, are considered for generation at each step. If both `k` and `p` are enabled, `p` acts after `k`.
Defaults to `0.75`. min value of `0.01`, max value of `0.99`.
Compatible Deployments: Cohere Platform, Azure, AWS Sagemaker/Bedrock, Private Deployments
seed : typing.Optional[int]
If specified, the backend will make a best effort to sample tokens
deterministically, such that repeated requests with the same
seed and parameters should return the same result. However,
determinism cannot be totally guaranteed.
Compatible Deployments: Cohere Platform, Azure, AWS Sagemaker/Bedrock, Private Deployments
stop_sequences : typing.Optional[typing.Sequence[str]]
A list of up to 5 strings that the model will use to stop generation. If the model generates a string that matches any of the strings in the list, it will stop generating tokens and return the generated text up to that point not including the stop sequence.
Compatible Deployments: Cohere Platform, Azure, AWS Sagemaker/Bedrock, Private Deployments
frequency_penalty : typing.Optional[float]
Defaults to `0.0`, min value of `0.0`, max value of `1.0`.
Used to reduce repetitiveness of generated tokens. The higher the value, the stronger a penalty is applied to previously present tokens, proportional to how many times they have already appeared in the prompt or prior generation.
Compatible Deployments: Cohere Platform, Azure, AWS Sagemaker/Bedrock, Private Deployments
presence_penalty : typing.Optional[float]
Defaults to `0.0`, min value of `0.0`, max value of `1.0`.
Used to reduce repetitiveness of generated tokens. Similar to `frequency_penalty`, except that this penalty is applied equally to all tokens that have already appeared, regardless of their exact frequencies.
Compatible Deployments: Cohere Platform, Azure, AWS Sagemaker/Bedrock, Private Deployments
raw_prompting : typing.Optional[bool]
When enabled, the user's prompt will be sent to the model without
any pre-processing.
Compatible Deployments: Cohere Platform, Azure, AWS Sagemaker/Bedrock, Private Deployments
return_prompt : typing.Optional[bool]
The prompt is returned in the `prompt` response field when this is enabled.
tools : typing.Optional[typing.Sequence[Tool]]
A list of available tools (functions) that the model may suggest invoking before producing a text response.
When `tools` is passed (without `tool_results`), the `text` field in the response will be `""` and the `tool_calls` field in the response will be populated with a list of tool calls that need to be made. If no calls need to be made, the `tool_calls` array will be empty.
Compatible Deployments: Cohere Platform, Azure, AWS Sagemaker/Bedrock, Private Deployments
tool_results : typing.Optional[typing.Sequence[ToolResult]]
A list of results from invoking tools recommended by the model in the previous chat turn. Results are used to produce a text response and will be referenced in citations. When using `tool_results`, `tools` must be passed as well.
Each tool_result contains information about how it was invoked, as well as a list of outputs in the form of dictionaries.
**Note**: `outputs` must be a list of objects. If your tool returns a single object (eg `{"status": 200}`), make sure to wrap it in a list.
```
tool_results = [
{
"call": {
"name": <tool name>,
"parameters": {
<param name>: <param value>
}
},
"outputs": [{
<key>: <value>
}]
},
...
]
```
**Note**: Chat calls with `tool_results` should not be included in the Chat history to avoid duplication of the message text.
Compatible Deployments: Cohere Platform, Azure, AWS Sagemaker/Bedrock, Private Deployments
force_single_step : typing.Optional[bool]
Forces the chat to be single step. Defaults to `false`.
response_format : typing.Optional[ResponseFormat]
request_options : typing.Optional[RequestOptions]
Request-specific configuration.
Returns
-------
NonStreamedChatResponse
Examples
--------
from cohere.client import Client
client = Client(
client_name="YOUR_CLIENT_NAME",
token="YOUR_TOKEN",
)
client.chat(
message="Can you give me a global market overview of solar panels?",
prompt_truncation="OFF",
temperature=0.3,
)
"""
_response = self._client_wrapper.httpx_client.request(
"v1/chat",
method="POST",
json={
"message": message,
"model": model,
"preamble": preamble,
"chat_history": chat_history,
"conversation_id": conversation_id,
"prompt_truncation": prompt_truncation,
"connectors": connectors,
"search_queries_only": search_queries_only,
"documents": documents,
"citation_quality": citation_quality,
"temperature": temperature,
"max_tokens": max_tokens,
"max_input_tokens": max_input_tokens,
"k": k,
"p": p,
"seed": seed,
"stop_sequences": stop_sequences,
"frequency_penalty": frequency_penalty,
"presence_penalty": presence_penalty,
"raw_prompting": raw_prompting,
"return_prompt": return_prompt,
"tools": tools,
"tool_results": tool_results,
"force_single_step": force_single_step,
"response_format": response_format,
"stream": False,
},
request_options=request_options,
omit=OMIT,
)
try:
if 200 <= _response.status_code < 300:
return typing.cast(NonStreamedChatResponse, construct_type(type_=NonStreamedChatResponse, object_=_response.json())) # type: ignore
if _response.status_code == 400:
raise BadRequestError(
typing.cast(typing.Any, construct_type(type_=typing.Any, object_=_response.json())) # type: ignore
)
if _response.status_code == 401:
raise UnauthorizedError(
typing.cast(typing.Any, construct_type(type_=typing.Any, object_=_response.json())) # type: ignore
)
if _response.status_code == 403:
raise ForbiddenError(
typing.cast(typing.Any, construct_type(type_=typing.Any, object_=_response.json())) # type: ignore
)
if _response.status_code == 404:
raise NotFoundError(
typing.cast(typing.Any, construct_type(type_=typing.Any, object_=_response.json())) # type: ignore
)
if _response.status_code == 422:
raise UnprocessableEntityError(
typing.cast(UnprocessableEntityErrorBody, construct_type(type_=UnprocessableEntityErrorBody, object_=_response.json())) # type: ignore
)
if _response.status_code == 429:
raise TooManyRequestsError(
typing.cast(TooManyRequestsErrorBody, construct_type(type_=TooManyRequestsErrorBody, object_=_response.json())) # type: ignore
)
if _response.status_code == 499:
raise ClientClosedRequestError(
typing.cast(ClientClosedRequestErrorBody, construct_type(type_=ClientClosedRequestErrorBody, object_=_response.json())) # type: ignore
)
if _response.status_code == 500:
raise InternalServerError(
typing.cast(typing.Any, construct_type(type_=typing.Any, object_=_response.json())) # type: ignore
)
if _response.status_code == 501:
raise NotImplementedError(
typing.cast(NotImplementedErrorBody, construct_type(type_=NotImplementedErrorBody, object_=_response.json())) # type: ignore
)
if _response.status_code == 503:
raise ServiceUnavailableError(
typing.cast(typing.Any, construct_type(type_=typing.Any, object_=_response.json())) # type: ignore
)
if _response.status_code == 504:
raise GatewayTimeoutError(
typing.cast(GatewayTimeoutErrorBody, construct_type(type_=GatewayTimeoutErrorBody, object_=_response.json())) # type: ignore
)
_response_json = _response.json()
except JSONDecodeError:
raise ApiError(status_code=_response.status_code, body=_response.text)
raise ApiError(status_code=_response.status_code, body=_response_json)
def generate_stream(
self,
*,
prompt: str,
model: typing.Optional[str] = OMIT,
num_generations: typing.Optional[int] = OMIT,
max_tokens: typing.Optional[int] = OMIT,
truncate: typing.Optional[GenerateStreamRequestTruncate] = OMIT,
temperature: typing.Optional[float] = OMIT,
seed: typing.Optional[int] = OMIT,
preset: typing.Optional[str] = OMIT,
end_sequences: typing.Optional[typing.Sequence[str]] = OMIT,
stop_sequences: typing.Optional[typing.Sequence[str]] = OMIT,
k: typing.Optional[int] = OMIT,
p: typing.Optional[float] = OMIT,
frequency_penalty: typing.Optional[float] = OMIT,
presence_penalty: typing.Optional[float] = OMIT,
return_likelihoods: typing.Optional[GenerateStreamRequestReturnLikelihoods] = OMIT,
raw_prompting: typing.Optional[bool] = OMIT,
request_options: typing.Optional[RequestOptions] = None
) -> typing.Iterator[GenerateStreamedResponse]:
"""
> 🚧 Warning
>
> This API is marked as "Legacy" and is no longer maintained. Follow the [migration guide](/docs/migrating-from-cogenerate-to-cochat) to start using the Chat API.
Generates realistic text conditioned on a given input.
Parameters
----------
prompt : str
The input text that serves as the starting point for generating the response.
Note: The prompt will be pre-processed and modified before reaching the model.
model : typing.Optional[str]
The identifier of the model to generate with. Currently available models are `command` (default), `command-nightly` (experimental), `command-light`, and `command-light-nightly` (experimental).
Smaller, "light" models are faster, while larger models will perform better. [Custom models](/docs/training-custom-models) can also be supplied with their full ID.
num_generations : typing.Optional[int]
The maximum number of generations that will be returned. Defaults to `1`, min value of `1`, max value of `5`.
max_tokens : typing.Optional[int]
The maximum number of tokens the model will generate as part of the response. Note: Setting a low value may result in incomplete generations.
This parameter is off by default, and if it's not specified, the model will continue generating until it emits an EOS completion token. See [BPE Tokens](/bpe-tokens-wiki) for more details.
Can only be set to `0` if `return_likelihoods` is set to `ALL` to get the likelihood of the prompt.
truncate : typing.Optional[GenerateStreamRequestTruncate]
One of `NONE|START|END` to specify how the API will handle inputs longer than the maximum token length.
Passing `START` will discard the start of the input. `END` will discard the end of the input. In both cases, input is discarded until the remaining input is exactly the maximum input token length for the model.
If `NONE` is selected, when the input exceeds the maximum input token length an error will be returned.
temperature : typing.Optional[float]
A non-negative float that tunes the degree of randomness in generation. Lower temperatures mean less random generations. See [Temperature](/temperature-wiki) for more details.
Defaults to `0.75`, min value of `0.0`, max value of `5.0`.
seed : typing.Optional[int]
If specified, the backend will make a best effort to sample tokens
deterministically, such that repeated requests with the same
seed and parameters should return the same result. However,
determinism cannot be totally guaranteed.
Compatible Deployments: Cohere Platform, Azure, AWS Sagemaker/Bedrock, Private Deployments
preset : typing.Optional[str]
Identifier of a custom preset. A preset is a combination of parameters, such as prompt, temperature etc. You can create presets in the [playground](https://dashboard.cohere.com/playground/generate).
When a preset is specified, the `prompt` parameter becomes optional, and any included parameters will override the preset's parameters.
end_sequences : typing.Optional[typing.Sequence[str]]
The generated text will be cut at the beginning of the earliest occurrence of an end sequence. The sequence will be excluded from the text.
stop_sequences : typing.Optional[typing.Sequence[str]]
The generated text will be cut at the end of the earliest occurrence of a stop sequence. The sequence will be included the text.
k : typing.Optional[int]
Ensures only the top `k` most likely tokens are considered for generation at each step.
Defaults to `0`, min value of `0`, max value of `500`.
p : typing.Optional[float]
Ensures that only the most likely tokens, with total probability mass of `p`, are considered for generation at each step. If both `k` and `p` are enabled, `p` acts after `k`.
Defaults to `0.75`. min value of `0.01`, max value of `0.99`.