标签: openai-api

LangChain如何帮助克服ChatGPT的上下文大小限制?

由于上下文大小有限,无法将长文档直接传递到 ChatGPT。因此,例如,乍一看不可能回答问题或总结长文档。我已经了解了 ChatGPT 原则上如何“了解”更大的上下文 - 基本上是通过从聊天历史中总结一系列先前的上下文 - 但这是否足以检测很长一段时间内的真正的远程依赖关系(带有“含义”)文本?

LangChain 似乎提供了一个解决方案,利用 OpenAI 的 API 和 矢量存储。我正在寻找一个高级描述,当 LangChain 将长文档甚至长文档语料库提供给 ChatGPT,然后通过巧妙的自动提示(例如问答或摘要)来利用 ChatGPT 的 NLP 功能时,会发生什么情况。我们假设文档已经格式化为 LangChain Document 对象。

document openai-api langchain

2
推荐指数
1
解决办法
3956
查看次数

tenacity.RetryError:RetryError[<Future at 0x7f89bc35eb90 state=finished raise AuthenticationError>]

我正在尝试部署一个用streamlit制作的应用程序(还使用streamlit_chat和streamlit_authenticator)。这个应用程序正在利用 llama-index 创建一个包含 chatgpt api 的查询引擎。当我在计算机中声明“streamlit run app.py”时,一切正常,但是当我部署它时,会出现以下错误:

    2023-06-07 16:45:28.682 Uncaught app exception

Traceback (most recent call last):

  File "/home/appuser/venv/lib/python3.10/site-packages/tenacity/__init__.py", line 382, in __call__

    result = fn(*args, **kwargs)

  File "/home/appuser/venv/lib/python3.10/site-packages/llama_index/embeddings/openai.py", line 106, in get_embedding

    return openai.Embedding.create(input=[text], engine=engine)["data"][0]["embedding"]

  File "/home/appuser/venv/lib/python3.10/site-packages/openai/api_resources/embedding.py", line 33, in create

    response = super().create(*args, **kwargs)

  File "/home/appuser/venv/lib/python3.10/site-packages/openai/api_resources/abstract/engine_api_resource.py", line 149, in create

    ) = cls.__prepare_create_request(

  File "/home/appuser/venv/lib/python3.10/site-packages/openai/api_resources/abstract/engine_api_resource.py", line 106, in __prepare_create_request

    requestor = api_requestor.APIRequestor(

  File "/home/appuser/venv/lib/python3.10/site-packages/openai/api_requestor.py", line 138, in __init__

    self.api_key = key or util.default_api_key()

  File "/home/appuser/venv/lib/python3.10/site-packages/openai/util.py", line 186, …
Run Code Online (Sandbox Code Playgroud)

python streamlit openai-api llama-index

2
推荐指数
1
解决办法
8241
查看次数

OpenAI API、ChatCompletion 和 Completion 使用相同的参数给出完全不同的答案。为什么?

我正在探索 gpt3.5-turbo 上不同提示的用法。

调查“ChatCompletion”和“Completion”之间的差异,一些参考文献说它们应该或多或少相同,例如:https ://platform.openai.com/docs/guides/gpt/chat-c​​ompletions-vs - 完工量

其他消息来源称,正如预期的那样,ChatCompletion 对于聊天机器人来说更有用,因为你有“角色”(系统、用户和助理),这样你就可以编排一些事情,比如一些例子和/或之前聊天消息的记忆。而完成对于摘要或文本生成更有用。

但差别似乎要大得多。我找不到解释幕后发生的事情的参考资料。

即使使用具有相同参数的相同模型,以下实验也给出了完全不同的结果。

通过聊天完成

import os
import openai
openai.api_type = "azure"
openai.api_version = "2023-03-15-preview"
openai.api_base = ...
openai.api_key = ...

chat_response = openai.ChatCompletion.create(
  engine="my_model", # gpt-35-turbo
  messages = [{"role":"user","content":"Give me something intresting:\n"}],
  temperature=0,
  max_tokens=800,
  top_p=0.95,
  frequency_penalty=0,
  presence_penalty=0,
  stop=None)

print(chat_response.choices[0]['message']['content'])
Run Code Online (Sandbox Code Playgroud)

结果是关于战争的事实:

Did you know that the shortest war in history was between Britain and Zanzibar in 1896? It lasted only 38 minutes!
Run Code Online (Sandbox Code Playgroud)

完成后

Did you know that the shortest war in history …
Run Code Online (Sandbox Code Playgroud)

python openai-api azure-openai chatgpt-api

2
推荐指数
1
解决办法
4330
查看次数

如何同时使用Python openai客户端与Azure和OpenAI?

OpenAI 提供了一个 Python 客户端,目前版本为 0.27.8,它同时支持 Azure 和 OpenAI。

\n

以下是如何使用它为每个提供商调用 ChatCompletion 的示例:

\n
# openai_chatcompletion.py\n\n"""Test OpenAI\'s ChatCompletion endpoint"""\nimport os\nimport openai\nimport dotenv\ndotenv.load_dotenv()\nopenai.api_key = os.environ.get(\'OPENAI_API_KEY\')\n\n# Hello, world.\napi_response = openai.ChatCompletion.create(\n  model="gpt-3.5-turbo",\n  messages=[\n    {"role": "user", "content": "Hello!"}\n  ],\n  max_tokens=16,\n  temperature=0,\n  top_p=1,\n  frequency_penalty=0,\n  presence_penalty=0,\n)\n\nprint(\'api_response:\', type(api_response), api_response)\nprint(\'api_response.choices[0].message:\', type(api_response.choices[0].message), api_response.choices[0].message)\n
Run Code Online (Sandbox Code Playgroud)\n

和:

\n
# azure_openai_35turbo.py\n\n"""Test Microsoft Azure\'s ChatCompletion endpoint"""\nimport os\nimport openai\nimport dotenv\ndotenv.load_dotenv()\n\nopenai.api_type = "azure"\nopenai.api_base = os.getenv("AZURE_OPENAI_ENDPOINT") \nopenai.api_version = "2023-05-15"\nopenai.api_key = os.getenv("AZURE_OPENAI_KEY")\n\n\n# Hello, world.\n# In addition to the `api_*` properties above, mind the difference in arguments\n# as well …
Run Code Online (Sandbox Code Playgroud)

python python-module azure openai-api openai-whisper

2
推荐指数
1
解决办法
4895
查看次数

如何在langchain faiss检索器中指定相似度阈值?

我想向检索器传递一个相似度阈值。到目前为止我只能弄清楚如何传递 ak 值,但这不是我想要的。我怎样才能通过门槛呢?

from langchain.document_loaders import PyPDFLoader
from langchain.vectorstores import FAISS
from langchain.embeddings.openai import OpenAIEmbeddings

def get_conversation_chain(vectorstore):
    llm = ChatOpenAI(temperature=0, model_name='gpt-3.5-turbo')
    qa = ConversationalRetrievalChain.from_llm(llm=llm, retriever=vectorstore.as_retriever(search_kwargs={'k': 2}), return_source_documents=True, verbose=True)
    return qa

loader = PyPDFLoader("sample.pdf")
# get pdf raw text
pages = loader.load_and_split()
faiss_index = FAISS.from_documents(list_of_documents, OpenAIEmbeddings())
# create conversation chain
chat_history = []
qa = get_conversation_chain(faiss_index)
query = "What is a sunflower?"
result = qa({"question": query, "chat_history": chat_history}) 
Run Code Online (Sandbox Code Playgroud)

python nlp openai-api langchain large-language-model

2
推荐指数
1
解决办法
5743
查看次数

Langchain / ChromaDB:为什么 VectorStore 返回这么多重复项?

import os
from langchain.llms import OpenAI
import bs4
import langchain
from langchain import hub
from langchain.document_loaders import UnstructuredFileLoader
from langchain.embeddings import OpenAIEmbeddings
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain.vectorstores import Chroma

os.environ["OPENAI_API_KEY"] = "KEY"

loader = UnstructuredFileLoader(
    'path_to_file'
)
docs = loader.load()

text_splitter = RecursiveCharacterTextSplitter(
    chunk_size=1000, chunk_overlap=200, add_start_index=True
)
all_splits = text_splitter.split_documents(docs)
vectorstore = Chroma.from_documents(documents=all_splits, embedding=OpenAIEmbeddings())
retriever = vectorstore.as_retriever(search_type="similarity", search_kwargs={"k": 6})

retrieved_docs = retriever.get_relevant_documents(
    "What is X?"
)
Run Code Online (Sandbox Code Playgroud)

这将返回:

[Document(page_content="...", metadata={'source': 'path_to_text', 'start_index': 16932}),
 Document(page_content="...", metadata={'source': 'path_to_text', 'start_index': 16932}),
 Document(page_content="...", metadata={'source': …
Run Code Online (Sandbox Code Playgroud)

python openai-api langchain chromadb py-langchain

2
推荐指数
1
解决办法
746
查看次数

OpenAI GPT-3 API 错误:“无法同时指定模型和引擎”

所以我正在编写一些与 chatgpt3 一起使用的 python 代码。它的作用是发送带有提示的请求,然后获取回复,但我不断收到错误。错误是

Traceback (most recent call last):
  File "main.py", line 16, in <module>
    print(response_json['choices'][0]['text'])
KeyError: 'choices'
Run Code Online (Sandbox Code Playgroud)

这是我的代码:

import json
import requests
import os
data = {
    "prompt": "What is the meaning of life?",
    "model": "text-davinci-002"
}

response = requests.post("https://api.openai.com/v1/engines/davinci/completions", json=data, headers={
    "Content-Type": "application/json",
    "Authorization": f"Bearer {apikey}",
})

response_json = json.loads(response.text)

print(response_json['choices'][0]['text'])

Run Code Online (Sandbox Code Playgroud)

我确实有一个有效的 API 密钥和 JSON 代码,但我没有得到 JSON 代码。

{'error': {'message': 'Cannot specify both model and engine', 'type': 'invalid_request_error', 'param': None, 'code': None}}
Run Code Online (Sandbox Code Playgroud)

我尝试过不同的 API 密钥,但没有成功。我什至查找了 chatgpt 的所有不同型号,但它仍然不起作用

python json python-3.x openai-api gpt-3

1
推荐指数
1
解决办法
6714
查看次数

OpenAI ChatGPT (GPT-3.5) API:如何从响应中提取消息内容?

当收到来自 OpenAI 模型的响应时text-davinci-003,我能够使用以下 PHP 代码从响应中提取文本:

$response = $response->choices[0]->text;
Run Code Online (Sandbox Code Playgroud)

这是text-davinci-003响应代码:

{
  "id": "cmpl-uqkvlQyYK7bGYrRHQ0eXlWi7",
  "object": "text_completion",
  "created": 1589478378,
  "model": "text-davinci-003",
  "choices": [
    {
      "text": "\n\nThis is indeed a test",
      "index": 0,
      "logprobs": null,
      "finish_reason": "length"
    }
  ],
  "usage": {
    "prompt_tokens": 5,
    "completion_tokens": 7,
    "total_tokens": 12
  }
}
Run Code Online (Sandbox Code Playgroud)

我现在尝试更改我的代码以使用最近发布的gpt-3.5-turbo模型,该模型返回的响应略有不同:

{
  "id": "chatcmpl-123",
  "object": "chat.completion",
  "created": 1677652288,
  "choices": [{
    "index": 0,
    "message": {
      "role": "assistant",
      "content": "\n\nHello there, how may I assist you today?",
    },
    "finish_reason": "stop"
  }], …
Run Code Online (Sandbox Code Playgroud)

php openai-api chatgpt-api

1
推荐指数
1
解决办法
8967
查看次数

OpenAI ChatGPT (GPT-3.5) API:为什么我得到 NULL 响应?

我正在尝试对新发布的模型执行 API 调用gpt-3.5-turbo,并具有以下代码,该代码$query应向 API 发送查询(通过变量),然后从 API 中提取响应消息的内容。

但我每次通话都收到空响应。有什么想法我做错了什么吗?

$ch = curl_init();

$query = "What is the capital city of England?";

$url = 'https://api.openai.com/v1/chat/completions';

$api_key = 'sk-**************************************';

$post_fields = [
    "model" => "gpt-3.5-turbo",
    "messages" => ["role" => "user","content" => $query],
    "max_tokens" => 500,
    "temperature" => 0.8
];

$header  = [
    'Content-Type: application/json',
    'Authorization: Bearer ' . $api_key
];

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post_fields));
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);

$result = curl_exec($ch);
if …
Run Code Online (Sandbox Code Playgroud)

php curl openai-api chatgpt-api

1
推荐指数
1
解决办法
6496
查看次数

如何从聊天 gpt 响应中仅提取代码内容?

我使用api( )chatGpt生成 SQL 查询并将其作为模型。openai/v1/chat/completionsgpt-3.5-turbo

但我在从响应中提取 SQL 查询时遇到困难。因为有时 chatGpt 会为查询提供一些解释,有时则不会。我尝试过使用正则表达式,但它不可靠。

regex = r"SELECT .*?;"
match = re.search(regex, result)
if match:
   sql_query = match.group()
   print(sql_query)
Run Code Online (Sandbox Code Playgroud)

是否有其他方法可以从响应中仅提取代码部分?

sql code-generation openai-api gpt-3 chatgpt-api

1
推荐指数
1
解决办法
6032
查看次数