> ## Documentation Index
> Fetch the complete documentation index at: https://langchain-docs-zh.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Cohere 集成

> 使用 LangChain Python 集成 Cohere LLM。

> [!WARNING]
>
> **您当前所在的页面正在记录使用 Cohere 模型作为文本完成模型的情况。许多流行的 Cohere 模型是 [对话完成模型](https://langchain-docs-zh.mintlify.site/langchain/oss/langchain/models.md)。**
>
> 您可能需要查找 [这个页面](https://langchain-docs-zh.mintlify.site/langchain/oss/python/integrations/chat/cohere.md)。

> [Cohere](https://cohere.ai/about) 是一家加拿大初创公司，提供自然语言处理模型，帮助公司改善人机交互。

请访问 [API 参考](https://reference.langchain.com/python/langchain-cohere/llms/Cohere) 获取所有属性和方法的详细文档。

## 设置

集成位于 `langchain-community` 包中。我们还需要安装 `cohere` 包本身。可以通过以下方式安装：

> [!WARNING]
>
> `langchain-community`包已不再维护。从`langchain_community`导入的示例可能过时或无法使用。请谨慎使用。

### 凭证

我们需要获取一个 [Cohere API 密钥](https://cohere.com/) 并设置 `COHERE_API_KEY` 环境变量：

```python theme={null}
import getpass
import os

if "COHERE_API_KEY" not in os.environ:
    os.environ["COHERE_API_KEY"] = getpass.getpass()
```

### 安装

```python theme={null}
pip install -U langchain-community langchain-cohere
```

（可选）设置 [LangSmith](https://smith.langchain.com) 以获得最佳级别的可观察性

```python theme={null}
os.environ["LANGSMITH_TRACING"] = "true"
# os.environ["LANGSMITH_API_KEY"] = getpass.getpass()
```

## 调用

Cohere 支持 [LLM](https://langchain-docs-zh.mintlify.site/langchain/oss/langchain/models.md) 的所有功能：

```python theme={null}
from langchain_cohere import Cohere
from langchain.messages import HumanMessage
```

```python theme={null}
model = Cohere(max_tokens=256, temperature=0.75)
```

```python theme={null}
message = "Knock knock"
model.invoke(message)
```

```text theme={null}
" Who's there?"
```

```python theme={null}
await model.ainvoke(message)
```

```text theme={null}
" Who's there?"
```

```python theme={null}
stream = model.stream_events(message, version="v3")
for token in stream.text:
    print(token, end="", flush=True)
```

```text theme={null}
 Who's there?
```

```python theme={null}
model.batch([message])
```

```text theme={null}
[" Who's there?"]
```

***

## API 参考

要获取所有 `Cohere` llm 功能和配置的详细文档，请访问 [API 参考](https://reference.langchain.com/python/langchain-cohere/llms/Cohere)

***

> 官方原文：[src/oss/python/integrations/llms/cohere.mdx](https://github.com/langchain-ai/docs/blob/main/src/oss/python/integrations/llms/cohere.mdx) · 非官方翻译，译文由 AI 生成，以英文原文为准。


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.