Merge branch 'preview' into nate/pyO3

This commit is contained in:
Nate Sesti 2023-12-01 14:17:29 -08:00
commit dd8b9fdcc7
11 changed files with 142 additions and 4425 deletions

View file

@ -1,12 +1,12 @@
{
"name": "continue",
"version": "0.7.23",
"version": "0.7.24",
"lockfileVersion": 2,
"requires": true,
"packages": {
"": {
"name": "continue",
"version": "0.7.23",
"version": "0.7.24",
"license": "Apache-2.0",
"dependencies": {
"@electron/rebuild": "^3.2.10",

View file

@ -1,7 +1,7 @@
{
"name": "continue",
"icon": "media/icon.png",
"version": "0.7.23",
"version": "0.7.24",
"repository": {
"type": "git",
"url": "https://github.com/continuedev/continue"

View file

@ -3,7 +3,13 @@ import uuid
from typing import List, Optional, cast
from aiohttp import ClientPayloadError
from openai import error as openai_errors
from openai import (
APIConnectionError,
APIError,
BadRequestError,
RateLimitError,
Timeout,
)
from ..libs.llm.prompts.chat import template_alpaca_messages
from ..libs.util.devdata import dev_data_logger
@ -37,22 +43,19 @@ from .sdk import ContinueSDK
def get_error_title(e: Exception) -> str:
if isinstance(e, openai_errors.APIError):
if isinstance(e, APIError):
return "OpenAI is overloaded with requests. Please try again."
elif isinstance(e, openai_errors.RateLimitError):
elif isinstance(e, RateLimitError):
return "This OpenAI API key has been rate limited. Please try again."
elif isinstance(e, openai_errors.Timeout):
elif isinstance(e, Timeout):
return "OpenAI timed out. Please try again."
elif (
isinstance(e, openai_errors.InvalidRequestError)
and e.code == "context_length_exceeded"
):
return e._message or e.__str__()
elif isinstance(e, BadRequestError) and e.code == "context_length_exceeded":
return e.message or e.__str__()
elif isinstance(e, ClientPayloadError):
return "The request failed. Please try again."
elif isinstance(e, openai_errors.APIConnectionError):
elif isinstance(e, APIConnectionError):
return 'The request failed. Please check your internet connection and try again. If this issue persists, you can use our API key for free by going to VS Code settings and changing the value of continue.OPENAI_API_KEY to ""'
elif isinstance(e, openai_errors.InvalidRequestError):
elif isinstance(e, BadRequestError):
return "Invalid request sent to OpenAI. Please try again."
elif "rate_limit_ip_middleware" in e.__str__():
return "You have reached your limit for free usage of our token. You can continue using Continue by entering your own OpenAI API key in VS Code settings."

View file

@ -12,7 +12,7 @@ import chromadb
from chromadb.config import Settings
from chromadb.utils import embedding_functions
from dotenv import load_dotenv
from openai.error import RateLimitError
from openai import RateLimitError
from pydantic import BaseModel
from ..chunkers.chunk_directory import IndexAction

View file

@ -1,10 +1,9 @@
import asyncio
from typing import List
from ...llm.base import LLM
import openai
from ..chunkers.chunk import Chunk
from ...llm.base import LLM
from ...util.logging import logger
from ..chunkers.chunk import Chunk
PROMPT = """
You are an expert software developer responsible for helping detect whether the retrieved snippet of code is relevant to the query. For a given input, you need to output a single word: "Yes" or "No" indicating the retrieved snippet is relevant to the query.
@ -50,18 +49,19 @@ async def single_token_reranker(chunk: Chunk, user_input: str, model: LLM) -> fl
)
if False:
return 0.5
# TODO: Continuous ranking with logits
# openai.api_key = openai_api_key
response = openai.Completion.create(
model="gpt-3.5-turbo",
prompt=compiled_prompt,
max_tokens=1,
temperature=0.0,
stop=["```"],
logit_bias={3363: 1, 1400: 1},
logprobs=1,
)
return response["choices"][0]["logprobs"]["token_logprobs"][0]
# response = openai.Completion.create(
# model="gpt-3.5-turbo",
# prompt=compiled_prompt,
# max_tokens=1,
# temperature=0.0,
# stop=["```"],
# logit_bias={3363: 1, 1400: 1},
# logprobs=1,
# )
# return response["choices"][0]["logprobs"]["token_logprobs"][0]
else:
try:
completion = await model.complete(

View file

@ -1,16 +1,15 @@
import asyncio
from contextlib import asynccontextmanager
from typing import AsyncGenerator, List, Literal, Optional
import certifi
import openai
from openai.error import RateLimitError
import httpx
import litellm
from litellm import acompletion
from pydantic import Field, validator
from ...core.main import ChatMessage
from ..util.count_tokens import CONTEXT_LENGTH_FOR_MODEL
from ..util.logging import logger
from .base import LLM
from .prompts.chat import template_alpaca_messages
CHAT_MODELS = {
"gpt-3.5-turbo",
@ -122,126 +121,104 @@ class OpenAI(LLM):
if self.context_length is None:
self.context_length = CONTEXT_LENGTH_FOR_MODEL.get(self.model, 4096)
openai.api_key = self.api_key
if self.api_type is not None:
openai.api_type = self.api_type
if self.api_base is not None:
openai.api_base = self.api_base
if self.api_version is not None:
openai.api_version = self.api_version
if (
self.request_options.verify_ssl is not None
and self.request_options.verify_ssl is False
):
openai.verify_ssl_certs = False
if self.request_options.proxy is not None:
openai.proxy = self.request_options.proxy
openai.ca_bundle_path = self.request_options.ca_bundle_path or certifi.where()
session = self.create_client_session()
openai.aiosession.set(session)
def collect_args(self, options):
args = super().collect_args(options)
if self.engine is not None:
args["engine"] = self.engine
if self.api_type == "azure":
assert self.engine is not None, "engine must be specified for Azure API"
args["model"] = f"azure/{self.engine}"
args["api_version"] = self.api_version
args["api_key"] = self.api_key
args["api_base"] = self.api_base
if not args["model"].endswith("0613") and "functions" in args:
del args["functions"]
return args
def httpx_client(self) -> httpx.AsyncClient:
args = {}
if timeout := self.request_options.timeout:
args["timeout"] = httpx.Timeout(timeout)
if verify_ssl := self.request_options.verify_ssl:
args["verify"] = verify_ssl
if ca_bundle_path := self.request_options.ca_bundle_path:
args["cert"] = ca_bundle_path
if proxy := self.request_options.proxy:
args["proxies"] = {"https": proxy, "http": proxy}
if headers := self.request_options.headers:
args["headers"] = headers
return httpx.AsyncClient(**args)
@asynccontextmanager
async def httpx_client_context(self):
client = self.httpx_client()
litellm.aclient_session = client
try:
yield
finally:
await client.aclose()
async def _stream_complete(self, prompt, options):
args = self.collect_args(options)
args["stream"] = True
if (
args["model"] not in NON_CHAT_MODELS
and not self.use_legacy_completions_endpoint
):
async for chunk in await openai.ChatCompletion.acreate(
messages=[{"role": "user", "content": prompt}],
async with self.httpx_client_context():
resp = await acompletion(
messages=[{"content": prompt, "role": "user"}],
**args,
headers=self.request_options.headers,
):
if len(chunk.choices) > 0 and "content" in chunk.choices[0].delta:
yield chunk.choices[0].delta.content
else:
async for chunk in await openai.Completion.acreate(
prompt=prompt, **args, headers=self.request_options.headers
):
if len(chunk.choices) > 0:
yield chunk.choices[0].text
stream=True,
)
async for chunk in resp:
yield chunk.choices[0].delta.content
async def _stream_chat(
self, messages: List[ChatMessage], options
) -> AsyncGenerator[ChatMessage, None]:
args = self.collect_args(options)
# and not self.use_legacy_completions_endpoint
# headers=self.request_options.headers,
# resp = await acompletion(
# messages=[msg.to_dict() for msg in messages],
# **args,
# api_base=self.api_base,
# api_version=self.api_version,
# # engine=self.engine,
# api_key=self.api_key,
# custom_llm_provider="azure" if self.api_type == "azure" else None,
# )
if (
args["model"] not in NON_CHAT_MODELS
and not self.use_legacy_completions_endpoint
):
async for chunk in await openai.ChatCompletion.acreate(
async with self.httpx_client_context():
resp = await acompletion(
messages=[msg.to_dict() for msg in messages],
stream=True,
**args,
headers=self.request_options.headers,
):
if not hasattr(chunk, "choices") or len(chunk.choices) == 0:
continue
stream=True,
)
async for chunk in resp:
if len(chunk.choices) == 0:
continue # :)
delta = chunk.choices[0].delta
if self.api_type == "azure":
if self.model == "gpt-4":
await asyncio.sleep(0.03)
else:
await asyncio.sleep(0.01)
yield ChatMessage(role="assistant", content=delta.get("content", ""))
else:
async for chunk in await openai.Completion.acreate(
prompt=template_alpaca_messages(messages),
stream=True,
**args,
headers=self.request_options.headers,
):
if len(chunk.choices) > 0:
ChatMessage(role="assistant", content=chunk.choices[0].text)
yield ChatMessage(
role="assistant", content=chunk.choices[0].delta.content or ""
)
async def _complete(self, prompt: str, options):
args = self.collect_args(options)
if (
args["model"] not in NON_CHAT_MODELS
and not self.use_legacy_completions_endpoint
):
wait_time = 0.2
while True:
try:
resp = await openai.ChatCompletion.acreate(
messages=[{"role": "user", "content": prompt}],
**args,
headers=self.request_options.headers,
)
return resp.choices[0].message.content
except RateLimitError as e:
logger.debug(f"Rate limit exceeded, waiting {wait_time} seconds")
await asyncio.sleep(wait_time)
wait_time *= 2
if wait_time > 2**10:
raise e
else:
return (
(
await openai.Completion.acreate(
prompt=prompt, **args, headers=self.request_options.headers
)
)
.choices[0]
.text
async with self.httpx_client_context():
resp = await acompletion(
messages=[{"content": prompt, "role": "user"}],
**args,
)
return resp.choices[0].message.content

View file

@ -0,0 +1,32 @@
import asyncio
import os
import traceback
from dotenv import load_dotenv
from litellm import acompletion
load_dotenv()
async def completion_call():
try:
print("test acompletion + streaming")
response = await acompletion(
model="gpt-3.5-turbo",
messages=[{"content": "Hello, how are you?", "role": "user"}],
stream=True,
api_key=os.getenv("OPENAI_API_KEY"),
)
print(f"response: {response}")
async for chunk in response:
print(chunk)
except Exception:
print(f"error occurred: {traceback.format_exc()}")
pass
async def complete_n_times(n: int):
await asyncio.gather(*[completion_call() for _ in range(n)])
asyncio.run(completion_call())

View file

@ -2,9 +2,7 @@ import json
import os
from typing import List
import openai
from directory_tree import display_tree
from dotenv import load_dotenv
from pydantic import Field
from ...core.main import ChatMessage, FunctionCall, Models, Step, step_to_json_schema
@ -13,10 +11,6 @@ from ...core.steps import MessageStep
from ...libs.llm.openai import OpenAI
from .main import EditHighlightedCodeStep
load_dotenv()
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
openai.api_key = OPENAI_API_KEY
FREE_USAGE_STEP_NAME = "Please enter OpenAI API key"

4292
server/poetry.lock generated

File diff suppressed because it is too large Load diff

View file

@ -8,7 +8,6 @@ license = "Apache-2.0"
[tool.poetry.dependencies]
python = "^3.8.1"
openai = "^0.27.5"
boltons = "^23.0.0"
pydantic = "^1.10.8"
uvicorn = "^0.21.1"
@ -45,6 +44,9 @@ tqdm = "^4.66.1"
html2text = "^2020.1.16"
pygit2 = "^1.13.2"
maturin = "^1.3.1"
openai = "^1.3.4"
aiohttp = "^3.9.0"
litellm = "^1.3.3"
[tool.poetry.scripts]
typegen = "continuedev.models.generate_json_schema:main"

View file

@ -1,6 +1,5 @@
fastapi==0.95.2
typer==0.9.0
openai==0.27.5
boltons==23.0.0
pydantic==1.10.8
uvicorn==0.21.1
@ -32,4 +31,6 @@ rich==13.6.0
python-socketio==5.10.0
pathspec==0.11.2
tqdm==4.66.1
html2text==2020.1.16
html2text==2020.1.16
openai==1.3.4
litellm==1.3.3