Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Добавление Assistants API, возможность загружать файлы + добавление недостающих полей в pydantic модели #19

Merged
merged 4 commits into from
May 20, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[tool.poetry]
name = "gigachat"
version = "0.1.24"
version = "0.1.26"
description = "GigaChat. Python-library for GigaChain and LangChain"
authors = ["Konstantin Krestnikov <[email protected]>", "Sergey Malyshev <[email protected]>"]
license = "MIT"
Expand Down
13 changes: 13 additions & 0 deletions src/gigachat/_types.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
from typing import IO, Mapping, Optional, Tuple, Union

FileContent = Union[IO[bytes], bytes, str]
FileTypes = Union[
# file (or bytes)
FileContent,
# (filename, file (or bytes))
Tuple[Optional[str], FileContent],
# (filename, file (or bytes), content_type)
Tuple[Optional[str], FileContent, Optional[str]],
# (filename, file (or bytes), content_type, headers)
Tuple[Optional[str], FileContent, Optional[str], Mapping[str, str]],
]
Empty file.
57 changes: 57 additions & 0 deletions src/gigachat/api/assistants/get_assistants.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
from http import HTTPStatus
from typing import Any, Dict, Optional

import httpx

from gigachat.api.utils import build_headers
from gigachat.exceptions import AuthenticationError, ResponseError
from gigachat.models.assistants import Assistants


def _get_kwargs(
*,
assistant_id: Optional[str] = None,
access_token: Optional[str] = None,
) -> Dict[str, Any]:
headers = build_headers(access_token)
params = {
"method": "GET",
"url": "/assistants",
"headers": headers,
}
if assistant_id:
params["params"] = {"assistant_id": assistant_id}
return params


def _build_response(response: httpx.Response) -> Assistants:
if response.status_code == HTTPStatus.OK:
return Assistants(**response.json())
elif response.status_code == HTTPStatus.UNAUTHORIZED:
raise AuthenticationError(response.url, response.status_code, response.content, response.headers)
else:
raise ResponseError(response.url, response.status_code, response.content, response.headers)


def sync(
client: httpx.Client,
*,
assistant_id: Optional[str] = None,
access_token: Optional[str] = None,
) -> Assistants:
"""Возвращает массив объектов с данными доступных ассистентов"""
kwargs = _get_kwargs(assistant_id=assistant_id, access_token=access_token)
response = client.request(**kwargs)
return _build_response(response)


async def asyncio(
client: httpx.AsyncClient,
*,
assistant_id: Optional[str] = None,
access_token: Optional[str] = None,
) -> Assistants:
"""Возвращает массив объектов с данными доступных ассистентов"""
kwargs = _get_kwargs(assistant_id=assistant_id, access_token=access_token)
response = await client.request(**kwargs)
return _build_response(response)
60 changes: 60 additions & 0 deletions src/gigachat/api/assistants/post_assistant_files_delete.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
from http import HTTPStatus
from typing import Any, Dict, Optional

import httpx

from gigachat.api.utils import build_headers
from gigachat.exceptions import AuthenticationError, ResponseError
from gigachat.models.assistants import AssistantFileDelete


def _get_kwargs(
*,
assistant_id: str,
file_id: str,
access_token: Optional[str] = None,
) -> Dict[str, Any]:
headers = build_headers(access_token)

return {
"method": "POST",
"url": "/assistants/files/delete",
"json": {
"assistant_id": assistant_id,
"file_id": file_id,
},
"headers": headers,
}


def _build_response(response: httpx.Response) -> AssistantFileDelete:
if response.status_code == HTTPStatus.OK:
return AssistantFileDelete(**response.json())
elif response.status_code == HTTPStatus.UNAUTHORIZED:
raise AuthenticationError(response.url, response.status_code, response.content, response.headers)
else:
raise ResponseError(response.url, response.status_code, response.content, response.headers)


def sync(
client: httpx.Client,
*,
assistant_id: str,
file_id: str,
access_token: Optional[str] = None,
) -> AssistantFileDelete:
kwargs = _get_kwargs(assistant_id=assistant_id, file_id=file_id, access_token=access_token)
response = client.request(**kwargs)
return _build_response(response)


async def asyncio(
client: httpx.AsyncClient,
*,
assistant_id: str,
file_id: str,
access_token: Optional[str] = None,
) -> AssistantFileDelete:
kwargs = _get_kwargs(assistant_id=assistant_id, file_id=file_id, access_token=access_token)
response = await client.request(**kwargs)
return _build_response(response)
92 changes: 92 additions & 0 deletions src/gigachat/api/assistants/post_assistant_modify.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
from http import HTTPStatus
from typing import Any, Dict, List, Optional

import httpx

from gigachat.api.utils import build_headers
from gigachat.exceptions import AuthenticationError, ResponseError
from gigachat.models.assistants import Assistant


def _get_kwargs(
*,
assistant_id: str,
name: Optional[str] = None,
description: Optional[str] = None,
instructions: Optional[str] = None,
file_ids: Optional[List[str]] = None,
metadata: Optional[Dict[str, Any]] = None,
access_token: Optional[str] = None,
) -> Dict[str, Any]:
headers = build_headers(access_token)

return {
"method": "POST",
"url": "/assistants/modify",
"json": {
"assistant_id": assistant_id,
"name": name,
"description": description,
"instructions": instructions,
"file_ids": file_ids,
"metadata": metadata,
},
"headers": headers,
}


def _build_response(response: httpx.Response) -> Assistant:
if response.status_code == HTTPStatus.OK:
return Assistant(**response.json())
elif response.status_code == HTTPStatus.UNAUTHORIZED:
raise AuthenticationError(response.url, response.status_code, response.content, response.headers)
else:
raise ResponseError(response.url, response.status_code, response.content, response.headers)


def sync(
client: httpx.Client,
*,
assistant_id: str,
name: Optional[str] = None,
description: Optional[str] = None,
instructions: Optional[str] = None,
file_ids: Optional[List[str]] = None,
metadata: Optional[Dict[str, Any]] = None,
access_token: Optional[str] = None,
) -> Assistant:
kwargs = _get_kwargs(
assistant_id=assistant_id,
name=name,
description=description,
instructions=instructions,
file_ids=file_ids,
metadata=metadata,
access_token=access_token,
)
response = client.request(**kwargs)
return _build_response(response)


async def asyncio(
client: httpx.AsyncClient,
*,
assistant_id: str,
name: Optional[str] = None,
description: Optional[str] = None,
instructions: Optional[str] = None,
file_ids: Optional[List[str]] = None,
metadata: Optional[Dict[str, Any]] = None,
access_token: Optional[str] = None,
) -> Assistant:
kwargs = _get_kwargs(
assistant_id=assistant_id,
name=name,
description=description,
instructions=instructions,
file_ids=file_ids,
metadata=metadata,
access_token=access_token,
)
response = await client.request(**kwargs)
return _build_response(response)
94 changes: 94 additions & 0 deletions src/gigachat/api/assistants/post_assistants.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
from http import HTTPStatus
from typing import Any, Dict, List, Optional

import httpx

from gigachat.api.utils import build_headers
from gigachat.exceptions import AuthenticationError, ResponseError
from gigachat.models.assistants import CreateAssistant


def _get_kwargs(
*,
model: str,
name: str,
description: Optional[str] = None,
instructions: str,
file_ids: Optional[List[str]] = None,
metadata: Optional[Dict[str, Any]] = None,
access_token: Optional[str] = None,
) -> Dict[str, Any]:
headers = build_headers(access_token)

return {
"method": "POST",
"url": "/assistants",
"json": {
"model": model,
"name": name,
"description": description,
"instructions": instructions,
"file_ids": file_ids,
"metadata": metadata,
},
"headers": headers,
}


def _build_response(response: httpx.Response) -> CreateAssistant:
if response.status_code == HTTPStatus.OK:
return CreateAssistant(**response.json())
elif response.status_code == HTTPStatus.UNAUTHORIZED:
raise AuthenticationError(response.url, response.status_code, response.content, response.headers)
else:
raise ResponseError(response.url, response.status_code, response.content, response.headers)


def sync(
client: httpx.Client,
*,
model: str,
name: str,
description: Optional[str] = None,
instructions: str,
file_ids: Optional[List[str]] = None,
metadata: Optional[Dict[str, Any]] = None,
access_token: Optional[str] = None,
) -> CreateAssistant:
"""Создание ассистента"""
kwargs = _get_kwargs(
model=model,
name=name,
description=description,
instructions=instructions,
file_ids=file_ids,
metadata=metadata,
access_token=access_token,
)
response = client.request(**kwargs)
return _build_response(response)


async def asyncio(
client: httpx.AsyncClient,
*,
model: str,
name: str,
description: Optional[str] = None,
instructions: str,
file_ids: Optional[List[str]] = None,
metadata: Optional[Dict[str, Any]] = None,
access_token: Optional[str] = None,
) -> CreateAssistant:
"""Создание ассистента"""
kwargs = _get_kwargs(
model=model,
name=name,
description=description,
instructions=instructions,
file_ids=file_ids,
metadata=metadata,
access_token=access_token,
)
response = await client.request(**kwargs)
return _build_response(response)
59 changes: 59 additions & 0 deletions src/gigachat/api/post_files.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
from http import HTTPStatus
from typing import Any, Dict, Literal, Optional

import httpx

from gigachat._types import FileTypes
from gigachat.api.utils import build_headers
from gigachat.exceptions import AuthenticationError, ResponseError
from gigachat.models import UploadedFile


def _get_kwargs(
*,
file: FileTypes,
purpose: Literal["general", "assistant"] = "general",
access_token: Optional[str] = None,
) -> Dict[str, Any]:
headers = build_headers(access_token)

return {
"method": "POST",
"url": "/files",
"files": {"file": file},
"data": {"purpose": purpose},
"headers": headers,
}


def _build_response(response: httpx.Response) -> UploadedFile:
if response.status_code == HTTPStatus.OK:
return UploadedFile(**response.json())
elif response.status_code == HTTPStatus.UNAUTHORIZED:
raise AuthenticationError(response.url, response.status_code, response.content, response.headers)
else:
raise ResponseError(response.url, response.status_code, response.content, response.headers)


def sync(
client: httpx.Client,
*,
file: FileTypes,
purpose: Literal["general", "assistant"] = "general",
access_token: Optional[str] = None,
) -> UploadedFile:
kwargs = _get_kwargs(file=file, purpose=purpose, access_token=access_token)
response = client.request(**kwargs)
return _build_response(response)


async def asyncio(
client: httpx.AsyncClient,
*,
file: FileTypes,
purpose: Literal["general", "assistant"] = "general",
access_token: Optional[str] = None,
) -> UploadedFile:
kwargs = _get_kwargs(file=file, purpose=purpose, access_token=access_token)
response = await client.request(**kwargs)
return _build_response(response)
Empty file.
Loading