Feat/zhipuai function calling (#2199)
Co-authored-by: Joel <iamjoel007@gmail.com>
This commit is contained in:
parent
bdc5e9ceb0
commit
b921c55677
46 changed files with 2115 additions and 138 deletions
|
|
@ -1,61 +0,0 @@
|
|||
"""Wrapper around ZhipuAI APIs."""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import posixpath
|
||||
|
||||
from pydantic import BaseModel, Extra
|
||||
from zhipuai.model_api.api import InvokeType
|
||||
from zhipuai.utils import jwt_token
|
||||
from zhipuai.utils.http_client import post, stream
|
||||
from zhipuai.utils.sse_client import SSEClient
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class ZhipuModelAPI(BaseModel):
|
||||
base_url: str = "https://open.bigmodel.cn/api/paas/v3/model-api"
|
||||
api_key: str
|
||||
api_timeout_seconds = 60
|
||||
|
||||
class Config:
|
||||
"""Configuration for this pydantic object."""
|
||||
|
||||
extra = Extra.forbid
|
||||
|
||||
def invoke(self, **kwargs):
|
||||
url = self._build_api_url(kwargs, InvokeType.SYNC)
|
||||
response = post(url, self._generate_token(), kwargs, self.api_timeout_seconds)
|
||||
if not response['success']:
|
||||
raise ValueError(
|
||||
f"Error Code: {response['code']}, Message: {response['msg']} "
|
||||
)
|
||||
return response
|
||||
|
||||
def sse_invoke(self, **kwargs):
|
||||
url = self._build_api_url(kwargs, InvokeType.SSE)
|
||||
data = stream(url, self._generate_token(), kwargs, self.api_timeout_seconds)
|
||||
return SSEClient(data)
|
||||
|
||||
def _build_api_url(self, kwargs, *path):
|
||||
if kwargs:
|
||||
if "model" not in kwargs:
|
||||
raise Exception("model param missed")
|
||||
model = kwargs.pop("model")
|
||||
else:
|
||||
model = "-"
|
||||
|
||||
return posixpath.join(self.base_url, model, *path)
|
||||
|
||||
def _generate_token(self):
|
||||
if not self.api_key:
|
||||
raise Exception(
|
||||
"api_key not provided, you could provide it."
|
||||
)
|
||||
|
||||
try:
|
||||
return jwt_token.generate_token(self.api_key)
|
||||
except Exception:
|
||||
raise ValueError(
|
||||
f"Your api_key is invalid, please check it."
|
||||
)
|
||||
|
|
@ -3,13 +3,15 @@ from typing import Any, Dict, Generator, List, Optional, Union
|
|||
|
||||
from core.model_runtime.entities.llm_entities import LLMResult, LLMResultChunk, LLMResultChunkDelta
|
||||
from core.model_runtime.entities.message_entities import (AssistantPromptMessage, PromptMessage, PromptMessageRole,
|
||||
PromptMessageTool, SystemPromptMessage, UserPromptMessage,
|
||||
PromptMessageTool, SystemPromptMessage, UserPromptMessage, ToolPromptMessage,
|
||||
TextPromptMessageContent, ImagePromptMessageContent, PromptMessageContentType)
|
||||
from core.model_runtime.errors.validate import CredentialsValidateFailedError
|
||||
from core.model_runtime.utils import helper
|
||||
from core.model_runtime.model_providers.__base.large_language_model import LargeLanguageModel
|
||||
from core.model_runtime.model_providers.zhipuai._client import ZhipuModelAPI
|
||||
from core.model_runtime.model_providers.zhipuai._common import _CommonZhipuaiAI
|
||||
|
||||
from core.model_runtime.model_providers.zhipuai.zhipuai_sdk._client import ZhipuAI
|
||||
from core.model_runtime.model_providers.zhipuai.zhipuai_sdk.types.chat.chat_completion_chunk import ChatCompletionChunk
|
||||
from core.model_runtime.model_providers.zhipuai.zhipuai_sdk.types.chat.chat_completion import Completion
|
||||
|
||||
class ZhipuAILargeLanguageModel(_CommonZhipuaiAI, LargeLanguageModel):
|
||||
|
||||
|
|
@ -35,7 +37,7 @@ class ZhipuAILargeLanguageModel(_CommonZhipuaiAI, LargeLanguageModel):
|
|||
credentials_kwargs = self._to_credential_kwargs(credentials)
|
||||
|
||||
# invoke model
|
||||
return self._generate(model, credentials_kwargs, prompt_messages, model_parameters, stop, stream, user)
|
||||
return self._generate(model, credentials_kwargs, prompt_messages, model_parameters, tools, stop, stream, user)
|
||||
|
||||
def get_num_tokens(self, model: str, credentials: dict, prompt_messages: list[PromptMessage],
|
||||
tools: Optional[list[PromptMessageTool]] = None) -> int:
|
||||
|
|
@ -48,7 +50,7 @@ class ZhipuAILargeLanguageModel(_CommonZhipuaiAI, LargeLanguageModel):
|
|||
:param tools: tools for tool calling
|
||||
:return:
|
||||
"""
|
||||
prompt = self._convert_messages_to_prompt(prompt_messages)
|
||||
prompt = self._convert_messages_to_prompt(prompt_messages, tools)
|
||||
|
||||
return self._get_num_tokens_by_gpt2(prompt)
|
||||
|
||||
|
|
@ -72,6 +74,7 @@ class ZhipuAILargeLanguageModel(_CommonZhipuaiAI, LargeLanguageModel):
|
|||
model_parameters={
|
||||
"temperature": 0.5,
|
||||
},
|
||||
tools=[],
|
||||
stream=False
|
||||
)
|
||||
except Exception as ex:
|
||||
|
|
@ -79,6 +82,7 @@ class ZhipuAILargeLanguageModel(_CommonZhipuaiAI, LargeLanguageModel):
|
|||
|
||||
def _generate(self, model: str, credentials_kwargs: dict,
|
||||
prompt_messages: list[PromptMessage], model_parameters: dict,
|
||||
tools: Optional[list[PromptMessageTool]] = None,
|
||||
stop: Optional[List[str]] = None, stream: bool = True,
|
||||
user: Optional[str] = None) -> Union[LLMResult, Generator]:
|
||||
"""
|
||||
|
|
@ -97,7 +101,7 @@ class ZhipuAILargeLanguageModel(_CommonZhipuaiAI, LargeLanguageModel):
|
|||
if stop:
|
||||
extra_model_kwargs['stop_sequences'] = stop
|
||||
|
||||
client = ZhipuModelAPI(
|
||||
client = ZhipuAI(
|
||||
api_key=credentials_kwargs['api_key']
|
||||
)
|
||||
|
||||
|
|
@ -128,11 +132,17 @@ class ZhipuAILargeLanguageModel(_CommonZhipuaiAI, LargeLanguageModel):
|
|||
# not support image message
|
||||
continue
|
||||
|
||||
if new_prompt_messages and new_prompt_messages[-1].role == PromptMessageRole.USER:
|
||||
if new_prompt_messages and new_prompt_messages[-1].role == PromptMessageRole.USER and \
|
||||
copy_prompt_message.role == PromptMessageRole.USER:
|
||||
new_prompt_messages[-1].content += "\n\n" + copy_prompt_message.content
|
||||
else:
|
||||
if copy_prompt_message.role == PromptMessageRole.USER:
|
||||
new_prompt_messages.append(copy_prompt_message)
|
||||
elif copy_prompt_message.role == PromptMessageRole.TOOL:
|
||||
new_prompt_messages.append(copy_prompt_message)
|
||||
elif copy_prompt_message.role == PromptMessageRole.SYSTEM:
|
||||
new_prompt_message = SystemPromptMessage(content=copy_prompt_message.content)
|
||||
new_prompt_messages.append(new_prompt_message)
|
||||
else:
|
||||
new_prompt_message = UserPromptMessage(content=copy_prompt_message.content)
|
||||
new_prompt_messages.append(new_prompt_message)
|
||||
|
|
@ -145,7 +155,7 @@ class ZhipuAILargeLanguageModel(_CommonZhipuaiAI, LargeLanguageModel):
|
|||
if model == 'glm-4v':
|
||||
params = {
|
||||
'model': model,
|
||||
'prompt': [{
|
||||
'messages': [{
|
||||
'role': prompt_message.role.value,
|
||||
'content':
|
||||
[
|
||||
|
|
@ -171,23 +181,63 @@ class ZhipuAILargeLanguageModel(_CommonZhipuaiAI, LargeLanguageModel):
|
|||
else:
|
||||
params = {
|
||||
'model': model,
|
||||
'prompt': [{
|
||||
'role': prompt_message.role.value,
|
||||
'content': prompt_message.content,
|
||||
} for prompt_message in new_prompt_messages],
|
||||
'messages': [],
|
||||
**model_parameters
|
||||
}
|
||||
# glm model
|
||||
if not model.startswith('chatglm'):
|
||||
|
||||
for prompt_message in new_prompt_messages:
|
||||
if prompt_message.role == PromptMessageRole.TOOL:
|
||||
params['messages'].append({
|
||||
'role': 'tool',
|
||||
'content': prompt_message.content,
|
||||
'tool_call_id': prompt_message.tool_call_id
|
||||
})
|
||||
else:
|
||||
params['messages'].append({
|
||||
'role': prompt_message.role.value,
|
||||
'content': prompt_message.content
|
||||
})
|
||||
else:
|
||||
# chatglm model
|
||||
for prompt_message in new_prompt_messages:
|
||||
# merge system message to user message
|
||||
if prompt_message.role == PromptMessageRole.SYSTEM or \
|
||||
prompt_message.role == PromptMessageRole.TOOL or \
|
||||
prompt_message.role == PromptMessageRole.USER:
|
||||
if len(params['messages']) > 0 and params['messages'][-1]['role'] == 'user':
|
||||
params['messages'][-1]['content'] += "\n\n" + prompt_message.content
|
||||
else:
|
||||
params['messages'].append({
|
||||
'role': 'user',
|
||||
'content': prompt_message.content
|
||||
})
|
||||
else:
|
||||
params['messages'].append({
|
||||
'role': prompt_message.role.value,
|
||||
'content': prompt_message.content
|
||||
})
|
||||
|
||||
if tools and len(tools) > 0:
|
||||
params['tools'] = [
|
||||
{
|
||||
'type': 'function',
|
||||
'function': helper.dump_model(tool)
|
||||
} for tool in tools
|
||||
]
|
||||
|
||||
if stream:
|
||||
response = client.sse_invoke(incremental=True, **params).events()
|
||||
return self._handle_generate_stream_response(model, credentials_kwargs, response, prompt_messages)
|
||||
response = client.chat.completions.create(stream=stream, **params)
|
||||
return self._handle_generate_stream_response(model, credentials_kwargs, tools, response, prompt_messages)
|
||||
|
||||
response = client.invoke(**params)
|
||||
return self._handle_generate_response(model, credentials_kwargs, response, prompt_messages)
|
||||
response = client.chat.completions.create(**params)
|
||||
return self._handle_generate_response(model, credentials_kwargs, tools, response, prompt_messages)
|
||||
|
||||
def _handle_generate_response(self, model: str,
|
||||
credentials: dict,
|
||||
response: Dict[str, Any],
|
||||
tools: Optional[list[PromptMessageTool]],
|
||||
response: Completion,
|
||||
prompt_messages: list[PromptMessage]) -> LLMResult:
|
||||
"""
|
||||
Handle llm response
|
||||
|
|
@ -197,26 +247,39 @@ class ZhipuAILargeLanguageModel(_CommonZhipuaiAI, LargeLanguageModel):
|
|||
:param prompt_messages: prompt messages
|
||||
:return: llm response
|
||||
"""
|
||||
data = response["data"]
|
||||
text = ''
|
||||
for res in data["choices"]:
|
||||
text += res['content']
|
||||
assistant_tool_calls: List[AssistantPromptMessage.ToolCall] = []
|
||||
for choice in response.choices:
|
||||
if choice.message.tool_calls:
|
||||
for tool_call in choice.message.tool_calls:
|
||||
if tool_call.type == 'function':
|
||||
assistant_tool_calls.append(
|
||||
AssistantPromptMessage.ToolCall(
|
||||
id=tool_call.id,
|
||||
type=tool_call.type,
|
||||
function=AssistantPromptMessage.ToolCall.ToolCallFunction(
|
||||
name=tool_call.function.name,
|
||||
arguments=tool_call.function.arguments,
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
text += choice.message.content or ''
|
||||
|
||||
token_usage = data.get("usage")
|
||||
if token_usage is not None:
|
||||
if 'prompt_tokens' not in token_usage:
|
||||
token_usage['prompt_tokens'] = 0
|
||||
if 'completion_tokens' not in token_usage:
|
||||
token_usage['completion_tokens'] = token_usage['total_tokens']
|
||||
prompt_usage = response.usage.prompt_tokens
|
||||
completion_usage = response.usage.completion_tokens
|
||||
|
||||
# transform usage
|
||||
usage = self._calc_response_usage(model, credentials, token_usage['prompt_tokens'], token_usage['completion_tokens'])
|
||||
usage = self._calc_response_usage(model, credentials, prompt_usage, completion_usage)
|
||||
|
||||
# transform response
|
||||
result = LLMResult(
|
||||
model=model,
|
||||
prompt_messages=prompt_messages,
|
||||
message=AssistantPromptMessage(content=text),
|
||||
message=AssistantPromptMessage(
|
||||
content=text,
|
||||
tool_calls=assistant_tool_calls
|
||||
),
|
||||
usage=usage,
|
||||
)
|
||||
|
||||
|
|
@ -224,7 +287,8 @@ class ZhipuAILargeLanguageModel(_CommonZhipuaiAI, LargeLanguageModel):
|
|||
|
||||
def _handle_generate_stream_response(self, model: str,
|
||||
credentials: dict,
|
||||
responses: list[Generator],
|
||||
tools: Optional[list[PromptMessageTool]],
|
||||
responses: Generator[ChatCompletionChunk, None, None],
|
||||
prompt_messages: list[PromptMessage]) -> Generator:
|
||||
"""
|
||||
Handle llm stream response
|
||||
|
|
@ -234,39 +298,64 @@ class ZhipuAILargeLanguageModel(_CommonZhipuaiAI, LargeLanguageModel):
|
|||
:param prompt_messages: prompt messages
|
||||
:return: llm response chunk generator result
|
||||
"""
|
||||
for index, event in enumerate(responses):
|
||||
if event.event == "add":
|
||||
full_assistant_content = ''
|
||||
for chunk in responses:
|
||||
if len(chunk.choices) == 0:
|
||||
continue
|
||||
|
||||
delta = chunk.choices[0]
|
||||
|
||||
if delta.finish_reason is None and (delta.delta.content is None or delta.delta.content == ''):
|
||||
continue
|
||||
|
||||
assistant_tool_calls: List[AssistantPromptMessage.ToolCall] = []
|
||||
for tool_call in delta.delta.tool_calls or []:
|
||||
if tool_call.type == 'function':
|
||||
assistant_tool_calls.append(
|
||||
AssistantPromptMessage.ToolCall(
|
||||
id=tool_call.id,
|
||||
type=tool_call.type,
|
||||
function=AssistantPromptMessage.ToolCall.ToolCallFunction(
|
||||
name=tool_call.function.name,
|
||||
arguments=tool_call.function.arguments,
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
# transform assistant message to prompt message
|
||||
assistant_prompt_message = AssistantPromptMessage(
|
||||
content=delta.delta.content if delta.delta.content else '',
|
||||
tool_calls=assistant_tool_calls
|
||||
)
|
||||
|
||||
full_assistant_content += delta.delta.content if delta.delta.content else ''
|
||||
|
||||
if delta.finish_reason is not None and chunk.usage is not None:
|
||||
completion_tokens = chunk.usage.completion_tokens
|
||||
prompt_tokens = chunk.usage.prompt_tokens
|
||||
|
||||
# transform usage
|
||||
usage = self._calc_response_usage(model, credentials, prompt_tokens, completion_tokens)
|
||||
|
||||
yield LLMResultChunk(
|
||||
model=chunk.model,
|
||||
prompt_messages=prompt_messages,
|
||||
model=model,
|
||||
system_fingerprint='',
|
||||
delta=LLMResultChunkDelta(
|
||||
index=index,
|
||||
message=AssistantPromptMessage(content=event.data)
|
||||
index=delta.index,
|
||||
message=assistant_prompt_message,
|
||||
finish_reason=delta.finish_reason,
|
||||
usage=usage
|
||||
)
|
||||
)
|
||||
elif event.event == "error" or event.event == "interrupted":
|
||||
raise ValueError(
|
||||
f"{event.data}"
|
||||
)
|
||||
elif event.event == "finish":
|
||||
meta = json.loads(event.meta)
|
||||
token_usage = meta['usage']
|
||||
if token_usage is not None:
|
||||
if 'prompt_tokens' not in token_usage:
|
||||
token_usage['prompt_tokens'] = 0
|
||||
if 'completion_tokens' not in token_usage:
|
||||
token_usage['completion_tokens'] = token_usage['total_tokens']
|
||||
|
||||
usage = self._calc_response_usage(model, credentials, token_usage['prompt_tokens'], token_usage['completion_tokens'])
|
||||
|
||||
else:
|
||||
yield LLMResultChunk(
|
||||
model=model,
|
||||
model=chunk.model,
|
||||
prompt_messages=prompt_messages,
|
||||
system_fingerprint='',
|
||||
delta=LLMResultChunkDelta(
|
||||
index=index,
|
||||
message=AssistantPromptMessage(content=event.data),
|
||||
finish_reason='finish',
|
||||
usage=usage
|
||||
index=delta.index,
|
||||
message=assistant_prompt_message,
|
||||
)
|
||||
)
|
||||
|
||||
|
|
@ -291,11 +380,10 @@ class ZhipuAILargeLanguageModel(_CommonZhipuaiAI, LargeLanguageModel):
|
|||
raise ValueError(f"Got unknown type {message}")
|
||||
|
||||
return message_text
|
||||
|
||||
def _convert_messages_to_prompt(self, messages: List[PromptMessage]) -> str:
|
||||
"""
|
||||
Format a list of messages into a full prompt for the Anthropic model
|
||||
|
||||
|
||||
def _convert_messages_to_prompt(self, messages: List[PromptMessage], tools: Optional[list[PromptMessageTool]] = None) -> str:
|
||||
"""
|
||||
:param messages: List of PromptMessage to combine.
|
||||
:return: Combined string with necessary human_prompt and ai_prompt tags.
|
||||
"""
|
||||
|
|
@ -306,5 +394,10 @@ class ZhipuAILargeLanguageModel(_CommonZhipuaiAI, LargeLanguageModel):
|
|||
for message in messages
|
||||
)
|
||||
|
||||
if tools and len(tools) > 0:
|
||||
text += "\n\nTools:"
|
||||
for tool in tools:
|
||||
text += f"\n{tool.json()}"
|
||||
|
||||
# trim off the trailing ' ' that might come from the "Assistant: "
|
||||
return text.rstrip()
|
||||
return text.rstrip()
|
||||
|
|
@ -5,7 +5,7 @@ from core.model_runtime.entities.model_entities import PriceType
|
|||
from core.model_runtime.entities.text_embedding_entities import EmbeddingUsage, TextEmbeddingResult
|
||||
from core.model_runtime.errors.validate import CredentialsValidateFailedError
|
||||
from core.model_runtime.model_providers.__base.text_embedding_model import TextEmbeddingModel
|
||||
from core.model_runtime.model_providers.zhipuai._client import ZhipuModelAPI
|
||||
from core.model_runtime.model_providers.zhipuai.zhipuai_sdk._client import ZhipuAI
|
||||
from core.model_runtime.model_providers.zhipuai._common import _CommonZhipuaiAI
|
||||
from langchain.schema.language_model import _get_token_ids_default_method
|
||||
|
||||
|
|
@ -28,7 +28,7 @@ class ZhipuAITextEmbeddingModel(_CommonZhipuaiAI, TextEmbeddingModel):
|
|||
:return: embeddings result
|
||||
"""
|
||||
credentials_kwargs = self._to_credential_kwargs(credentials)
|
||||
client = ZhipuModelAPI(
|
||||
client = ZhipuAI(
|
||||
api_key=credentials_kwargs['api_key']
|
||||
)
|
||||
|
||||
|
|
@ -69,7 +69,7 @@ class ZhipuAITextEmbeddingModel(_CommonZhipuaiAI, TextEmbeddingModel):
|
|||
try:
|
||||
# transform credentials to kwargs for model instance
|
||||
credentials_kwargs = self._to_credential_kwargs(credentials)
|
||||
client = ZhipuModelAPI(
|
||||
client = ZhipuAI(
|
||||
api_key=credentials_kwargs['api_key']
|
||||
)
|
||||
|
||||
|
|
@ -82,7 +82,7 @@ class ZhipuAITextEmbeddingModel(_CommonZhipuaiAI, TextEmbeddingModel):
|
|||
except Exception as ex:
|
||||
raise CredentialsValidateFailedError(str(ex))
|
||||
|
||||
def embed_documents(self, model: str, client: ZhipuModelAPI, texts: List[str]) -> Tuple[List[List[float]], int]:
|
||||
def embed_documents(self, model: str, client: ZhipuAI, texts: List[str]) -> Tuple[List[List[float]], int]:
|
||||
"""Call out to ZhipuAI's embedding endpoint.
|
||||
|
||||
Args:
|
||||
|
|
@ -91,17 +91,16 @@ class ZhipuAITextEmbeddingModel(_CommonZhipuaiAI, TextEmbeddingModel):
|
|||
Returns:
|
||||
List of embeddings, one for each text.
|
||||
"""
|
||||
|
||||
|
||||
embeddings = []
|
||||
embedding_used_tokens = 0
|
||||
|
||||
for text in texts:
|
||||
response = client.invoke(model=model, prompt=text)
|
||||
data = response["data"]
|
||||
embeddings.append(data.get('embedding'))
|
||||
response = client.embeddings.create(model=model, input=text)
|
||||
data = response.data[0]
|
||||
embeddings.append(data.embedding)
|
||||
embedding_used_tokens += response.usage.total_tokens
|
||||
|
||||
embedding_used_tokens = data.get('usage')
|
||||
|
||||
return [list(map(float, e)) for e in embeddings], embedding_used_tokens['total_tokens'] if embedding_used_tokens else 0
|
||||
return [list(map(float, e)) for e in embeddings], embedding_used_tokens
|
||||
|
||||
def embed_query(self, text: str) -> List[float]:
|
||||
"""Call out to ZhipuAI's embedding endpoint.
|
||||
|
|
|
|||
|
|
@ -0,0 +1,17 @@
|
|||
|
||||
from ._client import ZhipuAI
|
||||
|
||||
from .core._errors import (
|
||||
ZhipuAIError,
|
||||
APIStatusError,
|
||||
APIRequestFailedError,
|
||||
APIAuthenticationError,
|
||||
APIReachLimitError,
|
||||
APIInternalError,
|
||||
APIServerFlowExceedError,
|
||||
APIResponseError,
|
||||
APIResponseValidationError,
|
||||
APITimeoutError,
|
||||
)
|
||||
|
||||
from .__version__ import __version__
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
|
||||
__version__ = 'v2.0.1'
|
||||
|
|
@ -0,0 +1,71 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from typing import Union, Mapping
|
||||
|
||||
from typing_extensions import override
|
||||
|
||||
from .core import _jwt_token
|
||||
from .core._errors import ZhipuAIError
|
||||
from .core._http_client import HttpClient, ZHIPUAI_DEFAULT_MAX_RETRIES
|
||||
from .core._base_type import NotGiven, NOT_GIVEN
|
||||
from . import api_resource
|
||||
import os
|
||||
import httpx
|
||||
from httpx import Timeout
|
||||
|
||||
|
||||
class ZhipuAI(HttpClient):
|
||||
chat: api_resource.chat
|
||||
api_key: str
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
api_key: str | None = None,
|
||||
base_url: str | httpx.URL | None = None,
|
||||
timeout: Union[float, Timeout, None, NotGiven] = NOT_GIVEN,
|
||||
max_retries: int = ZHIPUAI_DEFAULT_MAX_RETRIES,
|
||||
http_client: httpx.Client | None = None,
|
||||
custom_headers: Mapping[str, str] | None = None
|
||||
) -> None:
|
||||
# if api_key is None:
|
||||
# api_key = os.environ.get("ZHIPUAI_API_KEY")
|
||||
if api_key is None:
|
||||
raise ZhipuAIError("未提供api_key,请通过参数或环境变量提供")
|
||||
self.api_key = api_key
|
||||
|
||||
if base_url is None:
|
||||
base_url = os.environ.get("ZHIPUAI_BASE_URL")
|
||||
if base_url is None:
|
||||
base_url = f"https://open.bigmodel.cn/api/paas/v4"
|
||||
from .__version__ import __version__
|
||||
super().__init__(
|
||||
version=__version__,
|
||||
base_url=base_url,
|
||||
timeout=timeout,
|
||||
custom_httpx_client=http_client,
|
||||
custom_headers=custom_headers,
|
||||
)
|
||||
self.chat = api_resource.chat.Chat(self)
|
||||
self.images = api_resource.images.Images(self)
|
||||
self.embeddings = api_resource.embeddings.Embeddings(self)
|
||||
self.files = api_resource.files.Files(self)
|
||||
self.fine_tuning = api_resource.fine_tuning.FineTuning(self)
|
||||
|
||||
@property
|
||||
@override
|
||||
def _auth_headers(self) -> dict[str, str]:
|
||||
api_key = self.api_key
|
||||
return {"Authorization": f"{_jwt_token.generate_token(api_key)}"}
|
||||
|
||||
def __del__(self) -> None:
|
||||
if (not hasattr(self, "_has_custom_http_client")
|
||||
or not hasattr(self, "close")
|
||||
or not hasattr(self, "_client")):
|
||||
# if the '__init__' method raised an error, self would not have client attr
|
||||
return
|
||||
|
||||
if self._has_custom_http_client:
|
||||
return
|
||||
|
||||
self.close()
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
from .chat import chat
|
||||
from .images import Images
|
||||
from .embeddings import Embeddings
|
||||
from .files import Files
|
||||
from .fine_tuning import fine_tuning
|
||||
|
|
@ -0,0 +1,87 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from typing import Union, List, Optional, TYPE_CHECKING
|
||||
|
||||
import httpx
|
||||
from typing_extensions import Literal
|
||||
|
||||
from ...core._base_api import BaseAPI
|
||||
from ...core._base_type import NotGiven, NOT_GIVEN, Headers
|
||||
from ...core._http_client import make_user_request_input
|
||||
from ...types.chat.async_chat_completion import AsyncTaskStatus, AsyncCompletion
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from ..._client import ZhipuAI
|
||||
|
||||
|
||||
class AsyncCompletions(BaseAPI):
|
||||
def __init__(self, client: "ZhipuAI") -> None:
|
||||
super().__init__(client)
|
||||
|
||||
|
||||
def create(
|
||||
self,
|
||||
*,
|
||||
model: str,
|
||||
request_id: Optional[str] | NotGiven = NOT_GIVEN,
|
||||
do_sample: Optional[Literal[False]] | Literal[True] | NotGiven = NOT_GIVEN,
|
||||
temperature: Optional[float] | NotGiven = NOT_GIVEN,
|
||||
top_p: Optional[float] | NotGiven = NOT_GIVEN,
|
||||
max_tokens: int | NotGiven = NOT_GIVEN,
|
||||
seed: int | NotGiven = NOT_GIVEN,
|
||||
messages: Union[str, List[str], List[int], List[List[int]], None],
|
||||
stop: Optional[Union[str, List[str], None]] | NotGiven = NOT_GIVEN,
|
||||
sensitive_word_check: Optional[object] | NotGiven = NOT_GIVEN,
|
||||
tools: Optional[object] | NotGiven = NOT_GIVEN,
|
||||
tool_choice: str | NotGiven = NOT_GIVEN,
|
||||
extra_headers: Headers | None = None,
|
||||
disable_strict_validation: Optional[bool] | None = None,
|
||||
timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
|
||||
) -> AsyncTaskStatus:
|
||||
_cast_type = AsyncTaskStatus
|
||||
|
||||
if disable_strict_validation:
|
||||
_cast_type = object
|
||||
return self._post(
|
||||
"/async/chat/completions",
|
||||
body={
|
||||
"model": model,
|
||||
"request_id": request_id,
|
||||
"temperature": temperature,
|
||||
"top_p": top_p,
|
||||
"do_sample": do_sample,
|
||||
"max_tokens": max_tokens,
|
||||
"seed": seed,
|
||||
"messages": messages,
|
||||
"stop": stop,
|
||||
"sensitive_word_check": sensitive_word_check,
|
||||
"tools": tools,
|
||||
"tool_choice": tool_choice,
|
||||
},
|
||||
options=make_user_request_input(
|
||||
extra_headers=extra_headers, timeout=timeout
|
||||
),
|
||||
cast_type=_cast_type,
|
||||
enable_stream=False,
|
||||
)
|
||||
|
||||
def retrieve_completion_result(
|
||||
self,
|
||||
id: str,
|
||||
extra_headers: Headers | None = None,
|
||||
disable_strict_validation: Optional[bool] | None = None,
|
||||
timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
|
||||
) -> Union[AsyncCompletion, AsyncTaskStatus]:
|
||||
_cast_type = Union[AsyncCompletion,AsyncTaskStatus]
|
||||
if disable_strict_validation:
|
||||
_cast_type = object
|
||||
return self._get(
|
||||
path=f"/async-result/{id}",
|
||||
cast_type=_cast_type,
|
||||
options=make_user_request_input(
|
||||
extra_headers=extra_headers,
|
||||
timeout=timeout
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
|
|
@ -0,0 +1,16 @@
|
|||
from typing import TYPE_CHECKING
|
||||
from .completions import Completions
|
||||
from .async_completions import AsyncCompletions
|
||||
from ...core._base_api import BaseAPI
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from ..._client import ZhipuAI
|
||||
|
||||
|
||||
class Chat(BaseAPI):
|
||||
completions: Completions
|
||||
|
||||
def __init__(self, client: "ZhipuAI") -> None:
|
||||
super().__init__(client)
|
||||
self.completions = Completions(client)
|
||||
self.asyncCompletions = AsyncCompletions(client)
|
||||
|
|
@ -0,0 +1,71 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from typing import Union, List, Optional, TYPE_CHECKING
|
||||
|
||||
import httpx
|
||||
from typing_extensions import Literal
|
||||
|
||||
from ...core._base_api import BaseAPI
|
||||
from ...core._base_type import NotGiven, NOT_GIVEN, Headers
|
||||
from ...core._http_client import make_user_request_input
|
||||
from ...core._sse_client import StreamResponse
|
||||
from ...types.chat.chat_completion import Completion
|
||||
from ...types.chat.chat_completion_chunk import ChatCompletionChunk
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from ..._client import ZhipuAI
|
||||
|
||||
|
||||
class Completions(BaseAPI):
|
||||
def __init__(self, client: "ZhipuAI") -> None:
|
||||
super().__init__(client)
|
||||
|
||||
def create(
|
||||
self,
|
||||
*,
|
||||
model: str,
|
||||
request_id: Optional[str] | NotGiven = NOT_GIVEN,
|
||||
do_sample: Optional[Literal[False]] | Literal[True] | NotGiven = NOT_GIVEN,
|
||||
stream: Optional[Literal[False]] | Literal[True] | NotGiven = NOT_GIVEN,
|
||||
temperature: Optional[float] | NotGiven = NOT_GIVEN,
|
||||
top_p: Optional[float] | NotGiven = NOT_GIVEN,
|
||||
max_tokens: int | NotGiven = NOT_GIVEN,
|
||||
seed: int | NotGiven = NOT_GIVEN,
|
||||
messages: Union[str, List[str], List[int], object, None],
|
||||
stop: Optional[Union[str, List[str], None]] | NotGiven = NOT_GIVEN,
|
||||
sensitive_word_check: Optional[object] | NotGiven = NOT_GIVEN,
|
||||
tools: Optional[object] | NotGiven = NOT_GIVEN,
|
||||
tool_choice: str | NotGiven = NOT_GIVEN,
|
||||
extra_headers: Headers | None = None,
|
||||
disable_strict_validation: Optional[bool] | None = None,
|
||||
timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
|
||||
) -> Completion | StreamResponse[ChatCompletionChunk]:
|
||||
_cast_type = Completion
|
||||
_stream_cls = StreamResponse[ChatCompletionChunk]
|
||||
if disable_strict_validation:
|
||||
_cast_type = object
|
||||
_stream_cls = StreamResponse[object]
|
||||
return self._post(
|
||||
"/chat/completions",
|
||||
body={
|
||||
"model": model,
|
||||
"request_id": request_id,
|
||||
"temperature": temperature,
|
||||
"top_p": top_p,
|
||||
"do_sample": do_sample,
|
||||
"max_tokens": max_tokens,
|
||||
"seed": seed,
|
||||
"messages": messages,
|
||||
"stop": stop,
|
||||
"sensitive_word_check": sensitive_word_check,
|
||||
"stream": stream,
|
||||
"tools": tools,
|
||||
"tool_choice": tool_choice,
|
||||
},
|
||||
options=make_user_request_input(
|
||||
extra_headers=extra_headers,
|
||||
),
|
||||
cast_type=_cast_type,
|
||||
enable_stream=stream or False,
|
||||
stream_cls=_stream_cls,
|
||||
)
|
||||
|
|
@ -0,0 +1,49 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from typing import Union, List, Optional, TYPE_CHECKING
|
||||
|
||||
import httpx
|
||||
|
||||
from ..core._base_api import BaseAPI
|
||||
from ..core._base_type import NotGiven, NOT_GIVEN, Headers
|
||||
from ..core._http_client import make_user_request_input
|
||||
from ..types.embeddings import EmbeddingsResponded
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from .._client import ZhipuAI
|
||||
|
||||
|
||||
class Embeddings(BaseAPI):
|
||||
def __init__(self, client: "ZhipuAI") -> None:
|
||||
super().__init__(client)
|
||||
|
||||
def create(
|
||||
self,
|
||||
*,
|
||||
input: Union[str, List[str], List[int], List[List[int]]],
|
||||
model: Union[str],
|
||||
encoding_format: str | NotGiven = NOT_GIVEN,
|
||||
user: str | NotGiven = NOT_GIVEN,
|
||||
sensitive_word_check: Optional[object] | NotGiven = NOT_GIVEN,
|
||||
extra_headers: Headers | None = None,
|
||||
disable_strict_validation: Optional[bool] | None = None,
|
||||
timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
|
||||
) -> EmbeddingsResponded:
|
||||
_cast_type = EmbeddingsResponded
|
||||
if disable_strict_validation:
|
||||
_cast_type = object
|
||||
return self._post(
|
||||
"/embeddings",
|
||||
body={
|
||||
"input": input,
|
||||
"model": model,
|
||||
"encoding_format": encoding_format,
|
||||
"user": user,
|
||||
"sensitive_word_check": sensitive_word_check,
|
||||
},
|
||||
options=make_user_request_input(
|
||||
extra_headers=extra_headers, timeout=timeout
|
||||
),
|
||||
cast_type=_cast_type,
|
||||
enable_stream=False,
|
||||
)
|
||||
|
|
@ -0,0 +1,78 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import httpx
|
||||
|
||||
from ..core._base_api import BaseAPI
|
||||
from ..core._base_type import NOT_GIVEN, Body, Query, Headers, NotGiven, FileTypes
|
||||
from ..core._files import is_file_content
|
||||
from ..core._http_client import (
|
||||
make_user_request_input,
|
||||
)
|
||||
from ..types.file_object import FileObject, ListOfFileObject
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from .._client import ZhipuAI
|
||||
|
||||
__all__ = ["Files"]
|
||||
|
||||
|
||||
class Files(BaseAPI):
|
||||
|
||||
def __init__(self, client: "ZhipuAI") -> None:
|
||||
super().__init__(client)
|
||||
|
||||
def create(
|
||||
self,
|
||||
*,
|
||||
file: FileTypes,
|
||||
purpose: str,
|
||||
extra_headers: Headers | None = None,
|
||||
timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
|
||||
) -> FileObject:
|
||||
if not is_file_content(file):
|
||||
prefix = f"Expected file input `{file!r}`"
|
||||
raise RuntimeError(
|
||||
f"{prefix} to be bytes, an io.IOBase instance, PathLike or a tuple but received {type(file)} instead."
|
||||
) from None
|
||||
files = [("file", file)]
|
||||
|
||||
extra_headers = {"Content-Type": "multipart/form-data", **(extra_headers or {})}
|
||||
|
||||
return self._post(
|
||||
"/files",
|
||||
body={
|
||||
"purpose": purpose,
|
||||
},
|
||||
files=files,
|
||||
options=make_user_request_input(
|
||||
extra_headers=extra_headers, timeout=timeout
|
||||
),
|
||||
cast_type=FileObject,
|
||||
)
|
||||
|
||||
def list(
|
||||
self,
|
||||
*,
|
||||
purpose: str | NotGiven = NOT_GIVEN,
|
||||
limit: int | NotGiven = NOT_GIVEN,
|
||||
after: str | NotGiven = NOT_GIVEN,
|
||||
order: str | NotGiven = NOT_GIVEN,
|
||||
extra_headers: Headers | None = None,
|
||||
timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
|
||||
) -> ListOfFileObject:
|
||||
return self._get(
|
||||
"/files",
|
||||
cast_type=ListOfFileObject,
|
||||
options=make_user_request_input(
|
||||
extra_headers=extra_headers,
|
||||
timeout=timeout,
|
||||
query={
|
||||
"purpose": purpose,
|
||||
"limit": limit,
|
||||
"after": after,
|
||||
"order": order,
|
||||
},
|
||||
),
|
||||
)
|
||||
|
|
@ -0,0 +1,15 @@
|
|||
from typing import TYPE_CHECKING
|
||||
from .jobs import Jobs
|
||||
from ...core._base_api import BaseAPI
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from ..._client import ZhipuAI
|
||||
|
||||
|
||||
class FineTuning(BaseAPI):
|
||||
jobs: Jobs
|
||||
|
||||
def __init__(self, client: "ZhipuAI") -> None:
|
||||
super().__init__(client)
|
||||
self.jobs = Jobs(client)
|
||||
|
||||
|
|
@ -0,0 +1,115 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from typing import Optional, TYPE_CHECKING
|
||||
|
||||
import httpx
|
||||
|
||||
from ...core._base_api import BaseAPI
|
||||
from ...core._base_type import NOT_GIVEN, Headers, NotGiven
|
||||
from ...core._http_client import (
|
||||
make_user_request_input,
|
||||
)
|
||||
from ...types.fine_tuning import (
|
||||
FineTuningJob,
|
||||
job_create_params,
|
||||
ListOfFineTuningJob,
|
||||
FineTuningJobEvent,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from ..._client import ZhipuAI
|
||||
|
||||
__all__ = ["Jobs"]
|
||||
|
||||
|
||||
class Jobs(BaseAPI):
|
||||
|
||||
def __init__(self, client: "ZhipuAI") -> None:
|
||||
super().__init__(client)
|
||||
|
||||
def create(
|
||||
self,
|
||||
*,
|
||||
model: str,
|
||||
training_file: str,
|
||||
hyperparameters: job_create_params.Hyperparameters | NotGiven = NOT_GIVEN,
|
||||
suffix: Optional[str] | NotGiven = NOT_GIVEN,
|
||||
request_id: Optional[str] | NotGiven = NOT_GIVEN,
|
||||
validation_file: Optional[str] | NotGiven = NOT_GIVEN,
|
||||
extra_headers: Headers | None = None,
|
||||
timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
|
||||
) -> FineTuningJob:
|
||||
return self._post(
|
||||
"/fine_tuning/jobs",
|
||||
body={
|
||||
"model": model,
|
||||
"training_file": training_file,
|
||||
"hyperparameters": hyperparameters,
|
||||
"suffix": suffix,
|
||||
"validation_file": validation_file,
|
||||
"request_id": request_id,
|
||||
},
|
||||
options=make_user_request_input(
|
||||
extra_headers=extra_headers, timeout=timeout
|
||||
),
|
||||
cast_type=FineTuningJob,
|
||||
)
|
||||
|
||||
def retrieve(
|
||||
self,
|
||||
fine_tuning_job_id: str,
|
||||
*,
|
||||
extra_headers: Headers | None = None,
|
||||
timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
|
||||
) -> FineTuningJob:
|
||||
return self._get(
|
||||
f"/fine_tuning/jobs/{fine_tuning_job_id}",
|
||||
options=make_user_request_input(
|
||||
extra_headers=extra_headers, timeout=timeout
|
||||
),
|
||||
cast_type=FineTuningJob,
|
||||
)
|
||||
|
||||
def list(
|
||||
self,
|
||||
*,
|
||||
after: str | NotGiven = NOT_GIVEN,
|
||||
limit: int | NotGiven = NOT_GIVEN,
|
||||
extra_headers: Headers | None = None,
|
||||
timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
|
||||
) -> ListOfFineTuningJob:
|
||||
return self._get(
|
||||
"/fine_tuning/jobs",
|
||||
cast_type=ListOfFineTuningJob,
|
||||
options=make_user_request_input(
|
||||
extra_headers=extra_headers,
|
||||
timeout=timeout,
|
||||
query={
|
||||
"after": after,
|
||||
"limit": limit,
|
||||
},
|
||||
),
|
||||
)
|
||||
|
||||
def list_events(
|
||||
self,
|
||||
fine_tuning_job_id: str,
|
||||
*,
|
||||
after: str | NotGiven = NOT_GIVEN,
|
||||
limit: int | NotGiven = NOT_GIVEN,
|
||||
extra_headers: Headers | None = None,
|
||||
timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
|
||||
) -> FineTuningJobEvent:
|
||||
|
||||
return self._get(
|
||||
f"/fine_tuning/jobs/{fine_tuning_job_id}/events",
|
||||
cast_type=FineTuningJobEvent,
|
||||
options=make_user_request_input(
|
||||
extra_headers=extra_headers,
|
||||
timeout=timeout,
|
||||
query={
|
||||
"after": after,
|
||||
"limit": limit,
|
||||
},
|
||||
),
|
||||
)
|
||||
|
|
@ -0,0 +1,55 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from typing import Union, List, Optional, TYPE_CHECKING
|
||||
|
||||
import httpx
|
||||
|
||||
from ..core._base_api import BaseAPI
|
||||
from ..core._base_type import NotGiven, NOT_GIVEN, Headers
|
||||
from ..core._http_client import make_user_request_input
|
||||
from ..types.image import ImagesResponded
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from .._client import ZhipuAI
|
||||
|
||||
|
||||
class Images(BaseAPI):
|
||||
def __init__(self, client: "ZhipuAI") -> None:
|
||||
super().__init__(client)
|
||||
|
||||
def generations(
|
||||
self,
|
||||
*,
|
||||
prompt: str,
|
||||
model: str | NotGiven = NOT_GIVEN,
|
||||
n: Optional[int] | NotGiven = NOT_GIVEN,
|
||||
quality: Optional[str] | NotGiven = NOT_GIVEN,
|
||||
response_format: Optional[str] | NotGiven = NOT_GIVEN,
|
||||
size: Optional[str] | NotGiven = NOT_GIVEN,
|
||||
style: Optional[str] | NotGiven = NOT_GIVEN,
|
||||
user: str | NotGiven = NOT_GIVEN,
|
||||
extra_headers: Headers | None = None,
|
||||
disable_strict_validation: Optional[bool] | None = None,
|
||||
timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
|
||||
) -> ImagesResponded:
|
||||
_cast_type = ImagesResponded
|
||||
if disable_strict_validation:
|
||||
_cast_type = object
|
||||
return self._post(
|
||||
"/images/generations",
|
||||
body={
|
||||
"prompt": prompt,
|
||||
"model": model,
|
||||
"n": n,
|
||||
"quality": quality,
|
||||
"response_format": response_format,
|
||||
"size": size,
|
||||
"style": style,
|
||||
"user": user,
|
||||
},
|
||||
options=make_user_request_input(
|
||||
extra_headers=extra_headers, timeout=timeout
|
||||
),
|
||||
cast_type=_cast_type,
|
||||
enable_stream=False,
|
||||
)
|
||||
|
|
@ -0,0 +1,17 @@
|
|||
from __future__ import annotations
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from .._client import ZhipuAI
|
||||
|
||||
|
||||
class BaseAPI:
|
||||
_client: ZhipuAI
|
||||
|
||||
def __init__(self, client: ZhipuAI) -> None:
|
||||
self._client = client
|
||||
self._delete = client.delete
|
||||
self._get = client.get
|
||||
self._post = client.post
|
||||
self._put = client.put
|
||||
self._patch = client.patch
|
||||
|
|
@ -0,0 +1,115 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from os import PathLike
|
||||
from typing import (
|
||||
TYPE_CHECKING,
|
||||
Type,
|
||||
Union,
|
||||
Mapping,
|
||||
TypeVar, IO, Tuple, Sequence, Any, List,
|
||||
)
|
||||
|
||||
import pydantic
|
||||
from typing_extensions import (
|
||||
Literal,
|
||||
override,
|
||||
)
|
||||
|
||||
|
||||
Query = Mapping[str, object]
|
||||
Body = object
|
||||
AnyMapping = Mapping[str, object]
|
||||
PrimitiveData = Union[str, int, float, bool, None]
|
||||
Data = Union[PrimitiveData, List[Any], Tuple[Any], "Mapping[str, Any]"]
|
||||
ModelT = TypeVar("ModelT", bound=pydantic.BaseModel)
|
||||
_T = TypeVar("_T")
|
||||
|
||||
if TYPE_CHECKING:
|
||||
NoneType: Type[None]
|
||||
else:
|
||||
NoneType = type(None)
|
||||
|
||||
|
||||
# Sentinel class used until PEP 0661 is accepted
|
||||
class NotGiven(pydantic.BaseModel):
|
||||
"""
|
||||
A sentinel singleton class used to distinguish omitted keyword arguments
|
||||
from those passed in with the value None (which may have different behavior).
|
||||
|
||||
For example:
|
||||
|
||||
```py
|
||||
def get(timeout: Union[int, NotGiven, None] = NotGiven()) -> Response: ...
|
||||
|
||||
get(timeout=1) # 1s timeout
|
||||
get(timeout=None) # No timeout
|
||||
get() # Default timeout behavior, which may not be statically known at the method definition.
|
||||
```
|
||||
"""
|
||||
|
||||
def __bool__(self) -> Literal[False]:
|
||||
return False
|
||||
|
||||
@override
|
||||
def __repr__(self) -> str:
|
||||
return "NOT_GIVEN"
|
||||
|
||||
|
||||
NotGivenOr = Union[_T, NotGiven]
|
||||
NOT_GIVEN = NotGiven()
|
||||
|
||||
|
||||
class Omit(pydantic.BaseModel):
|
||||
"""In certain situations you need to be able to represent a case where a default value has
|
||||
to be explicitly removed and `None` is not an appropriate substitute, for example:
|
||||
|
||||
```py
|
||||
# as the default `Content-Type` header is `application/json` that will be sent
|
||||
client.post('/upload/files', files={'file': b'my raw file content'})
|
||||
|
||||
# you can't explicitly override the header as it has to be dynamically generated
|
||||
# to look something like: 'multipart/form-data; boundary=0d8382fcf5f8c3be01ca2e11002d2983'
|
||||
client.post(..., headers={'Content-Type': 'multipart/form-data'})
|
||||
|
||||
# instead you can remove the default `application/json` header by passing Omit
|
||||
client.post(..., headers={'Content-Type': Omit()})
|
||||
```
|
||||
"""
|
||||
|
||||
def __bool__(self) -> Literal[False]:
|
||||
return False
|
||||
|
||||
|
||||
Headers = Mapping[str, Union[str, Omit]]
|
||||
|
||||
ResponseT = TypeVar(
|
||||
"ResponseT",
|
||||
bound="Union[str, None, BaseModel, List[Any], Dict[str, Any], Response, UnknownResponse, ModelBuilderProtocol, BinaryResponseContent]",
|
||||
)
|
||||
|
||||
# for user input files
|
||||
if TYPE_CHECKING:
|
||||
FileContent = Union[IO[bytes], bytes, PathLike[str]]
|
||||
else:
|
||||
FileContent = Union[IO[bytes], bytes, PathLike]
|
||||
|
||||
FileTypes = Union[
|
||||
FileContent, # file content
|
||||
Tuple[str, FileContent], # (filename, file)
|
||||
Tuple[str, FileContent, str], # (filename, file , content_type)
|
||||
Tuple[str, FileContent, str, Mapping[str, str]], # (filename, file , content_type, headers)
|
||||
]
|
||||
|
||||
RequestFiles = Union[Mapping[str, FileTypes], Sequence[Tuple[str, FileTypes]]]
|
||||
|
||||
# for httpx client supported files
|
||||
|
||||
HttpxFileContent = Union[bytes, IO[bytes]]
|
||||
HttpxFileTypes = Union[
|
||||
FileContent, # file content
|
||||
Tuple[str, HttpxFileContent], # (filename, file)
|
||||
Tuple[str, HttpxFileContent, str], # (filename, file , content_type)
|
||||
Tuple[str, HttpxFileContent, str, Mapping[str, str]], # (filename, file , content_type, headers)
|
||||
]
|
||||
|
||||
HttpxRequestFiles = Union[Mapping[str, HttpxFileTypes], Sequence[Tuple[str, HttpxFileTypes]]]
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue