cohere-api
Cohere API for embeddings, RAG, reranking, and semantic search.
What this skill does
# cohere-api
## Purpose
This skill integrates the Cohere API to handle AI tasks like generating embeddings, implementing Retrieval-Augmented Generation (RAG), reranking results, and performing semantic search. It's designed for enhancing AI workflows with Cohere's language models, using real-time API calls for efficient processing.
## When to Use
Use this skill when processing text for vector embeddings in ML pipelines, building RAG systems for accurate query responses, reranking search results for relevance, or conducting semantic searches on large datasets. Apply it in scenarios requiring API-based AI enhancements, such as chatbots needing contextual retrieval or applications analyzing text similarity.
## Key Capabilities
- Generate embeddings: Convert text to vectors via the /embed endpoint, supporting models like "embed-english-v3.0" for up to 512 tokens per request.
- RAG implementation: Fetch and augment responses using /generate with external data sources, handling up to 2048 tokens for input and output.
- Reranking: Use the /rerank endpoint to score and reorder lists of texts based on query relevance, with options for top-k results.
- Semantic search: Leverage embeddings for similarity searches, integrating with vector databases like Pinecone or Weaviate.
- Rate limiting: API enforces 60 requests per minute; monitor usage via response headers.
- Model selection: Specify models in requests, e.g., "command" for generation or "embed-multilingual-v2.0" for cross-language embeddings.
## Usage Patterns
To use this skill, first set the environment variable for authentication: export COHERE_API_KEY=your_api_key. Then, make API calls via HTTP requests or the Cohere SDK. For embeddings, structure requests with JSON payloads containing text arrays. In RAG patterns, retrieve documents first, then pass them to /generate for context-aware responses. Always handle asynchronous patterns by checking response status codes. For reranking, pipe search results through the endpoint in a single call. Use try-except blocks in code to wrap API interactions for reliability.
## Common Commands/API
Interact with Cohere API endpoints using curl or Python SDK. Authentication requires the Bearer token from $COHERE_API_KEY.
- Embeddings endpoint: POST https://api.cohere.ai/v1/embed
Example: curl -X POST https://api.cohere.ai/v1/embed -H "Authorization: Bearer $COHERE_API_KEY" -H "Content-Type: application/json" -d '{"texts": ["Hello world"], "model": "embed-english-v3.0"}'
- Generate endpoint (for RAG): POST https://api.cohere.ai/v1/generate
Code snippet:
import cohere; import os
client = cohere.Client(api_key=os.environ['COHERE_API_KEY'])
response = client.generate(model='command', prompt='Explain AI', max_tokens=50)
- Rerank endpoint: POST https://api.cohere.ai/v1/rerank
Example: curl -X POST https://api.cohere.ai/v1/rerank -H "Authorization: Bearer $COHERE_API_KEY" -d '{"query": "best AI tools", "documents": ["OpenClaw is great", "Cohere is useful"], "top_n": 1}'
- Semantic search pattern: First generate embeddings, then compute cosine similarity in code.
Code snippet:
import numpy as np
emb1 = response.body['embeddings'][0] # From embed response
emb2 = [0.1, 0.2, ...] # Another embedding
similarity = np.dot(emb1, emb2) / (np.linalg.norm(emb1) * np.linalg.norm(emb2))
Config formats: All requests use JSON; for SDK, pass dictionaries like {"model": "command", "prompt": "text"}.
## Integration Notes
Integrate by importing the Cohere SDK in your Python environment: pip install cohere. Set $COHERE_API_KEY as an environment variable for secure handling. In OpenClaw workflows, invoke this skill via function calls, e.g., using the skill ID "cohere-api" in agent prompts. For multi-step integrations, chain outputs: use embeddings from one call as input for RAG. Monitor API usage with Cohere's dashboard to avoid rate limits. Ensure HTTPS for all requests and handle regional endpoints if needed (e.g., us.cohere.ai).
## Error Handling
Common errors include 401 Unauthorized (missing or invalid API key), 429 Too Many Requests (rate limit exceeded), and 400 Bad Request (invalid JSON or parameters). To handle: Check response.status_code in code and retry with exponential backoff for 429 errors. For 401, verify $COHERE_API_KEY and log the issue. Use try-except blocks like this:
Code snippet:
try:
response = client.embed(texts=["text"])
except cohere.CohereError as e:
if e.http_status == 429:
time.sleep(60) # Wait and retry
else:
raise
Always validate inputs before API calls to prevent 400 errors, e.g., ensure text length is under 512 tokens.
## Concrete Usage Examples
**Example 1: Generating Embeddings for Semantic Search**
To create embeddings for a query and compare with documents:
First, set up: export COHERE_API_KEY=your_key
Then, run:
import cohere; import os
client = cohere.Client(api_key=os.environ['COHERE_API_KEY'])
emb_response = client.embed(texts=["What is AI?"])
query_emb = emb_response.body['embeddings'][0]
# Use query_emb for similarity search in a vector DB
**Example 2: Implementing RAG for Question Answering**
For RAG, retrieve context and generate a response:
Prepare documents array, e.g., docs = ["AI is machine intelligence."]
Code:
response = client.generate(
model='command',
prompt='What is AI? Context: ' + ' '.join(docs),
max_tokens=100
)
print(response.body['generations'][0]['text']) # Output the generated answer
## Graph Relationships
- Related to cluster: ai-apis (e.g., shares dependencies with other API-based skills like openai-api).
- Connected via tags: ai-apis, api (links to skills in similar categories for combined workflows).
- Outgoing: Provides inputs to skills like vector-stores for embedding-based searches.
Related in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.