← Code Recipes
Language Models

Cohere Free code examples in C#, Python, Java and JavaScript

Command models, plus best-in-class rerank and embedding endpoints.

C# Python Java JavaScript

WHAT THIS PAGE COVERS

Rerank — the cheapest accuracy win available to an existing RAG pipeline.

Model command-a-03-2025
Package cohere
Checked

Model ids change. If a sample returns a 404 on the model, that is the first thing to check against the official docs.

No official SDK — use the v2 HTTP API

Cohere's own SDK list covers Python, TypeScript, Java and Go; there is no .NET client. HttpClient needs no package and the v2 shape is stable.

# Nothing to install — System.Net.Http.Json is in the shared framework.

setx CO_API_KEY "..."
First call

Register HttpClient through IHttpClientFactory in a real app rather than newing one per call. Response text is nested: message.content[0].text.

using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;

using HttpClient http = new() { BaseAddress = new Uri("https://api.cohere.com/") };
http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
    "Bearer", Environment.GetEnvironmentVariable("CO_API_KEY"));

var request = new
{
    model = "command-a-03-2025",
    messages = new[]
    {
        new { role = "system", content = "You are a concise technical assistant." },
        new { role = "user", content = "Explain a database index in two sentences." },
    },
};

using var response = await http.PostAsJsonAsync("v2/chat", request);

if (!response.IsSuccessStatusCode)
{
    Console.Error.WriteLine(
        $"Cohere {(int)response.StatusCode}: {await response.Content.ReadAsStringAsync()}");
    return;
}

using var body = JsonDocument.Parse(await response.Content.ReadAsStringAsync());

Console.WriteLine(body.RootElement
    .GetProperty("message")
    .GetProperty("content")[0]
    .GetProperty("text")
    .GetString());
Rerank — the cheapest accuracy win in RAG

The reason most teams add Cohere at all. Over-fetch from your vector store, rerank, send only the top few to the model.

using System.Net.Http.Json;
using System.Text.Json;

string[] candidates =
[
    "Annual leave accrues at 1.75 days per month of service.",
    "The office is closed on national holidays.",
    "Notice period is 60 days for all permanent staff.",
    "Expense claims must be filed within 30 days.",
];

var request = new
{
    model = "rerank-v3.5",
    query = "How much notice do I have to give?",
    documents = candidates,
    top_n = 2,
};

using var response = await http.PostAsJsonAsync("v2/rerank", request);
response.EnsureSuccessStatusCode();

using var body = JsonDocument.Parse(await response.Content.ReadAsStringAsync());

foreach (var result in body.RootElement.GetProperty("results").EnumerateArray())
{
    int index = result.GetProperty("index").GetInt32();
    double score = result.GetProperty("relevance_score").GetDouble();

    Console.WriteLine($"{score:F3}  {candidates[index]}");
}
What to watch for

Three things that differ from every other provider on this page.

// 1. THE ENV VAR IS CO_API_KEY, not COHERE_API_KEY.

// 2. MODEL IDS MOVED. command-r-plus-08-2024 is in most tutorials and
//    is two generations old; command-a-03-2025 is current.

// 3. RESPONSE TEXT IS NESTED — message.content[0].text. content is an
//    array of typed blocks so tool calls and citations can sit beside
//    the text, which is why there is no single .content string.

// Rerank is the endpoint worth the integration. Chat is competent;
// rerank is the one that improves a pipeline you already have.
Install

Note the environment variable is CO_API_KEY, not COHERE_API_KEY — a small thing that costs ten minutes the first time.

pip install cohere

export CO_API_KEY="..."      # macOS / Linux
setx CO_API_KEY "..."        # Windows, then open a new shell
First call

ClientV2, not Client. The v1 client takes a single message string; v2 takes a messages array like everything else on this page. Response text is nested one level deeper than OpenAI's.

import cohere

client = cohere.ClientV2()      # reads CO_API_KEY

response = client.chat(
    model="command-a-03-2025",
    messages=[
        {"role": "system", "content": "You are a concise technical assistant."},
        {"role": "user", "content": "Explain a database index in two sentences."},
    ],
)

# content is a list of typed blocks, not a string.
print(response.message.content[0].text)
print(response.usage.tokens)
Streaming

Events are typed by a string tag. Anything other than content-delta — citations, tool calls, the end marker — will crash a loop that assumes text is always there.

stream = client.chat_stream(
    model="command-a-03-2025",
    messages=[{"role": "user", "content": "Write a haiku about indexes."}],
)

for event in stream:
    if event.type == "content-delta":
        print(event.delta.message.content.text, end="", flush=True)

print()
Rerank — the cheapest accuracy win in RAG

This, not chat, is why most teams add Cohere. Vector search gets you twenty roughly-relevant chunks; rerank orders them by actual relevance to the question and lets you send three instead. Less context, lower cost, better answers — and it works on top of whatever retrieval you already have.

import cohere

client = cohere.ClientV2()

# Whatever your vector store returned — over-fetch deliberately.
candidates = [
    "Annual leave accrues at 1.75 days per month of service.",
    "The office is closed on national holidays.",
    "Notice period is 60 days for all permanent staff.",
    "Expense claims must be filed within 30 days.",
]

ranked = client.rerank(
    model="rerank-v3.5",
    query="How much notice do I have to give?",
    documents=candidates,
    top_n=2,
)

for result in ranked.results:
    print(f"{result.relevance_score:.3f}  {candidates[result.index]}")

# Send only the top_n to the model. Over-fetch wide, rerank, send narrow.
Install

Cohere ships an official Java SDK (com.cohere:cohere-java), but its README still shows the v1 chat shape while Python is on v2. These samples use the v2 HTTP API so the page teaches one API — swap in the SDK once you have checked which version yours exposes.

<!-- Nothing required: java.net.http is in the JDK since Java 11. -->
<!-- Official SDK, if you prefer it and have checked its version:  -->
<dependency>
    <groupId>com.cohere</groupId>
    <artifactId>cohere-java</artifactId>
    <version>1.6.0</version>
</dependency>
First call

java.net.http.HttpClient, no dependency. Response text is nested: message.content[0].text.

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.List;
import java.util.Map;

ObjectMapper mapper = new ObjectMapper();
HttpClient http = HttpClient.newHttpClient();

String payload = mapper.writeValueAsString(Map.of(
    "model", "command-a-03-2025",
    "messages", List.of(
        Map.of("role", "system", "content", "You are a concise technical assistant."),
        Map.of("role", "user", "content", "Explain a database index in two sentences."))));

HttpRequest request = HttpRequest.newBuilder()
    .uri(URI.create("https://api.cohere.com/v2/chat"))
    .header("Authorization", "Bearer " + System.getenv("CO_API_KEY"))
    .header("Content-Type", "application/json")
    .POST(HttpRequest.BodyPublishers.ofString(payload))
    .build();

HttpResponse<String> response = http.send(
    request, HttpResponse.BodyHandlers.ofString());

if (response.statusCode() != 200) {
    System.err.println("Cohere " + response.statusCode() + ": " + response.body());
    return;
}

JsonNode body = mapper.readTree(response.body());
System.out.println(body.get("message").get("content").get(0).get("text").asText());
Rerank — the cheapest accuracy win in RAG

The reason most teams add Cohere. Over-fetch from your vector store, rerank, send only the top few to the model.

import com.fasterxml.jackson.databind.JsonNode;

List<String> candidates = List.of(
    "Annual leave accrues at 1.75 days per month of service.",
    "The office is closed on national holidays.",
    "Notice period is 60 days for all permanent staff.",
    "Expense claims must be filed within 30 days.");

String payload = mapper.writeValueAsString(Map.of(
    "model", "rerank-v3.5",
    "query", "How much notice do I have to give?",
    "documents", candidates,
    "top_n", 2));

HttpRequest request = HttpRequest.newBuilder()
    .uri(URI.create("https://api.cohere.com/v2/rerank"))
    .header("Authorization", "Bearer " + System.getenv("CO_API_KEY"))
    .header("Content-Type", "application/json")
    .POST(HttpRequest.BodyPublishers.ofString(payload))
    .build();

JsonNode body = mapper.readTree(
    http.send(request, HttpResponse.BodyHandlers.ofString()).body());

for (JsonNode result : body.get("results")) {
    int index = result.get("index").asInt();
    double score = result.get("relevance_score").asDouble();

    System.out.printf("%.3f  %s%n", score, candidates.get(index));
}
What to watch for

Three things that differ from every other provider on this page.

// 1. THE ENV VAR IS CO_API_KEY, not COHERE_API_KEY.

// 2. MODEL IDS MOVED. command-r-plus-08-2024 appears in most tutorials
//    and is two generations old; command-a-03-2025 is current.

// 3. RESPONSE TEXT IS NESTED — message.content[0].text. content is an
//    array of typed blocks so tool calls and citations sit beside the
//    text, which is why there is no single content string.

// Rerank is the endpoint worth the integration. Chat is competent;
// rerank improves a retrieval pipeline you already have.
Install

Cohere ships an official SDK (cohere-ai). These samples use the v2 HTTP API instead, because the SDK's chat surface differs by version and the HTTP shape is the one thing that is the same everywhere — swap the SDK in once you have checked which version yours exposes.

# Nothing to install — fetch is built into Node 18+.
# Official SDK, if you prefer it:  npm install cohere-ai

export CO_API_KEY="..."
First call

Bearer auth, and the response nests text one level deeper than OpenAI: message.content is an array of typed blocks.

const response = await fetch("https://api.cohere.com/v2/chat", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.CO_API_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    model: "command-a-03-2025",
    messages: [
      { role: "system", content: "You are a concise technical assistant." },
      { role: "user", content: "Explain a database index in two sentences." },
    ],
  }),
});

if (!response.ok) {
  throw new Error(`Cohere ${response.status}: ${await response.text()}`);
}

const body = await response.json();
console.log(body.message.content[0].text);
Rerank — the cheapest accuracy win in RAG

This, not chat, is why most teams add Cohere. Over-fetch from your vector store, rerank, then send only the top few to the model: less context, lower cost, better answers.

const candidates = [
  "Annual leave accrues at 1.75 days per month of service.",
  "The office is closed on national holidays.",
  "Notice period is 60 days for all permanent staff.",
  "Expense claims must be filed within 30 days.",
];

const response = await fetch("https://api.cohere.com/v2/rerank", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.CO_API_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    model: "rerank-v3.5",
    query: "How much notice do I have to give?",
    documents: candidates,
    top_n: 2,
  }),
});

const { results } = await response.json();

for (const result of results) {
  console.log(result.relevance_score.toFixed(3), candidates[result.index]);
}
What to watch for

Three things that differ from every other provider on this page.

// 1. THE ENV VAR IS CO_API_KEY, not COHERE_API_KEY.

// 2. MODEL IDS MOVED. command-r-plus-08-2024 appears in most tutorials
//    and is two generations old; command-a-03-2025 is current. Keep it
//    in config.
const MODEL = process.env.COHERE_MODEL ?? "command-a-03-2025";

// 3. RESPONSE TEXT IS NESTED. body.message.content[0].text, not
//    choices[0].message.content — content is an array of typed blocks
//    so that tool calls and citations can sit beside the text.

QUESTIONS

Which languages are the Cohere examples in?

C#, Python, Java and JavaScript. Every sample runs as pasted and reads its credentials from an environment variable — no key is ever written into the code.

Which package do I install for Cohere?

The samples use cohere. The install step on each language tab gives the exact command.

Which Cohere model do these examples use?

command-a-03-2025, checked against the official documentation on 25 September 2026. Model ids change often; if a call returns a model-not-found error, check the current list in the official docs.

Where is the official Cohere documentation?

https://docs.cohere.com/ — it is linked at the bottom of this page, and it is the authority whenever it disagrees with a sample here.

ALSO IN LANGUAGE MODELS

The authority

Official Cohere documentation

Model names, pricing and rate limits change faster than any page here can. When this page and the official docs disagree, the official docs are right.

Read the docs ↗

https://docs.cohere.com/

New drops, every week

Free tools & Claude templates, landing regularly.

We keep shipping new free tools, code recipes and Claude Code templates. Follow @freeyantra on Instagram or join the newsletter so you never miss one.

Follow @freeyantra

or get them by email

Double opt-in. Unsubscribe any time. Privacy