OpenAI API 访问

您需要获取一个 OpenAI API 密钥 才能使用这些过程。使用它们会在您的 OpenAI 账户中产生费用。您可以通过在 apoc.conf 中定义 apoc.openai.key 配置来全局设置 API 密钥。

此外,您也可以使用这些过程来调用兼容 OpenAI 的 API,它们将使用各自的 API 密钥(甚至无需 API 密钥)。请参阅下文的兼容 OpenAI 的提供商一节。

以下所有过程都可以使用以下 APOC 配置,例如在 apoc.conf 中或通过 Docker 环境变量进行配置。

键 (key)

description(描述)

默认

apoc.ml.openai.type

“AZURE”、“HUGGINGFACE”、“OPENAI”,用于指示 API 是 Azure、HuggingFace、Anthropic 还是其他类型

“OPENAI”

apoc.ml.openai.url

OpenAI 端点的基础 URL

默认值为 https://api.openai.com/v1;如果 apoc.ml.openai.type=<ANTHROPIC>,则为 https://api.anthropic.com/v1;如果 apoc.ml.openai.type=<AZURE 或 HUGGINGFACE>,则为空字符串。

apoc.ml.azure.api.version

apoc.ml.openai.type=AZURE 时,指定在 ?api-version= URL 之后传递的 api-version

""

此外,它们可以接收以下配置键作为最后一个参数。如果存在,它们将优先于类似的 APOC 配置。

表 1. 通用配置参数

键 (key)

description(描述)

apiType

类似于 apoc.ml.openai.type APOC 配置。

endpoint

类似于 apoc.ml.openai.url APOC 配置。

apiVersion

类似于 apoc.ml.azure.api.version APOC 配置。

path

用于自定义添加到基础 URL(由 endpoint 配置定义)的 URL 部分。默认情况下,apoc.ml.openai.embeddingapoc.ml.openai.completionapoc.ml.openai.chat 过程分别使用 /embeddings/completions/chat/completions

jsonPath

用于自定义响应的 JSONPathapoc.ml.openai.chatapoc.ml.openai.completion 过程的默认值为 $,而 apoc.ml.openai.embedding 过程的默认值为 $.data

failOnError

如果为 true(默认值),当输入为空、空白或 null 时,过程将失败。

enableBackOffRetries

如果设置为 true,则启用指数退避重试策略以处理故障。(默认值:false)

backOffRetries

设置操作抛出异常前的最大重试次数。(默认值:5)

exponentialBackoff

如果设置为 true,则重试之间的等待时间呈指数级增长。如果设置为 false,则等待时间线性增加。(默认值:false)

因此,我们可以使用这些过程调用 Azure 提供的 OpenAI 服务,并指向文档中说明的正确端点。

例如,如果我们想调用类似 https://my-resource.openai.azure.com/openai/deployments/my-deployment-id/embeddings?api-version=my-api-version` 的端点,只需传递配置参数即可。

    {endpoint: "https://my-resource.openai.azure.com/openai/deployments/my-deployment-id",
        apiVersion: my-api-version,
        apiType: 'AZURE'
}

/embeddings 部分将在底层自动添加。同样,如果我们使用 apoc.ml.openai.completion,且想要调用类似 https://my-resource.openai.azure.com/openai/deployments/my-deployment-id/completions?api-version=my-api-version 的端点,我们可以编写与上述相同的配置参数,系统会自动添加 /completions 部分。

在使用 apoc.ml.openai.chat 时,使用相同的配置,URL 部分 /chat/completions 将被自动添加。

或者,我们可以编写此 apoc.conf

apoc.ml.openai.url=https://my-resource.openai.azure.com/openai/deployments/my-deployment-id
apoc.ml.azure.api.version=my-api-version
apoc.ml.openai.type=AZURE

生成嵌入 API (Generate Embeddings API)

apoc.ml.openai.embedding 过程可以接收一个文本字符串列表,并为每个字符串返回一行,其中包含 1536 个元素的嵌入向量数据。它使用 此文档中记录的 /embeddings/create API。

其他配置会传递给 API,默认模型为 text-embedding-ada-002

生成嵌入调用
CALL apoc.ml.openai.embedding(['Some Text'], $apiKey, {}) yield index, text, embedding;
表 2. 生成嵌入响应
index 文本 (text) embedding

0

"一些文本"

[-0.0065358975, -7.9563365E-4, …​. -0.010693862, -0.005087272]

表 3. 参数
名称 (name) description(描述)

texts

文本字符串列表

apiKey

OpenAI API 密钥

配置

用于模型和其他请求参数的可选映射。

我们还可以传递自定义的 endpoint: <MyAndPointKey> 条目(它优先于 apoc.ml.openai.url 配置)。<MyAndPointKey> 可以是完整的端点(例如使用 Azure:https://my-resource.openai.azure.com/openai/deployments/my-deployment-id/chat/completions?api-version=my-api-version),或者带有一个 %s(例如使用 Azure:https://my-resource.openai.azure.com/openai/deployments/my-deployment-id/%s?api-version=my-api-version),它最终会被分别替换为 embeddingschat/completioncompletion

或者使用 authType: 'AUTH_TYPE',可以是 authType: "BEARER"(默认配置,通过 Authorization: Bearer $apiKey 标头传递 API 密钥),或 authType: "API_KEY"(通过 api-key: $apiKey 标头条目传递 API 密钥)。

表 4. 结果
名称 (name) description(描述)

index

原始列表中的索引条目

文本 (text)

原始列表中的文本行

embedding

用于 ada-002 模型的 1536 元素浮点嵌入向量

文本补全 API (Text Completion API)

apoc.ml.openai.completion 过程可以继续/补全给定的文本。

它使用 此文档中记录的 /completions/create API。

其他配置会传递给 API,默认模型为 text-davinci-003

文本补全调用
CALL apoc.ml.openai.completion('What color is the sky? Answer in one word: ', $apiKey, {config}) yield value;
文本补全响应
{ created=1684248202, model="text-davinci-003", id="cmpl-7GqBWwX49yMJljdmnLkWxYettZoOy",
  usage={completion_tokens=2, prompt_tokens=12, total_tokens=14},
  choices=[{finish_reason="stop", index=0, text="Blue", logprobs=null}], object="text_completion"}
表 5. 参数
名称 (name) description(描述)

prompt

待补全文本

apiKey

OpenAI API 密钥

配置

用于模型、temperature 和其他请求参数的可选映射

表 6. 结果
名称 (name) description(描述)

OpenAI 的结果条目(包含)

OpenLM API

我们还可以调用 HuggingFace 和 Cohere 的补全 API,类似于 OpenLM 库,如下所示。

对于 HuggingFace API,我们必须定义配置 apiType: 'HUGGINGFACE',因为我们需要转换请求主体。

例如:

CALL apoc.ml.openai.completion('[MASK] is the color of the sky', $huggingFaceApiKey,
{endpoint: 'https://api-inference.huggingface.co/models/google-bert/bert-base-uncased', apiType: 'HUGGINGFACE'})

使用 gpt2 或其他文本补全模型时,回答可能无效。

或者,通过使用 Cohere API,我们必须定义 path: ''',以避免在 URL 后添加 /completions 后缀。

CALL apoc.ml.openai.completion('What color is the sky? Answer in one word: ', $cohereApiKey,
{endpoint: 'https://api.cohere.ai/v1/generate', path: '', model: 'command'})

聊天补全 API (Chat Completion API)

apoc.ml.openai.chat 过程接收一个包含助手和用户之间对话(带有可选的系统消息)的映射列表,并将返回对话流程中的下一条消息。

它使用 此文档中记录的 /chat/create API。

其他配置会传递给 API,默认模型为 gpt-4o

聊天补全调用
CALL apoc.ml.openai.chat([
{role:"system", content:"Only answer with a single word"},
{role:"user", content:"What planet do humans live on?"}
],  $apiKey) yield value
聊天补全响应
{created=1684248203, id="chatcmpl-7GqBXZr94avd4fluYDi2fWEz7DIHL",
object="chat.completion", model="gpt-3.5-turbo-0301",
usage={completion_tokens=2, prompt_tokens=26, total_tokens=28},
choices=[{finish_reason="stop", index=0, message={role="assistant", content="Earth."}}]}
自定义模型的聊天补全调用
CALL apoc.ml.openai.chat([
{role:"user", content:"Which athletes won the gold medal in mixed doubles's curling at the 2022 Winter Olympics?"}
],  $apiKey, { model: "gpt-3.5-turbo" }) yield value
自定义模型的聊天补全响应
{
  "created" : 1721902606,
  "usage" : {
    "total_tokens" : 59,
    "completion_tokens" : 32,
    "prompt_tokens" : 27
  },
  "model" : "gpt-3.5-turbo-2024-05-13",
  "id" : "chatcmpl-9opocM1gj9AMXIh7oSWWfoumJOTRC",
  "choices" : [ {
    "index" : 0,
    "finish_reason" : "stop",
    "message" : {
      "content" : "The gold medal in mixed doubles curling at the 2022 Winter Olympics was won by the Italian team, consisting of Stefania Constantini and Amos Mosaner.",
      "role" : "assistant"
    }
  } ],
  "system_fingerprint" : "fp_400f27fa1f",
  "object" : "chat.completion"
}
表 7. 参数
名称 (name) description(描述)

messages

包含 {role:"assistant|user|system", content:"text"} 指令的映射列表

apiKey

OpenAI API 密钥

配置

用于模型、temperature 和其他请求参数的可选映射

表 8. 结果
名称 (name) description(描述)

来自 OpenAI 的结果条目(包含 created、id、model、object、usage(tokens)、choices(message, index, finish_reason))

兼容 OpenAI 的提供商

我们还可以通过定义 endpoint 配置,以及可选的 modelpathjsonPath 配置,使用这些过程来调用兼容 OpenAI 的 API。

例如,我们可以调用 Anyscale Endpoints

CALL apoc.ml.openai.embedding(['Some Text'], $anyScaleApiKey,
{endpoint: 'https://api.endpoints.anyscale.com/v1', model: 'thenlper/gte-large'})

或者通过 LocalAI API(注意默认情况下 apiKey 为 null)。

CALL apoc.ml.openai.embedding(['Some Text'], "ignored",
{endpoint: 'https://:8080/v1', model: 'text-embedding-ada-002'})

我们可以使用 tomasonjo 模型 从文本生成 Cypher。

WITH 'Node properties are the following:
Movie {title: STRING, votes: INTEGER, tagline: STRING, released: INTEGER}, Person {born: INTEGER, name: STRING}
Relationship properties are the following:
ACTED_IN {roles: LIST}, REVIEWED {summary: STRING, rating: INTEGER}
The relationships are the following:
(:Person)-[:ACTED_IN]->(:Movie), (:Person)-[:DIRECTED]->(:Movie), (:Person)-[:PRODUCED]->(:Movie), (:Person)-[:WROTE]->(:Movie), (:Person)-[:FOLLOWS]->(:Person), (:Person)-[:REVIEWED]->(:Movie)'
as schema,
'Which actors played in the most movies?' as question
CALL apoc.ml.openai.chat([
            {role:"system", content:"Given an input question, convert it to a Cypher query. No pre-amble."},
            {role:"user", content:"Based on the Neo4j graph schema below, write a Cypher query that would answer the user's question:
\n "+ schema +" \n\n Question: "+ question +" \n Cypher query:"}
            ], '<apiKey>', { endpoint: 'https://:8080/chat/completions', model: 'text2cypher-demo-4bit-gguf-unsloth.Q4_K_M.gguf'})
YIELD value RETURN value

或者,通过使用 LLMatic 库

CALL apoc.ml.openai.embedding(['Some Text'], "ignored",
{endpoint: 'https://:3000/v1', model: 'thenlper/gte-large'})

此外,我们可以使用 Groq API,例如。

CALL apoc.ml.openai.chat([{"role": "user", "content": "Explain the importance of low latency LLMs"}],
    '<apiKey>',
    {endpoint: 'https://api.groq.com/openai/v1', model: 'llama3-70b-8192'})

我们也可以将 Mistral APIapoc.ml.openai.chat 过程一起使用,例如。

CALL apoc.ml.openai.chat([
 {role: "user", content: "What planet do humans live on?"}
],
'<apiKey>',
{
 endpoint: 'https://api.mistral.ai/v1',
 model: 'mistral-large-latest'
})

Anthropic API (兼容 OpenAI)

另一种选择是使用 Anthropic API

我们可以使用 apoc.ml.openai.chat 过程来利用 Anthropic Messages API

如果未指定,这些是默认的键值参数,将被包含在请求主体中。

表 9. 默认 Anthropic 键值参数
键 (key)

max_tokens

1000

model

"claude-3-5-sonnet-20240620"

例如:

CALL apoc.ml.openai.chat([
      { content: "What planet do humans live on?", role: "user" },
      { content: "Only answer with a single word", role: "assistant" }
    ],
    $anthropicApiKey,
    {apiType: 'ANTHROPIC'}
)
表 10. 示例结果

{"id": "msg_01NUvsajthuiqRXKJyfs4nBE", "content": [{"text": " in lowercase: What planet do humans live on?", type: "text"}], "model": "claude-3-5-sonnet-20240620", "role": "assistant", "usage": {"output_tokens": 13, input_tokens: 20}, "stop_reason": "end_turn", "stop_sequence": null, "type": "message" }

此外,我们可以通过 anthropic-version 配置参数定义 Anthropic API 版本,例如。

CALL apoc.ml.openai.chat([
      { content: "What planet do humans live on?", role: "user" }
    ],
    $anthropicApiKey,
    {apiType: 'ANTHROPIC', `anthropic-version`: "2023-06-01"}
)

结果类似于上面。

此外,我们可以指定一个 Base64 图像包含在主体中,例如。

CALL apoc.ml.openai.chat([
      { role: "user", content: [
        {type: "image", source: {type: "base64",
            media_type: "image/jpeg",
            data: "<theBase64ImageOfAPizza>"} }
      ]
    }
    ],
    $anthropicApiKey,
    {apiType: 'ANTHROPIC'}
)
表 11. 示例结果

{"id": "msg_01NxAth45myf36njuh1qwxfM", "content": [{ "text": "This image shows a pizza…​..", "type": "text" } ], "model": "claude-3-5-sonnet-20240620", "role": "assistant", "usage": { "output_tokens": 202, "input_tokens": 192 }, "stop_reason": "end_turn", "stop_sequence": null, "type": "message" }

我们还可以指定其他自定义请求主体,例如 max_tokens 值,包含在配置参数中。

CALL apoc.ml.openai.chat([
      { content: "What planet do humans live on?", role: "user" }
    ],
    $anthropicApiKey,
    {apiType: 'ANTHROPIC', max_tokens: 2}
)
表 12. 示例结果

{ "id": "msg_01HxQbBuPc9xxBDSBc5iWw2P", "content": [ { text": "Hearth", "type": "text" } ], "model": "claude-3-5-sonnet-20240620", "role": "assistant", "usage": { "output_tokens": 10, "input_tokens": 20 }, "stop_reason": "max_tokens", "stop_sequence": null, "type": "message" }

此外,我们可以使用 apoc.ml.openai.completion 过程来利用 Anthropic Complete API

如果未指定,这些是默认的键值参数,将被包含在请求主体中。

表 13. 默认 Anthropic 键值参数
键 (key)

max_tokens_to_sample

1000

model

"claude-2.1"

例如:

CALL apoc.ml.openai.completion('\n\nHuman: What color is sky?\n\nAssistant:',
    $anthropicApiKey,
    {apiType: 'ANTHROPIC'}
)
表 14. 示例结果

{ "id": "compl_016JGWzFfBQCVWQ8vkoDsdL3", "stop": "Human:", "model": "claude-2.1", "stop_reason": "stop_sequence", "type": "completion", "completion": " The sky appears blue on a clear day. This is due to how air molecules in Earth’s atmosphere scatter sunlight. Shorter wavelengths of light like blue and violet are scattered more, making the sky appear blue to our eyes.", "log_id": "compl_016JGWzFfBQCVWQ8vkoDsdL3" }

此外,我们可以指定其他自定义请求主体,例如 max_tokens_to_sample 值,包含在配置参数中。

CALL apoc.ml.openai.completion('\n\nHuman: What color is sky?\n\nAssistant:',
    $anthropicApiKey,
    {apiType: 'ANTHROPIC', max_tokens_to_sample: 3}
)
表 15. 示例结果

{ "id": "compl_015yzL9jDdMQnLSN3jkQifZt", "stop": null, "model": "claude-2.1", "stop_reason": "max_tokens", "type": "completion", "completion": " The sky is", "log_id": "compl_015yzL9jDdMQnLSN3jkQifZt" }

我们也可以通过 anthropic-version 配置参数指定 API 版本,类似于上面使用 apoc.ml.openai.chat 过程的示例。

目前 Anthropic 不支持嵌入 API。

同时,包含 stream: true 的负载也不受支持,因为 apoc.ml.openai 的结果必须是 JSON。

© . This site is unofficial and not affiliated with Neo4j, Inc.