以编程方式使用文档

Groq 提供由 LPU™ AI 推理技术驱动的快速 AI 推理。

有关可用模型的列表,请参阅 Groq 模型文档.

本页面帮助您开始使用 Groq 聊天模型。有关所有功能的详细文档 ChatGroq 和配置,请参阅 API 参考.

概述

集成详情

ClassPackageSerializablePython 支持DownloadsVersion
ChatGroq@langchain/groq!NPM - Downloads!NPM - Version

模型特性

请参阅下方表格标题中的链接以获取有关如何使用特定功能的指南。

工具调用结构化输出图像输入Audio inputVideo input令牌级流式处理令牌使用量Logprobs

设置

要访问 ChatGroq 模型,您需要创建一个 Groq 账户,获取 API 密钥,并安装 @langchain/groq 集成包。

凭证

要使用 Groq API,请在 Groq 控制台. 中创建一个 API 密钥。然后,您可以在终端中将 API 密钥设置为环境变量:

如果您想获取模型调用的自动跟踪,您还可以设置您的 LangSmith API 密钥,取消下方注释:

# export LANGSMITH_TRACING="true"
# export LANGSMITH_API_KEY="your-api-key"

安装

LangChain ChatGroq 集成位于 @langchain/groq package:

npm install @langchain/groq @langchain/core
yarn add @langchain/groq @langchain/core
pnpm add @langchain/groq @langchain/core

实例化

现在我们可以实例化模型对象并生成聊天补全:

const llm = new ChatGroq({
    model: "openai/gpt-oss-120b",
    temperature: 0,
    maxTokens: undefined,
    maxRetries: 2,
    // other params...
})

调用

const aiMsg = await llm.invoke([
    {
      role: "system",
      content: "You are a helpful assistant that translates English to French. Translate the user sentence.",
    },
    { role: "user", content: "I love programming." },
])
aiMsg
AIMessage {
  "content": "I enjoy programming. (The French translation is: \"J'aime programmer.\")\n\nNote: I chose to translate \"I love programming\" as \"J'aime programmer\" instead of \"Je suis amoureux de programmer\" because the latter has a romantic connotation that is not present in the original English sentence.",
  "additional_kwargs": {},
  "response_metadata": {
    "tokenUsage": {
      "completionTokens": 73,
      "promptTokens": 31,
      "totalTokens": 104
    },
    "finish_reason": "stop"
  },
  "tool_calls": [],
  "invalid_tool_calls": []
}
console.log(aiMsg.content)
I enjoy programming. (The French translation is: "J'aime programmer.")

Note: I chose to translate "I love programming" as "J'aime programmer" instead of "Je suis amoureux de programmer" because the latter has a romantic connotation that is not present in the original English sentence.

使用 JSON 输出调用

const messages = [
  {
    role: "system",
    content: "You are a math tutor that handles math exercises and makes output in json in format { result: number }.",
  },
  { role: "user",  content: "2 + 2 * 2" },
];

const aiInvokeMsg = await llm.invoke(messages, { response_format: { type: "json_object" } });

// if you want not to pass response_format in every invoke, you can bind it to the instance
const llmWithResponseFormat = llm.bind({ response_format: { type: "json_object" } });
const aiBindMsg = await llmWithResponseFormat.invoke(messages);

// they are the same
console.log({ aiInvokeMsgContent: aiInvokeMsg.content, aiBindMsg: aiBindMsg.content });
{
  aiInvokeMsgContent: '{\n"result": 6\n}',
  aiBindMsg: '{\n"result": 6\n}'
}

API 参考

有关所有功能的详细文档 ChatGroq 和配置,请前往 API 参考.