Cohere API 之旅

Cohere API之旅

  • 0. 背景
  • 1. Cohere提供的模型和函数
  • 2. Cohere 客户端
  • 3. Co.Generate API
  • 4. Co.Embed API
  • 5. Co.Classify API
  • 6. Co.Tokenize API
  • 7. Co.Detokenize API
  • 8. Co.Detect_language
  • 9. Co.Summarize API
  • 10. Co.Rerank API

0. 背景

大约两个月前有一份新闻稿。

https://www.oracle.com/news/announcement/oracle-to-deliver-powerful-and-secure-generative-ai-service-for-business-2023-06-13/

Oracle 计划与为企业提供人工智能平台的 Cohere 合作,在 OCI 上提供新的生成式人工智能服务。

请注意,对于可以免费使用的试用密钥,严格设置了速率限制和执行总数。

Trial Key Limitations

1. Cohere提供的模型和函数

  • Command

    • 提供文本生成模型
    • 学会遵循用户命令
  • Embeddings

    • 提供 Embedding 模型
    • 多言语対応

此外,所提供的功能在 API 参考中进行了描述,但除非在某些等待列表中注册才能使用的功能除外。

API endpoint概述
/generate给定输入,生成真实文本并返回
/embed对文本进行 Embedding 并返回浮点列表
/classify判断哪个标签与输入文本匹配并返回结果
/tokenize将输入文本转换分为 token 并返回结果
/detokenize接收 BPE(byte-pair encoding)token 并返回其文本表示形式
/detect-language识别输入文本是用哪种语言编写的并返回结果
/summarize为输入文本创建英文摘要并返回结果
/rerank接受查询和文本列表,生成并返回一个有序数组,其中每个文本都分配有一个关联的分数

2. Cohere 客户端

Cohere 还有一个异步客户端,但这次我们将使用同步客户端,因为我们只是测试功能。

代码示例,

import cohere
api_key = '<your-api-key>'co = cohere.Client(api_key)
co.check_api_key()

3. Co.Generate API

仅指定最少的必要参数并尝试执行。

示例代码,

res_generate = co.generate(prompt='Hello, how'
)print(res_generate)

输出结果,

[cohere.Generation {id: 905bc1fa-cb5a-4082-b1d8-2704d426956bprompt: Hello, howtext:  How can I help you?likelihood: Nonefinish_reason: Nonetoken_likelihoods: None
}]

它生成了文本 “How can I help you?”?

还有其他参数允许您选择模型(model)、要生成的文本数量、文本中的最大标记数量等等。以下是我尝试过的一些示例。

示例:使用 Nightly 版本生成 3 个包含最多 50 个标记的文本

示例代码,

res_generate = co.generate(prompt='Hello, how',model='command-nightly',num_generations=3,max_tokens=50
)print(res_generate)

输出结果,

[cohere.Generation {id: 8eca3fb0-9a9b-4df2-997d-e5fba22ebfbbprompt: Hello, howtext:  can I help you?likelihood: Nonefinish_reason: Nonetoken_likelihoods: None
}, cohere.Generation {id: 2b5d7382-64cb-48a8-8bb0-33c574565defprompt: Hello, howtext:  Hello! I'm a chatbot trained to be helpful and harmless. How can I assist you today?likelihood: Nonefinish_reason: Nonetoken_likelihoods: None
}, cohere.Generation {id: 060903ac-241f-4a9f-bd46-32de661a0799prompt: Hello, howtext:  are you doing today?likelihood: Nonefinish_reason: Nonetoken_likelihoods: None
}]

示例:仅考虑前 5 个最可能的标记 (k=5) 进行生成并最大化生成中的随机性 (temperature=5.0)

示例代码,

res_generate = co.generate(prompt='Hello, how',model='command-nightly',num_generations=3,max_tokens=50,k=5,temperature=5.0
)print(res_generate)

输出结果,

[cohere.Generation {id: 55f7482c-70ef-4846-be70-34af13df268aprompt: Hello, howtext:  are you ?likelihood: Nonefinish_reason: Nonetoken_likelihoods: None
}, cohere.Generation {id: d9286b01-bd12-4563-839b-6cf867f69873prompt: Hello, howtext:  I’d like to thank the user.  Is this how they would prefer me to address them?  If so I can change that to their username.
How may I be of service?  If I can help with any tasks Ilikelihood: Nonefinish_reason: Nonetoken_likelihoods: None
}, cohere.Generation {id: 6a2472a8-2663-4b83-a988-f164d1254707prompt: Hello, howtext:  can I help you with something, or provide any assistance?likelihood: Nonefinish_reason: Nonetoken_likelihoods: None
}]

示例:以 JSON 流的形式接收生成的结果(对于增量呈现响应内容的 UI 似乎很有用)

示例代码,

res_generate_streaming = co.generate(prompt='Hello, how',stream=True
)for index, token in enumerate(res_generate_streaming):print(f"{index}: {token}")res_generate_streaming.texts

输出结果,

0: StreamingText(index=0, text=' Hello', is_finished=False)
1: StreamingText(index=0, text='!', is_finished=False)
2: StreamingText(index=0, text=' How', is_finished=False)
3: StreamingText(index=0, text=' can', is_finished=False)
4: StreamingText(index=0, text=' I', is_finished=False)
5: StreamingText(index=0, text=' help', is_finished=False)
6: StreamingText(index=0, text=' you', is_finished=False)
7: StreamingText(index=0, text=' today', is_finished=False)
8: StreamingText(index=0, text='?', is_finished=False)
[' Hello! How can I help you today?']

其他详细信息请参阅API参考 - Co.Generate。

4. Co.Embed API

仅指定最少的必要参数并尝试执行。

示例代码,

res_embed = co.embed(texts=['hello', 'world']
)print(res_embed)

输出结果(部分省略),

cohere.Embeddings {embeddings: [[1.6142578, 0.24841309, 0.5385742, -1.6630859, -0.27783203, 0.35888672, 1.3378906, -1.8261719, 0.89404297, 1.0791016, 1.0566406, 1.0664062, 0.20983887, ... , -2.4160156, 0.22875977, -0.21594238]]compressed_embeddings: []meta: {'api_version': {'version': '1'}}
}

返回嵌入的结果。另外,在Embedding函数中,可以将要使用的模型指定为参数。

示例:尝试使用轻型版本模型 (model=embed-english-light-v2.0)

示例代码,

res_embed = co.embed(texts=['hello', 'world'],model='embed-english-light-v2.0'
)print(res_embed)

输出结果(部分省略),

cohere.Embeddings {embeddings: [[-0.16577148, -1.2109375, 0.54003906, -1.7148438, -1.5869141, 0.60839844, 0.6328125, 1.3974609, -0.49658203, -0.73046875, -1.796875, 1.5410156, 0.66064453, 0.9448242, -0.53515625, 0.24914551, 0.53222656, 0.23425293, 0.52685547, -1.3935547, 0.04095459, 0.8569336, -0.5620117, -0.42211914, 0.55371094, 3.5820312, 7.2890625, -1.2539062, 1.3583984, 0.12988281, -1.1660156, 0.124816895, ... ,0.87060547, 1.0205078, 0.5854492, -2.734375, -0.066589355, 1.8349609, 0.16430664, -0.26220703, -1.0625]]compressed_embeddings: []meta: {'api_version': {'version': '1'}}
}

示例:尝试使用多语言模型 (model=embed-multilingual-v2.0)

示例代码,

res_embed = co.embed(texts=['こんにちは', '世界'],model='embed-multilingual-v2.0'
)print(res_embed)

输出结果(部分省略),

cohere.Embeddings {embeddings: [[0.2590332, 0.41308594, 0.24279785, 0.30371094, 0.04647827, 0.1361084, 0.41357422, -0.40063477, 0.2553711, 0.17749023, -0.1899414, -0.041900635, 0.20141602, 0.43017578, -0.5878906, 0.18054199, 0.42333984, 0.010749817, -0.56640625, 0.1517334, 0.14282227, 0.36767578, 0.26953125, 0.1418457, 0.28051758, 0.1661377, -0.13293457, 0.23620605, 0.08703613, 0.36914062, 0.22180176, ... ,0.027786255, -0.18530273, -0.24414062, 0.123168945, 0.6425781, 0.08831787, -0.21862793, -0.18237305, -0.031341553]]compressed_embeddings: []meta: {'api_version': {'version': '1'}}
}

其他详细信息请参阅 API 参考 - Co.Embed。

5. Co.Classify API

仅指定最少的必要参数并尝试执行。

示例代码,

from cohere.responses.classify import Exampleexamples=[Example("Dermatologists don't like her!", "Spam"),Example("'Hello, open to this?'", "Spam"),Example("I need help please wire me $1000 right now", "Spam"),Example("Nice to know you ;)", "Spam"),Example("Please help me?", "Spam"),Example("Your parcel will be delivered today", "Not spam"),Example("Review changes to our Terms and Conditions", "Not spam"),Example("Weekly sync notes", "Not spam"),Example("'Re: Follow up from today's meeting'", "Not spam"),Example("Pre-read for tomorrow", "Not spam"),
]inputs=["Confirm your email address","hey i need u to send some $",
]res_classify = co.classify(inputs=inputs,examples=examples,
)print(res_classify)

输出结果,

[Classification<prediction: "Not spam", confidence: 0.5661598, labels: {'Not spam': LabelPrediction(confidence=0.5661598), 'Spam': LabelPrediction(confidence=0.43384025)}>, Classification<prediction: "Spam", confidence: 0.9909811, labels: {'Not spam': LabelPrediction(confidence=0.009018883), 'Spam': LabelPrediction(confidence=0.9909811)}>]

“Confirm your email address”,可能是垃圾邮件,也可能不是垃圾邮件,因此 Not spam: 0.56…, Spam: 0.43… 似乎合适。
“hey i need u to send some $”,听起来很垃圾邮件,但确实如此( Spam: 0.99, Not spam: 0.009 )。

在分类函数中,您可以指定其他参数来指定模型和截断(如何处理长于最大标记长度的输入)。

示例:当传递的输入长度超过轻量级模型 (model=embed-english-light-v2.0) 中的最大令牌长度时,返回错误 (truncate=NONE)

示例代码,

inputs_max_exceeded=["Confirm your email address","hey i need u to send some $","Please sign the receipt attached for the arrival of new office facilities.","Attached is the paper concerning with the cancellation of your current credit card.","The monthly financial statement is attached within the email.","The audit report you inquired is attached in the mail. Please review and transfer it to the related department.","There is a message for you from 01478719696, on 2016/08/23 18:26:30. You might want to check it when you get a chance.Thanks!","Dear John, I am attaching the mortgage documents relating to your department. They need to be signed in urgent manner.","This email/fax transmission is confidential and intended solely for the person or organisation to whom it is addressed. If you are not the intended recipient, you must not copy, distribute or disseminate the information, or take any action in reliance of it. Any views expressed in this message are those of the individual sender, except where the sender specifically states them to be the views of any organisation or employer. If you have received this message in error, do not open any attachment but please notify the sender (above) deleting this message from your system. For email transmissions please rely on your own virus check no responsibility is taken by the sender for any damage rising out of any bug or virus infection.","Sent with Genius Scan for iOS. http://bit.ly/download-genius-scan","Hey John, as you requested, attached is the paycheck for your next month?s salary in advance.","I am sending you the flight tickets for your business conference abroad next month. Please see the attached and note the date and time.","Attached is the bank transactions made from the company during last month. Please file these transactions into financial record.","example.com SV9100 InMail","Attached file is scanned image in PDF format. Use Acrobat(R)Reader(R) or Adobe(R)Reader(R) of Adobe Systems Incorporated to view the document. Adobe(R)Reader(R) can be downloaded from the following URL: Adobe, the Adobe logo, Acrobat, the Adobe PDF logo, and Reader are registered trademarks or trademarks of Adobe Systems Incorporated in the United States and other countries.","Here is the travel expense sheet for your upcoming company field trip. Please write down the approximate costs in the attachment.","Attached is the list of old office facilities that need to be replaced. Please copy the list into the purchase order form.","We are sending you the credit card receipt from yesterday. Please match the card number and amount.","Queries to: <scanner@example.com","Please find our invoice attached.","Hello! We are looking for employees working remotely. My name is Margaret, I am the personnel manager of a large International company. Most of the work you can do from home, that is, at a distance. Salary is $3000-$6000. If you are interested in this offer, please visit","Please see the attached copy of the report.","Attached is a pdf file containing items that have shipped. Please contact us if there are any questions or further assistance we can provide","Please see the attached license and send it to the head office.","Please find attached documents as requested.","We are looking for employees working remotely. My name is Enid, I am the personnel manager of a large International company. Most of the work you can do from home, that is, at a distance. Salary is $2000-$5400. If you are interested in this offer, please visit","Your item #123456789 has been sent to you by carrier. He will arrive to youon 23th of September, 2016 at noon.","Dear John, we are very sorry to inform you that the item you requested is out of stock. Here is the list of items similar to the ones you requested. Please take a look and let us know if you would like to substitute with any of them.","Thank you for your order! Please find your final sales receipt attached to this email. Your USPS Tracking Number is: 123456789. This order will ship tomorrow and you should be able to begin tracking tomorrow evening after it is picked up. If you have any questions or experience any problems, please let us know so we can assist you. Thanks again and enjoy! Thanks,","Thanks for using electronic billing. Please find your document attached","Dear John, I attached the clients’ accounts for your next operation. Please look through them and collect their data. I expect to hear from you soon.","You are receiving this email because the company has assigned you as part of the approval team. Please review the attached proposal form and make your approval decision. If you have any problem regarding the submission, please contact Gonzalo.","this is to inform you that your Debit Card is temporarily blocked as there were unknown transactions made today. We attached the scan of transactions. Please confirm whether you made these transactions.","The letter is attached. Please review his concerns carefully and reply him as soon as possible. King regards,","Confirm your email address","hey i need u to send some $","Please sign the receipt attached for the arrival of new office facilities.","Attached is the paper concerning with the cancellation of your current credit card.","The monthly financial statement is attached within the email.","The audit report you inquired is attached in the mail. Please review and transfer it to the related department.","There is a message for you from 01478719696, on 2016/08/23 18:26:30. You might want to check it when you get a chance.Thanks!","Dear John, I am attaching the mortgage documents relating to your department. They need to be signed in urgent manner.","This email/fax transmission is confidential and intended solely for the person or organisation to whom it is addressed. If you are not the intended recipient, you must not copy, distribute or disseminate the information, or take any action in reliance of it. Any views expressed in this message are those of the individual sender, except where the sender specifically states them to be the views of any organisation or employer. If you have received this message in error, do not open any attachment but please notify the sender (above) deleting this message from your system. For email transmissions please rely on your own virus check no responsibility is taken by the sender for any damage rising out of any bug or virus infection.","Sent with Genius Scan for iOS. http://bit.ly/download-genius-scan","Hey John, as you requested, attached is the paycheck for your next month?s salary in advance.","I am sending you the flight tickets for your business conference abroad next month. Please see the attached and note the date and time.","Attached is the bank transactions made from the company during last month. Please file these transactions into financial record.","example.com SV9100 InMail","Attached file is scanned image in PDF format. Use Acrobat(R)Reader(R) or Adobe(R)Reader(R) of Adobe Systems Incorporated to view the document. Adobe(R)Reader(R) can be downloaded from the following URL: Adobe, the Adobe logo, Acrobat, the Adobe PDF logo, and Reader are registered trademarks or trademarks of Adobe Systems Incorporated in the United States and other countries.","Here is the travel expense sheet for your upcoming company field trip. Please write down the approximate costs in the attachment.","Attached is the list of old office facilities that need to be replaced. Please copy the list into the purchase order form.","We are sending you the credit card receipt from yesterday. Please match the card number and amount.","Queries to: <scanner@example.com","Please find our invoice attached.","Hello! We are looking for employees working remotely. My name is Margaret, I am the personnel manager of a large International company. Most of the work you can do from home, that is, at a distance. Salary is $3000-$6000. If you are interested in this offer, please visit","Please see the attached copy of the report.","Attached is a pdf file containing items that have shipped. Please contact us if there are any questions or further assistance we can provide","Please see the attached license and send it to the head office.","Please find attached documents as requested.","We are looking for employees working remotely. My name is Enid, I am the personnel manager of a large International company. Most of the work you can do from home, that is, at a distance. Salary is $2000-$5400. If you are interested in this offer, please visit","Your item #123456789 has been sent to you by carrier. He will arrive to youon 23th of September, 2016 at noon.","Dear John, we are very sorry to inform you that the item you requested is out of stock. Here is the list of items similar to the ones you requested. Please take a look and let us know if you would like to substitute with any of them.","Thank you for your order! Please find your final sales receipt attached to this email. Your USPS Tracking Number is: 123456789. This order will ship tomorrow and you should be able to begin tracking tomorrow evening after it is picked up. If you have any questions or experience any problems, please let us know so we can assist you. Thanks again and enjoy! Thanks,","Thanks for using electronic billing. Please find your document attached","Dear John, I attached the clients’ accounts for your next operation. Please look through them and collect their data. I expect to hear from you soon.","You are receiving this email because the company has assigned you as part of the approval team. Please review the attached proposal form and make your approval decision. If you have any problem regarding the submission, please contact Gonzalo.","this is to inform you that your Debit Card is temporarily blocked as there were unknown transactions made today. We attached the scan of transactions. Please confirm whether you made these transactions.","The letter is attached. Please review his concerns carefully and reply him as soon as possible. King regards,","Confirm your email address","hey i need u to send some $","Please sign the receipt attached for the arrival of new office facilities.","Attached is the paper concerning with the cancellation of your current credit card.","The monthly financial statement is attached within the email.","The audit report you inquired is attached in the mail. Please review and transfer it to the related department.","There is a message for you from 01478719696, on 2016/08/23 18:26:30. You might want to check it when you get a chance.Thanks!","Dear John, I am attaching the mortgage documents relating to your department. They need to be signed in urgent manner.","This email/fax transmission is confidential and intended solely for the person or organisation to whom it is addressed. If you are not the intended recipient, you must not copy, distribute or disseminate the information, or take any action in reliance of it. Any views expressed in this message are those of the individual sender, except where the sender specifically states them to be the views of any organisation or employer. If you have received this message in error, do not open any attachment but please notify the sender (above) deleting this message from your system. For email transmissions please rely on your own virus check no responsibility is taken by the sender for any damage rising out of any bug or virus infection.","Sent with Genius Scan for iOS. http://bit.ly/download-genius-scan","Hey John, as you requested, attached is the paycheck for your next month?s salary in advance.","I am sending you the flight tickets for your business conference abroad next month. Please see the attached and note the date and time.","Attached is the bank transactions made from the company during last month. Please file these transactions into financial record.","example.com SV9100 InMail","Attached file is scanned image in PDF format. Use Acrobat(R)Reader(R) or Adobe(R)Reader(R) of Adobe Systems Incorporated to view the document. Adobe(R)Reader(R) can be downloaded from the following URL: Adobe, the Adobe logo, Acrobat, the Adobe PDF logo, and Reader are registered trademarks or trademarks of Adobe Systems Incorporated in the United States and other countries.","Here is the travel expense sheet for your upcoming company field trip. Please write down the approximate costs in the attachment.","Attached is the list of old office facilities that need to be replaced. Please copy the list into the purchase order form.","We are sending you the credit card receipt from yesterday. Please match the card number and amount.","Queries to: <scanner@example.com","Please find our invoice attached.","Hello! We are looking for employees working remotely. My name is Margaret, I am the personnel manager of a large International company. Most of the work you can do from home, that is, at a distance. Salary is $3000-$6000. If you are interested in this offer, please visit","Please see the attached copy of the report.","Attached is a pdf file containing items that have shipped. Please contact us if there are any questions or further assistance we can provide","Please see the attached license and send it to the head office.","Please find attached documents as requested.","We are looking for employees working remotely. My name is Enid, I am the personnel manager of a large International company. Most of the work you can do from home, that is, at a distance. Salary is $2000-$5400. If you are interested in this offer, please visit","Your item #123456789 has been sent to you by carrier. He will arrive to youon 23th of September, 2016 at noon.","Dear John, we are very sorry to inform you that the item you requested is out of stock. Here is the list of items similar to the ones you requested. Please take a look and let us know if you would like to substitute with any of them.","Thank you for your order! Please find your final sales receipt attached to this email. Your USPS Tracking Number is: 123456789. This order will ship tomorrow and you should be able to begin tracking tomorrow evening after it is picked up. If you have any questions or experience any problems, please let us know so we can assist you. Thanks again and enjoy! Thanks,","Thanks for using electronic billing. Please find your document attached","Dear John, I attached the clients’ accounts for your next operation. Please look through them and collect their data. I expect to hear from you soon.","You are receiving this email because the company has assigned you as part of the approval team. Please review the attached proposal form and make your approval decision. If you have any problem regarding the submission, please contact Gonzalo.","this is to inform you that your Debit Card is temporarily blocked as there were unknown transactions made today. We attached the scan of transactions. Please confirm whether you made these transactions.","The letter is attached. Please review his concerns carefully and reply him as soon as possible. King regards,","Confirm your email address","hey i need u to send some $","Please sign the receipt attached for the arrival of new office facilities.","Attached is the paper concerning with the cancellation of your current credit card.","The monthly financial statement is attached within the email.","The audit report you inquired is attached in the mail. Please review and transfer it to the related department.","There is a message for you from 01478719696, on 2016/08/23 18:26:30. You might want to check it when you get a chance.Thanks!","Dear John, I am attaching the mortgage documents relating to your department. They need to be signed in urgent manner.","This email/fax transmission is confidential and intended solely for the person or organisation to whom it is addressed. If you are not the intended recipient, you must not copy, distribute or disseminate the information, or take any action in reliance of it. Any views expressed in this message are those of the individual sender, except where the sender specifically states them to be the views of any organisation or employer. If you have received this message in error, do not open any attachment but please notify the sender (above) deleting this message from your system. For email transmissions please rely on your own virus check no responsibility is taken by the sender for any damage rising out of any bug or virus infection.","Sent with Genius Scan for iOS. http://bit.ly/download-genius-scan","Hey John, as you requested, attached is the paycheck for your next month?s salary in advance.","I am sending you the flight tickets for your business conference abroad next month. Please see the attached and note the date and time.","Attached is the bank transactions made from the company during last month. Please file these transactions into financial record.","example.com SV9100 InMail","Attached file is scanned image in PDF format. Use Acrobat(R)Reader(R) or Adobe(R)Reader(R) of Adobe Systems Incorporated to view the document. Adobe(R)Reader(R) can be downloaded from the following URL: Adobe, the Adobe logo, Acrobat, the Adobe PDF logo, and Reader are registered trademarks or trademarks of Adobe Systems Incorporated in the United States and other countries.","Here is the travel expense sheet for your upcoming company field trip. Please write down the approximate costs in the attachment.","Attached is the list of old office facilities that need to be replaced. Please copy the list into the purchase order form.","We are sending you the credit card receipt from yesterday. Please match the card number and amount.","Queries to: <scanner@example.com","Please find our invoice attached.","Hello! We are looking for employees working remotely. My name is Margaret, I am the personnel manager of a large International company. Most of the work you can do from home, that is, at a distance. Salary is $3000-$6000. If you are interested in this offer, please visit","Please see the attached copy of the report.","Attached is a pdf file containing items that have shipped. Please contact us if there are any questions or further assistance we can provide","Please see the attached license and send it to the head office.","Please find attached documents as requested.","We are looking for employees working remotely. My name is Enid, I am the personnel manager of a large International company. Most of the work you can do from home, that is, at a distance. Salary is $2000-$5400. If you are interested in this offer, please visit","Your item #123456789 has been sent to you by carrier. He will arrive to youon 23th of September, 2016 at noon.","Dear John, we are very sorry to inform you that the item you requested is out of stock. Here is the list of items similar to the ones you requested. Please take a look and let us know if you would like to substitute with any of them.","Thank you for your order! Please find your final sales receipt attached to this email. Your USPS Tracking Number is: 123456789. This order will ship tomorrow and you should be able to begin tracking tomorrow evening after it is picked up. If you have any questions or experience any problems, please let us know so we can assist you. Thanks again and enjoy! Thanks,","Thanks for using electronic billing. Please find your document attached","Dear John, I attached the clients’ accounts for your next operation. Please look through them and collect their data. I expect to hear from you soon.","You are receiving this email because the company has assigned you as part of the approval team. Please review the attached proposal form and make your approval decision. If you have any problem regarding the submission, please contact Gonzalo.","this is to inform you that your Debit Card is temporarily blocked as there were unknown transactions made today. We attached the scan of transactions. Please confirm whether you made these transactions.","The letter is attached. Please review his concerns carefully and reply him as soon as possible. King regards,",
]res_classify = co.classify(inputs=inputs_max_exceeded,examples=examples,model='embed-english-light-v2.0',truncate='END'
)res_classify.classifications

输出结果,

---------------------------------------------------------------------------
CohereAPIError                            Traceback (most recent call last)# ... omitCohereAPIError: invalid request: inputs cannot contain more than 96 elements, received 136

当我给最多只能传递 96 个输入的输入提供 136 个输入时,它返回错误。

有关更多详细信息,请参阅 API 参考 - Co.Classify。

6. Co.Tokenize API

仅指定最少的必要参数并尝试执行。

示例代码,

res_tokenize = co.tokenize(text='tokenize me !D',
)print(res_tokenize)

输出结果,

cohere.Tokens {tokens: [10002, 2261, 2012, 3362, 43]token_strings: ['token', 'ize', ' me', ' !', 'D']meta: {'api_version': {'version': '1'}}
}

除此之外,还有选择模型的参数,但即使参考API参考 - Co.Tokenize,除了 command 之外还可以选择什么,我也不太明白。

7. Co.Detokenize API

仅指定最少的必要参数并尝试执行。

示例代码,

tokens = [10002, 2261, 2012, 3362, 43] # tokenize me !Dres_detokenize = co.detokenize(tokens=tokens
)print(res_detokenize)

输出结果,

tokenize me !D

除此之外,还有选择模型的参数,但是即使参考API Reference - Co.Detokenize,我也不太明白除了 command 之外还可以选择什么。

8. Co.Detect_language

仅指定最少的必要参数并尝试执行。

示例代码,

res_detect_language = co.detect_language(texts=['Hello world', "'Здравствуй, Мир'", 'こんにちは世界', '世界你好', '안녕하세요']
)res_detect_language

输出结果,

cohere.DetectLanguageResponse {results: [Language<language_code: "en", language_name: "English">, Language<language_code: "ru", language_name: "Russian">, Language<language_code: "ja", language_name: "Japanese">, Language<language_code: "zh", language_name: "Chinese">, Language<language_code: "ko", language_name: "Korean">]meta: {'api_version': {'version': '1'}}
}

看来检测正确。 Detect_language 没有其他可以指定的参数。

9. Co.Summarize API

仅指定最少的必要参数并尝试执行。

示例代码,

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\n""The 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."
)co_summarize = co.summarize(text=text
)print(co_summarize)

输出结果,

SummarizeResponse(id='5d566208-06f3-4da0-ac54-fd590c22777f', summary='Ice cream is a frozen food, usually eaten as a snack or dessert. It is made from milk or cream, and is flavored with a sweetener and a spice or fruit. It can also be made by whisking a flavored cream base and liquid nitrogen together. Food coloring and stabilizers may be added. The mixture is cooled and stirred to incorporate air spaces and prevent ice crystals from forming. The result is a smooth, semi-solid foam that is solid at low temperatures. It becomes more malleable as its temperature increases. The meaning of the name "ice cream" varies from one country to another. Some countries, such as the US, have specific regulations for the commercial use of the term "ice cream". Products that do not meet the criteria to be called ice cream are sometimes labeled "frozen dairy dessert". Dairy alternatives, such as goat\'s or sheep\'s milk, or milk substitutes, are available for those who are lactose intolerant or allergic to dairy protein.', meta={'api_version': {'version': '1'}})

输出结果(机器翻译),

冰淇淋是一种冷冻食品,通常作为零食或甜点食用。它由牛奶或奶油制成,并用甜味剂和香料或水果调味。它也可以通过将调味奶油基料和液氮搅拌在一起来制成。可以添加食用色素和稳定剂。将混合物冷却并搅拌以加入空气空间并防止冰晶形成。最终形成光滑的半固态泡沫,在低温下呈固态。随着温度升高,它变得更具延展性。 “冰淇淋”这个名字的含义因国家而异。一些国家,例如美国,对“冰淇淋”一词的商业使用有具体规定。不符合冰淇淋标准的产品有时会被贴上“冷冻乳制品甜点”的标签。乳糖不耐症或对乳蛋白过敏的人可以选择乳制品替代品,例如山羊奶或绵羊奶或牛奶替代品。

看来总结得很好。除此之外,你还可以指定输出摘要的长度(length)、输出格式(format)以及摘要时从原始文本中提取多少内容。似乎可以指定(提取性)等参数。以下是我尝试过的一些示例。

示例:缩短长度(length=short)并以项目符号格式输出(format=bullets)

示例代码,

co_summarize = co.summarize(text=text,length='short',format='bullets'
)print(co_summarize)

输出结果,

SummarizeResponse(id='fefca5fe-1dd4-4fff-91b0-622fc9fc64ec', summary='- Ice cream is a frozen dessert made from milk or cream.\n- It is flavored with a sweetener and a spice or fruit.\n- It can also be made with dairy alternatives.', meta={'api_version': {'version': '1'}})

输出结果(机器翻译),

冰淇淋是一种由牛奶或奶油制成的冷冻甜点。
它用甜味剂和香料或水果调味。
它也可以用乳制品替代品制成。

示例:使用模型的轻型版本(model=command-light),从原始文本中提取更多内容(extractiveness=high),并以项目符号形式输出。

示例代码,

co_summarize = co.summarize(text=text,model='command-light',length='short',format='bullets',extractiveness='high'
)print(co_summarize)

输出结果,

SummarizeResponse(id='df22373b-dd85-4b8f-a6c4-0aac6db32898', summary='- Ice cream is a sweetened frozen food typically eaten as a snack or dessert.\n- It may be made from milk or cream and is flavored with a sweetener, either sugar or an alternative.\n- It can also be made by whisking a flavored cream base and liquid nitrogen together.\n- The result is a smooth, semi-solid foam that is solid at very low temperatures.\n- It becomes more malleable as its temperature increases.\n- The meaning of the name varies from one country to another.', meta={'api_version': {'version': '1'}})

输出结果(机器翻译),

冰淇淋是一种加糖的冷冻食品,通常作为零食或甜点食用。
它可以由牛奶或奶油制成,并用甜味剂(糖或替代品)调味。
它也可以通过将调味奶油基料和液氮搅拌在一起来制成。
其结果是形成光滑的半固态泡沫,在极低的温度下呈固态。
随着温度升高,它变得更具延展性。
名称的含义因国家而异。

当然,从原始句子中提取更多内容(例如,冰淇淋是一种加糖的冷冻食品,通常作为零食或甜点食用。)

其他详细信息请参阅 API 参考 - (Co.Summarize](https://docs.cohere.com/reference/summarize-2)。

10. Co.Rerank API

仅指定最少的必要参数并尝试执行。

示例代码,

docs = ['Carson City is the capital city of the American state of Nevada.','The Commonwealth of the Northern Mariana Islands is a group of islands in the Pacific Ocean. Its capital is Saipan.','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.','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.'
]co_rerank = co.rerank(model='rerank-english-v2.0',query='What is the capital of the United States?',documents=docs
)print(co_rerank)

根据API Reference - Co.Rerank,model的参数不是必需的,但是当它在没有分配 TypeError: rerank() missing 1 required positional argument: ‘model’ 的情况下执行并输出错误日志时,它似乎是必需的参数。当心。

输出结果,

[RerankResult<document['text']: 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., index: 2, relevance_score: 0.98005307>, RerankResult<document['text']: 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., index: 3, relevance_score: 0.27904198>, RerankResult<document['text']: Carson City is the capital city of the American state of Nevada., index: 0, relevance_score: 0.10194652>, RerankResult<document['text']: The Commonwealth of the Northern Mariana Islands is a group of islands in the Pacific Ocean. Its capital is Saipan., index: 1, relevance_score: 0.0721122>]

有序的数组也按照相关性的顺序排列整齐。

除此之外,似乎可以指定多语言模型(model=rerank-multilingual-v2.0),并且可以指定一个参数来指定要包含在有序数组中的响应数量(top_n=3) 。以下是我尝试过的一些示例。

示例:尝试日语 (model=rerank-multilingual-v2.0),让我们使用将前面的文档和查询应用到 DeepL 的结果。

示例代码,

docs_ja = ['カーソンシティはアメリカ・ネバダ州の州都である','北マリアナ諸島連邦は太平洋に浮かぶ島々である。首都はサイパンである。',' ワシントンD.C.(Washington, D.C.)は、アメリカ合衆国の首都である。連邦区である','死刑制度はアメリカ合衆国が国である以前から存在する。2017年現在、死刑は50州のうち30州で合法である。'
]co_rerank_ja = co.rerank(model='rerank-multilingual-v2.0',query='アメリカの首都は何ですか?',documents=docs_ja
)print(co_rerank_ja)

输出结果,

[RerankResult<document['text']:  ワシントンD.C.(Washington, D.C.)は、アメリカ合衆国の首都である。連邦区である, index: 2, relevance_score: 0.9998813>, RerankResult<document['text']: カーソンシティはアメリカ・ネバダ州の州都である, index: 0, relevance_score: 0.37903354>, RerankResult<document['text']: 北マリアナ諸島連邦は太平洋に浮かぶ島々である。首都はサイパンである。, index: 1, relevance_score: 0.23899394>, RerankResult<document['text']: 死刑制度はアメリカ合衆国が国である以前から存在する。2017年現在、死刑は50州のうち30州で合法である。, index: 3, relevance_score: 0.0007014083>]

与默认模型一样,即使在日语中,有序数组也按照相关顺序整齐排列。

示例:仅返回日语中最高相关性 (top_n=1) (model=rerank-multilingual-v2.0)。

示例代码,

docs_ja = ['カーソンシティはアメリカ・ネバダ州の州都である','北マリアナ諸島連邦は太平洋に浮かぶ島々である。首都はサイパンである。',' ワシントンD.C.(Washington, D.C.)は、アメリカ合衆国の首都である。連邦区である','死刑制度はアメリカ合衆国が国である以前から存在する。2017年現在、死刑は50州のうち30州で合法である。'
]co_rerank_ja = co.rerank(model='rerank-multilingual-v2.0',query='アメリカの首都は何ですか?',documents=docs_ja,top_n=1,
)print(co_rerank_ja)

输出结果,

[RerankResult<document['text']:  ワシントンD.C.(Washington, D.C.)は、アメリカ合衆国の首都である。連邦区である, index: 2, relevance_score: 0.9998813>]

我还尝试了一个名为 return_documents 的参数(是否在返回的数组中包含文档),但效果不佳。

其他详细信息请参阅 API 参考 - Co.Rerank。

完结!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/49112.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

合并两个有序数组【leetcode】

1. 题目&#xff1a; 给你两个按 非递减顺序 排列的整数数组 nums1 和 nums2&#xff0c;另有两个整数 m 和 n &#xff0c;分别表示 nums1 和 nums2 中的元素数目。 请你 合并 nums2 到 nums1 中&#xff0c;使合并后的数组同样按 非递减顺序 排列。 注意&#xff1a;最终&…

测试框架pytest教程(9)跳过测试skip和xfail

skip无条件跳过 使用装饰器 pytest.mark.skip(reason"no way of currently testing this") def test_example(faker):print("nihao")print(faker.words()) 方法内部调用 满足条件时跳过 def test_example():a1if a>0:pytest.skip("unsupported …

基于Redis的BitMap实现签到、连续签到统计(含源码)

微信公众号访问地址&#xff1a;基于Redis的BitMap实现签到、连续签到统计(含源码) 推荐文章&#xff1a; 1、springBoot对接kafka,批量、并发、异步获取消息,并动态、批量插入库表; 2、SpringBoot用线程池ThreadPoolTaskExecutor异步处理百万级数据; 3、基于Redis的Geo实现附…

python小脚本——批量将PDF文件转换成图片

语言&#xff1a;python 3 用法&#xff1a;选择PDF文件所在的目录&#xff0c;点击 确定 后&#xff0c;自动将该目录下的所有PDF转换成单个图片&#xff0c;图片名称为: pdf文件名.page_序号.jpg 如运行中报错&#xff0c;需要自行根据报错内容按照缺失的库 例如&#x…

ORB-SLAM系列算法演进

ORB-SLAM算法是特征点法的代表&#xff0c;当前最新发展的ORB-SLAM3已经将相机模型抽象化&#xff0c;适用范围非常广&#xff0c;虽然ORB-SLAM在算法上的创新并不是很丰富&#xff0c;但是它在工程上的创新确实让人耳目一新&#xff0c;也能更好的为AR、机器人的算法实现落地。…

CF 514 C Watto and Mechanism(双哈希)

CF 514 C. Watto and Mechanism(双哈希) Problem - 514C - Codeforces 大意&#xff1a;给出 n 个字典串 &#xff0c;现给出 m 个查询串 &#xff0c; 问是否存在字典串与当前查询串仅差一个字母。每个串仅包含 {‘a’ , ‘b’ , ‘c’ } 三个字母 。 思路&#xff1a;考虑…

Linux编程:在程序中异步的调用其他程序

Linux编程:execv在程序中同步调用其他程序_风静如云的博客-CSDN博客 介绍了同步的调用其他程序的方法。 有的时候我们需要异步的调用其他程序,也就是不用等待其他程序的执行结果,尤其是如果其他程序是作为守护进程运行的,也无法等待其运行的结果。 //ssss程序 #include …

操作教程|通过1Panel开源Linux面板快速安装DataEase

DataEase开源数据可视化分析工具&#xff08;dataease.io&#xff09;的在线安装是通过在服务器命令行执行Linux命令来进行的。但是在实际的安装部署过程中&#xff0c;很多数据分析师或者业务人员经常会因为不熟悉Linux操作系统及命令行操作方式&#xff0c;在安装DataEase的过…

LeetCode42.接雨水

这道题呢可以按列来累加&#xff0c;就是先算第1列的水的高度然后再加上第2列水的高度……一直加到最后就是能加的水的高度&#xff0c;我想到了这里然后就想第i列的水其实就是第i-1列和i1列中最小的高度减去第i列的高度&#xff0c;但是其实并不是&#xff0c;比如示例中的第5…

【蓝桥杯】 [蓝桥杯 2015 省 A] 饮料换购

原题链接&#xff1a;https://www.luogu.com.cn/problem/P8627 1. 题目描述 2. 思路分析 小伙伴们可以看看这篇文章~ https://blog.csdn.net/m0_62531913/article/details/132385341?spm1001.2014.3001.5501 我们这里主要讲下方法二的推导过程&#xff1a; 列方程。 设最…

企业数字化转型需要解决哪些问题?

随着信息技术的不断发展和应用&#xff0c;企业数字化转型已成为提高竞争力和实现可持续发展的必经之路。合沃作为一家专注于为企业提供工业物联网产品与解决方案的企业&#xff0c;拥有丰富的经验和技术实力&#xff0c;正致力于助力企业实现数字化转型。本文将探讨企业数字化…

流的基本概念

流的基本概念 Streaming 101与Streaming 102原文网页 文章目录 流的基本概念术语什么是流无界数据无界数据处理有界数据批处理引擎流引擎低延迟、近似、推测结果正确性时间推理工具 数据处理模式使用经典批处理引擎进行有界数据处理用经典批处理引擎通过临时固定窗口进行无界数…

物联网无线通信方式总结

本文主要内容(一些物联网无线通信方式) 本文将介绍一些物联网无线通信方式的技术特点、底层调制方式和主要应用场景物联网无线通信方式是指利用无线技术实现物体之间的信息交换和网络连接的方式物联网无线通信方式的选择需要考虑多种因素&#xff0c;如传输距离、功耗、数据速…

天翼物联、汕头电信与汕头大学共建新一代信息技术与数字创新(物联网)联合实验室

近日&#xff0c;在工业和信息化部和广东省人民政府共同主办的2023中国数字经济创新发展大会上&#xff0c;天翼物联、汕头电信与汕头大学共建“新一代信息技术与数字创新&#xff08;物联网&#xff09;”联合实验室签约仪式举行。汕头大学校长郝志峰、中国电信广东公司总经理…

字符集与字符编码

目录 一、字符集概述二、Unicode三、Unicode字符集四、Unicode编码规则五、Unicode字符编码规则 UTF-8六、Unicode 字符编码规则 UTF-16七、Unicode 字符编码规则 UTF-32八、UTF 字节顺序标记(BOM)九、Windows 代码页十、Windows(ANSI) 字符集十一、GB2312、GBK、GB18030 一、字…

leetcode原题: 堆箱子(动态规划实现)

题目&#xff1a; 给你一堆n个箱子&#xff0c;箱子宽 wi、深 di、高 hi。箱子不能翻转&#xff0c;将箱子堆起来时&#xff0c;下面箱子的宽度、高度和深度必须大于上面的箱子。实现一种方法&#xff0c;搭出最高的一堆箱子。箱堆的高度为每个箱子高度的总和。 输入使用数组…

elelementui组件

一、按钮 1、按钮样式 使用type、plain、round和circle属性来定义 Button 的样式。 2、主要代码 <el-row><el-button>默认按钮</el-button><el-button type"primary">主要按钮</el-button><el-button type"success">…

SQL函数和过程

一、存储过程概述 1.1 理解 含义&#xff1a;存储过程的英文是 Stored Procedure 。它的思想很简单&#xff0c;就是一组经过 预先编译 的 SQL 语句 的封装。 执行过程&#xff1a;存储过程预先存储在 MySQL 服务器上&#xff0c;需要执行的时候&#xff0c;客户端只需要向服…

DataLoader PyTorch 主要参数的含义

定义&#xff1a; DataLoader类是一个用于从数据集&#xff08;dataset&#xff09;中加载数据&#xff0c;并以迭代器&#xff08;iterator&#xff09;的形式返回数据样本&#xff08;data samples&#xff09;的工具。您给出的两个字典&#xff08;dictionary&#xff09;分…

(三)行为模式:2、命令模式(Command Pattern)(C++示例)

目录 1、命令模式&#xff08;Command Pattern&#xff09;含义 2、命令模式的UML图学习 3、命令模式的应用场景 4、命令模式的优缺点 5、C实现命令模式的实例 1、命令模式&#xff08;Command Pattern&#xff09;含义 命令模式&#xff08;Command&#xff09;&#xff…