cohere-api

Cohere API 为企业级自然语言处理提供嵌入、重排序、检索增强生成(RAG)和文本生成能力,适用于构建 RAG 流水线、语义搜索、文档重排序和企业级 NLP 应用。Command R+ 在工具调用与检索增强生成上表现突出;Embed v3 与 Rerank 3 在搜索质量方面处于行业领先地位。

仓库最近推送
GitHub Stars
219
Forks
38
Issues / PRs
1

安装方式

先用 Prompt 核对来源与依赖。也可下载安装包。

用 AI 助手安装

复制提示词,让助手先核对固定版本和依赖。

查看 Prompt收起 Prompt
先检查当前 Agent 是否已安装 SkillPI Skill Finder。如果尚未安装,请按官方仓库的说明安装并启用:https://github.com/Findskills/skillpi。然后使用 Skill Finder 打开此 SkillPI 详情页并定位 "cohere-api":https://skillpi.com/zh/skills/deepskill-c2d78735794dae93499a08dc70628181f55b6a502775e5305823e572c969a86f。安装前核对上游来源和版本:https://github.com/TerminalSkills/skills。来源不一致时停止并说明差异。核对通过后,用 Skill Finder 安装目标 Skill,并报告安装路径和来源版本。

来源与配置

github.com

配置方式待核实

请查看原始来源中的适用工具、依赖和权限要求。

安装实测待补充

Cohere API 为企业级自然语言处理提供嵌入、重排序、检索增强生成(RAG)和文本生成能力,适用于构建 RAG 流水线、语义搜索、文档重排序和企业级 NLP 应用。Command R+ 在工具调用与检索增强生成上表现突出;Embed v3 与 Rerank 3 在搜索质量方面处于行业领先地位。

0 下载

介绍来源: third_party · TerminalSkills · 1.0.0 参考来源

SkillPi 解读

软件、账号及付费要求
贝什
实测状态
未测试

文件浏览

在原站浏览文件 ↗

原始 SKILL.md

打开原文 ↗
Frontmatter
name: cohere-api
description: >-
  Cohere API for enterprise NLP — embeddings, reranking, RAG, and text generation.
  Use when building RAG pipelines, semantic search, document reranking, or enterprise
  NLP applications. Command R+ excels at tool use and retrieval-augmented generation;
  Embed v3 and Rerank 3 are best-in-class for search quality.
license: Apache-2.0
compatibility: "Python 3.9+ or Node.js 18+ with cohere SDK"
metadata:
  author: terminal-skills
  version: "1.0.0"
  category: data-ai
  tags: ["cohere", "embeddings", "rerank", "rag", "enterprise-nlp"]
  use-cases:
    - "Build a semantic search engine with Cohere Embed v3"
    - "Improve RAG pipeline accuracy by reranking retrieved documents with Rerank 3"
    - "Build an enterprise knowledge base Q&A system with Command R+"
  agents: [claude-code, openai-codex, gemini-cli, cursor]

Cohere API

Overview

Cohere provides enterprise-grade NLP models purpose-built for production use cases. Their flagship offerings are: Command R+ for RAG and agentic tasks, Embed v3 for state-of-the-art semantic embeddings, and Rerank 3 for dramatically improving search result relevance. All models are available via API with enterprise SLAs and on-premise deployment options.

Setup

# Python
pip install cohere

# TypeScript/Node
npm install cohere-ai
export COHERE_API_KEY=...

Available Models

Model Type Best For
command-r-plus Generation Complex RAG, tool use, long context
command-r Generation Efficient RAG, cost-effective
command Generation Simple text tasks
embed-english-v3.0 Embedding English semantic search
embed-multilingual-v3.0 Embedding 100+ language search
rerank-english-v3 Reranking English document reranking
rerank-multilingual-v3 Reranking Multilingual reranking

Instructions

Chat / Text Generation

import cohere

co = cohere.ClientV2(api_key="your_api_key")  # or reads COHERE_API_KEY

response = co.chat(
    model="command-r-plus",
    messages=[
        {"role": "user", "content": "Explain transformer architecture in plain English."},
    ],
)

print(response.message.content[0].text)

Document Embeddings

import cohere

co = cohere.ClientV2()

# Embed documents for indexing
docs = [
    "Cohere provides enterprise NLP solutions.",
    "Embeddings convert text into dense vectors.",
    "RAG improves LLM answers with retrieved context.",
]

response = co.embed(
    texts=docs,
    model="embed-english-v3.0",
    input_type="search_document",  # "search_document" for indexing
    embedding_types=["float"],
)

embeddings = response.embeddings.float_
print(f"Embedding shape: {len(embeddings)} x {len(embeddings[0])}")  # 3 x 1024

Query Embeddings for Search

import cohere
import numpy as np

co = cohere.ClientV2()

# Query embedding — use "search_query" for queries
query = "How do embeddings work?"

query_response = co.embed(
    texts=[query],
    model="embed-english-v3.0",
    input_type="search_query",  # Different from "search_document"!
    embedding_types=["float"],
)

query_vector = query_response.embeddings.float_[0]

# Find most similar documents using cosine similarity
def cosine_similarity(a, b):
    return np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b))

# (assuming doc_embeddings is a list of previously embedded documents)
similarities = [cosine_similarity(query_vector, doc_emb) for doc_emb in doc_embeddings]
top_idx = np.argsort(similarities)[::-1][:5]

Reranking for RAG Improvement

import cohere

co = cohere.ClientV2()

query = "What are the benefits of renewable energy?"

# Initial candidates (from vector search or keyword search)
documents = [
    "Solar panels convert sunlight into electricity efficiently.",
    "Wind energy reduces carbon emissions significantly.",
    "The history of fossil fuels dates back centuries.",
    "Renewable energy creates jobs in local communities.",
    "Nuclear power is debated as a clean energy source.",
    "Oil prices fluctuate based on global demand.",
]

rerank_response = co.rerank(
    model="rerank-english-v3",
    query=query,
    documents=documents,
    top_n=3,  # Return top 3 most relevant
)

for result in rerank_response.results:
    print(f"Rank {result.index}: Score {result.relevance_score:.3f}")
    print(f"  {documents[result.index]}\n")

Command R+ for RAG with Citations

import cohere

co = cohere.ClientV2()

# RAG with grounding documents — Command R+ provides cited responses
documents = [
    {"id": "doc1", "data": {"title": "Renewable Energy", "snippet": "Solar energy capacity grew 25% in 2024, reaching 1.5 TW globally."}},
    {"id": "doc2", "data": {"title": "Climate Policy", "snippet": "The EU Green Deal targets 55% emissions reduction by 2030."}},
]

response = co.chat(
    model="command-r-plus",
    messages=[{"role": "user", "content": "What is the current state of renewable energy?"}],
    documents=documents,
)

print(response.message.content[0].text)

# Citations reference specific document sources
if hasattr(response.message, "citations") and response.message.citations:
    for citation in response.message.citations:
        print(f"Citation: {citation}")

Tool Use with Command R+

import cohere
import json

co = cohere.ClientV2()

tools = [
    {
        "type": "function",
        "function": {
            "name": "get_stock_price",
            "description": "Get the current stock price for a ticker symbol",
            "parameters": {
                "type": "object",
                "properties": {
                    "ticker": {"type": "string", "description": "Stock ticker (e.g. AAPL)"},
                },
                "required": ["ticker"],
            },
        },
    }
]

messages = [{"role": "user", "content": "What's the current Apple stock price?"}]

response = co.chat(
    model="command-r-plus",
    messages=messages,
    tools=tools,
)

if response.message.tool_calls:
    tool_call = response.message.tool_calls[0]
    args = json.loads(tool_call.function.arguments)
    print(f"Tool: {tool_call.function.name}, Args: {args}")

    # Execute tool and return result
    messages.append({"role": "assistant", "tool_calls": response.message.tool_calls})
    messages.append({
        "role": "tool",
        "tool_call_id": tool_call.id,
        "content": json.dumps({"price": 189.84, "change": "+1.2%"}),
    })

    final = co.chat(model="command-r-plus", messages=messages, tools=tools)
    print(final.message.content[0].text)

Complete RAG Pipeline

import cohere
import numpy as np

co = cohere.ClientV2()

def build_rag_pipeline(documents: list[str]):
    """Embed a corpus of documents."""
    response = co.embed(
        texts=documents,
        model="embed-english-v3.0",
        input_type="search_document",
        embedding_types=["float"],
    )
    return response.embeddings.float_

def retrieve_and_rerank(query: str, documents: list[str], doc_embeddings, top_k=10, top_n=3):
    """Vector search + rerank for best results."""
    # Step 1: Embed query
    q_resp = co.embed(
        texts=[query],
        model="embed-english-v3.0",
        input_type="search_query",
        embedding_types=["float"],
    )
    q_vec = q_resp.embeddings.float_[0]

    # Step 2: Cosine similarity search
    sims = [np.dot(q_vec, d) / (np.linalg.norm(q_vec) * np.linalg.norm(d)) for d in doc_embeddings]
    candidates_idx = np.argsort(sims)[::-1][:top_k]
    candidates = [documents[i] for i in candidates_idx]

    # Step 3: Rerank candidates
    reranked = co.rerank(
        model="rerank-english-v3",
        query=query,
        documents=candidates,
        top_n=top_n,
    )

    return [candidates[r.index] for r in reranked.results]

def answer_with_rag(query: str, context_docs: list[str]) -> str:
    """Generate answer grounded in retrieved documents."""
    docs = [{"data": {"snippet": doc}} for doc in context_docs]
    response = co.chat(
        model="command-r-plus",
        messages=[{"role": "user", "content": query}],
        documents=docs,
    )
    return response.message.content[0].text

Guidelines

  • Always use input_type="search_document" when embedding docs and input_type="search_query" for queries — this matters for retrieval quality.
  • Reranking adds ~100ms latency but often improves RAG answer quality by 20–40% vs vector search alone.
  • Command R+ is optimized for RAG with grounding documents; use documents parameter for best citation quality.
  • The embed-multilingual-v3.0 model supports 100+ languages with a single model.
  • Cohere offers on-premise and private cloud deployment for enterprises requiring data isolation.
  • For large corpora, use Cohere's batch embedding endpoint to process thousands of documents efficiently.

当前收录版本

1.0.0

核对来源版本 ↗

质量评测

满分100 · 来自 SkillPi LAB 实验室的评测报告。

场景价值92/100

亮点

  • 提供企业级 NLP 核心能力(嵌入、重排序、RAG、文本生成),直接解决语义搜索、文档重排序等明确业务痛点
  • 覆盖 Command R+、Embed v3、Rerank 3 等主流模型,满足复杂 RAG 流水线构建需求
触发精准95/100

亮点

  • 触发描述精准覆盖 embeddings、reranking、RAG、semantic search 等核心场景变体
  • 边界清晰,明确区分不同模型的最佳使用场景(如 Command R+ 用于复杂 RAG,Embed v3 用于语义搜索)
结构规范90/100

亮点

  • Phase 划分清晰(Setup/Models/Instructions/Guidelines),含完整端到端 RAG 流水线示例
  • frontmatter 完整,单文件结构合理,Guidelines 提供关键最佳实践
执行可靠88/100

亮点

  • 工具来源明确(cohere SDK),参数使用正确(如 input_type 区分 search_document/search_query)
  • 覆盖主要异常场景(如 citations 检查、tool_calls 处理),Guidelines 强调关键配置项
证据可验 (前四项均值)91/100

取前四项原始分值的算术平均,四舍五入取整。可通过收录报告核对各项评分与说明,运行记录需单独查证。

正文静态检测

100 / 100 · skillpi-20261123-no-r3-v1

正文未命中当前规则。

分数仅反映正文中的规则命中,供使用前参考。附件与运行行为不在此评分范围内。

权限与使用前检查

根据当前主文档自动整理,命中内容可能是示例或防护说明;不是实际权限声明,也未覆盖附件、外部依赖或运行行为。

  • 安装或获取外部依赖

    使用官方来源并锁定版本,在隔离环境检查安装脚本。当前文档检查不覆盖后续下载的代码。

    主文档提及 · 第 32, 35 行
  • 账号、密钥或授权

    使用专用、最小权限账号,不把密钥粘贴到公开内容或命令日志;核对接收数据的服务与租户。

    主文档提及 · 第 61 行

本站展示提示不会授予权限。涉及文件改动、密钥、外部发送或费用时,仍由你使用的工具按需确认。

安全评级与访问范围

safe · 静态证据核验,不代表运行安全保证。

贝什

使用前请由宿主核对并授权实际文件读写、外部服务和联网目的地;本站的核验不会授予任何运行权限。