id stringlengths 6 6 | text stringlengths 20 17.2k | title stringclasses 1
value |
|---|---|---|
176250 | import nox
@nox.session(reuse_venv=True, name="test-pydantic-v1")
def test_pydantic_v1(session: nox.Session) -> None:
session.install("-r", "requirements-dev.lock")
session.install("pydantic<2")
session.run("pytest", "--showlocals", "--ignore=tests/functional", *session.posargs) | |
176299 | @pytest.mark.respx(base_url=base_url)
@pytest.mark.skipif(not PYDANTIC_V2, reason="dataclasses only supported in v2")
def test_parse_pydantic_dataclass(client: OpenAI, respx_mock: MockRouter, monkeypatch: pytest.MonkeyPatch) -> None:
from pydantic.dataclasses import dataclass
@dataclass
class CalendarEvent... | |
176375 | from azure.identity import DefaultAzureCredential, get_bearer_token_provider
from openai import AzureOpenAI
token_provider = get_bearer_token_provider(DefaultAzureCredential(), "https://cognitiveservices.azure.com/.default")
# may change in the future
# https://learn.microsoft.com/en-us/azure/ai-services/openai/ref... | |
176376 | from openai import AzureOpenAI
# may change in the future
# https://learn.microsoft.com/en-us/azure/ai-services/openai/reference#rest-api-versioning
api_version = "2023-07-01-preview"
# gets the API Key from environment variable AZURE_OPENAI_API_KEY
client = AzureOpenAI(
api_version=api_version,
# https://lea... | |
176408 | class BaseAPIResponse(Generic[R]):
_cast_to: type[R]
_client: BaseClient[Any, Any]
_parsed_by_type: dict[type[Any], Any]
_is_sse_stream: bool
_stream_cls: type[Stream[Any]] | type[AsyncStream[Any]] | None
_options: FinalRequestOptions
http_response: httpx.Response
retries_taken: int
... | |
176413 | def _parse(self, *, to: type[_T] | None = None) -> R | _T:
# unwrap `Annotated[T, ...]` -> `T`
if to and is_annotated_type(to):
to = extract_type_arg(to, 0)
if self._stream:
if to:
if not is_stream_class_type(to):
raise TypeError(f"Exp... | |
176427 | class BaseModel(pydantic.BaseModel):
if PYDANTIC_V2:
model_config: ClassVar[ConfigDict] = ConfigDict(
extra="allow", defer_build=coerce_boolean(os.environ.get("DEFER_PYDANTIC_BUILD", "true"))
)
else:
@property
@override
def model_fields_set(self) -> set[str]:... | |
176465 | # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
from __future__ import annotations
from typing import List, Union, Iterable
from typing_extensions import Literal, Required, TypedDict
from .embedding_model import EmbeddingModel
__all__ = ["EmbeddingCreateParams"]
class Embeddi... | |
176819 | from typing import Any
from typing_extensions import ClassVar
import pydantic
from .. import _models
from .._compat import PYDANTIC_V2, ConfigDict
class BaseModel(_models.BaseModel):
if PYDANTIC_V2:
model_config: ClassVar[ConfigDict] = ConfigDict(extra="ignore", arbitrary_types_allowed=True)
else:
... | |
176842 | from __future__ import annotations
import inspect
from typing import Any, TypeVar
from typing_extensions import TypeGuard
import pydantic
from .._types import NOT_GIVEN
from .._utils import is_dict as _is_dict, is_list
from .._compat import PYDANTIC_V2, model_json_schema
_T = TypeVar("_T")
def to_strict_json_sche... | |
177081 | @is_pipeline_test
@require_torch_or_tf
class TextGenerationPipelineTests(unittest.TestCase):
model_mapping = MODEL_FOR_CAUSAL_LM_MAPPING
tf_model_mapping = TF_MODEL_FOR_CAUSAL_LM_MAPPING
@require_torch
def test_small_model_pt(self):
text_generator = pipeline(task="text-generation", model="sshle... | |
177082 | _model_tf(self):
text_generator = pipeline(task="text-generation", model="sshleifer/tiny-ctrl", framework="tf")
# Using `do_sample=False` to force deterministic output
outputs = text_generator("This is a test", do_sample=False)
self.assertEqual(
outputs,
[
... | |
177098 | # Copyright 2020 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicabl... | |
177444 | @slow
@require_torch_gpu
@require_bitsandbytes
@require_read_token
def test_11b_model_integration_multi_image_generate(self):
processor = AutoProcessor.from_pretrained(self.instruct_model_checkpoint)
# Prepare inputs
image1 = Image.open(requests.get("https://llava-vl.github.io/s... | |
177519 | # coding=utf-8
# Copyright 2021, The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless ... | |
177521 | @require_torch
@require_sentencepiece
@require_tokenizers
class MarianIntegrationTest(unittest.TestCase):
src = "en"
tgt = "de"
src_text = [
"I am a small frog.",
"Now I can forget the 100 words of german that I know.",
"Tom asked his teacher for advice.",
"That's how I would... | |
179390 | # Testing mixed int8 quantization

The following is the recipe on how to effectively debug `bitsandbytes` integration on Hugging Face `transformers`.
## Library requirements
+ `transformers>=4.22.... | |
179391 | # coding=utf-8
# Copyright 2022 The HuggingFace Team Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a clone of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable... | |
180210 | <!--Copyright 2023 The HuggingFace Team. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed... | |
180531 | ce/optimum-benchmark)库进行了一些速度、吞吐量和延迟基准测试。
请注意,在编写本文档部分时,可用的量化方法包括:`awq`、`gptq`和`bitsandbytes`。
基准测试在一台NVIDIA-A100实例上运行,使用[`TheBloke/Mistral-7B-v0.1-AWQ`](https://huggingface.co/TheBloke/Mistral-7B-v0.1-AWQ)作为AWQ模型,[`TheBloke/Mistral-7B-v0.1-GPTQ`](https://huggingface.co/TheBloke/Mistral-7B-v0.1-GPTQ)作为GPTQ模型。我们还将其与`b... | |
181066 | TQ [[gptq]]
<Tip>
PEFT를 활용한 GPTQ 양자화를 사용해보시려면 이 [노트북](https://colab.research.google.com/drive/1_TIrmuKOFhuRRiTWN94iLKUFu6ZX4ceb)을 참고하시고, 자세한 내용은 이 [블로그 게시물](https://huggingface.co/blog/gptq-integration)에서 확인하세요!
</Tip>
[AutoGPTQ](https://github.com/PanQiWei/AutoGPTQ) 라이브러리는 GPTQ 알고리즘을 구현합니다. 이는 훈련 후 양자화 기법으로, 가중치 행... | |
181258 | hoosing a chat model
There are an enormous number of different chat models available on the [Hugging Face Hub](https://huggingface.co/models?pipeline_tag=text-generation&sort=trending),
and new users often feel very overwhelmed by the selection offered. Don't be, though! You really need to just focus on
two important ... | |
181285 | <!--Copyright 2023 The HuggingFace Team. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed... | |
181339 | <!--Copyright 2023 The HuggingFace Team. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed... | |
181343 | vanced: How do chat templates work?
The chat template for a model is stored on the `tokenizer.chat_template` attribute. If no chat template is set, the
default template for that model class is used instead. Let's take a look at a `Zephyr` chat template, though note this
one is a little simplified from the actual one!
... | |
181344 | vanced: Adding and editing chat templates
### How do I create a chat template?
Simple, just write a jinja template and set `tokenizer.chat_template`. You may find it easier to start with an
existing template from another model and simply edit it for your needs! For example, we could take the LLaMA template
above and... | |
181355 | <!--⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
rendered properly in your Markdown viewer.
-->
# Using pipelines for a webserver
<Tip>
Creating an inference engine is a complex topic, and the "best" solution
will most likely depend on your pr... | |
181385 | arameters
[`pipeline`] supports many parameters; some are task specific, and some are general to all pipelines.
In general, you can specify parameters anywhere you want:
```py
transcriber = pipeline(model="openai/whisper-large-v2", my_parameter=1)
out = transcriber(...) # This will use `my_parameter=1`.
out = trans... | |
181392 | <!--Copyright 2024 The HuggingFace Team. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed... | |
181402 | <!--Copyright 2024 The HuggingFace Team. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed... | |
181437 | <!--Copyright 2022 The HuggingFace Team. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed... | |
181440 | ad adapters with 🤗 PEFT
[[open-in-colab]]
[Parameter-Efficient Fine Tuning (PEFT)](https://huggingface.co/blog/peft) methods freeze the pretrained model parameters during fine-tuning and add a small number of trainable parameters (the adapters) on top of it. The adapters are trained to learn task-specific informatio... | |
181529 | <!--Copyright 2023 The HuggingFace Team. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed... | |
181531 | oning
Reasoning is one of the most difficult tasks for LLMs, and achieving good results often requires applying advanced prompting techniques, like
[Chain-of-thought](#chain-of-thought).
Let's try if we can make a model reason about a simple arithmetics task with a basic prompt:
```python
>>> torch.manual_seed(5) ... | |
181580 | <!--Copyright 2022 The HuggingFace Team. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed... | |
181843 | <!--Copyright 2020 The HuggingFace Team. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed... | |
181874 | ameleon
## Overview
The Chameleon model was proposed in [Chameleon: Mixed-Modal Early-Fusion Foundation Models
](https://arxiv.org/abs/2405.09818v1) by META AI Chameleon Team. Chameleon is a Vision-Language Model that use vector quantization to tokenize images which enables the model to generate multimodal output. Th... | |
181939 | <!--Copyright 2024 The HuggingFace Team. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed... | |
182030 | can access the TPU cores at a time. This means that if multiple team members
are trying to connect to the TPU cores errors, such as:
```
libtpu.so already in used by another process. Not attempting to load libtpu.so in this process.
```
are thrown. As a conclusion, we recommend every team member to create her/his ow... | |
182171 | import gzip
import json
import multiprocessing
import os
import re
import shutil
import time
from pathlib import Path
import numpy as np
from arguments import PreprocessingArguments
from datasets import load_dataset
from huggingface_hub.utils import insecure_hashlib
from minhash_deduplication import deduplicate_datase... | |
183779 | @add_end_docstrings(build_pipeline_init_args(has_tokenizer=True))
class Text2TextGenerationPipeline(Pipeline):
"""
Pipeline for text to text generation using seq2seq models.
Example:
```python
>>> from transformers import pipeline
>>> generator = pipeline(model="mrm8488/t5-base-finetuned-ques... | |
183794 | def check_task(task: str) -> Tuple[str, Dict, Any]:
"""
Checks an incoming task string, to validate it's correct and return the default Pipeline and Model classes, and
default models if they exist.
Args:
task (`str`):
The task defining which pipeline will be returned. Currently acce... | |
183795 | Utility factory method to build a [`Pipeline`].
Pipelines are made of:
- A [tokenizer](tokenizer) in charge of mapping raw textual input to token.
- A [model](model) to make predictions from the inputs.
- Some (optional) post processing for enhancing model's output.
Args:
task... | |
183816 | @add_end_docstrings(build_pipeline_init_args(has_tokenizer=True))
class TextGenerationPipeline(Pipeline):
"""
Language generation pipeline using any `ModelWithLMHead`. This pipeline predicts the words that will follow a
specified text prompt. When the underlying model is a conversational model, it can also ... | |
183817 | def __call__(self, text_inputs, **kwargs):
"""
Complete the prompt(s) given as inputs.
Args:
text_inputs (`str`, `List[str]`, List[Dict[str, str]], or `List[List[Dict[str, str]]]`):
One or several prompts (or one list of prompts) to complete. If strings or a list of ... | |
183840 | def save_pretrained(
self,
save_directory: Union[str, os.PathLike],
safe_serialization: bool = True,
**kwargs,
):
"""
Save the pipeline's model and tokenizer.
Args:
save_directory (`str` or `os.PathLike`):
A path to the directory w... | |
183905 | MMY_INPUTS = [[7, 6, 0, 0, 1], [1, 2, 3, 0, 0], [0, 0, 0, 4, 5]]
DUMMY_MASK = [[1, 1, 1, 1, 1], [1, 1, 1, 0, 0], [0, 0, 0, 1, 1]]
def check_min_version(min_version):
if version.parse(__version__) < version.parse(min_version):
if "dev" in min_version:
error_message = (
"This exa... | |
183974 | @dataclass
class GPTQConfig(QuantizationConfigMixin):
"""
This is a wrapper class about all possible attributes and features that you can play with a model that has been
loaded using `optimum` api for gptq quantization relying on auto_gptq backend.
Args:
bits (`int`):
The number of ... | |
184701 | @add_start_docstrings(
"The MARIAN Model with a language modeling head. Can be used for translation.", MARIAN_START_DOCSTRING
)
class FlaxMarianMTModel(FlaxMarianPreTrainedModel):
module_class = FlaxMarianMTModule
dtype: jnp.dtype = jnp.float32
@add_start_docstrings(MARIAN_DECODE_INPUTS_DOCSTRING)
... | |
189980 | def load_adapter(
self,
peft_model_id: Optional[str] = None,
adapter_name: Optional[str] = None,
revision: Optional[str] = None,
token: Optional[str] = None,
device_map: Optional[str] = "auto",
max_memory: Optional[str] = None,
offload_folder: Optional[str... | |
189981 | def add_adapter(self, adapter_config, adapter_name: Optional[str] = None) -> None:
r"""
If you are not familiar with adapters and PEFT methods, we invite you to read more about them on the PEFT
official documentation: https://huggingface.co/docs/peft
Adds a fresh new adapter to the curr... | |
190144 | def _validate_model_kwargs(self, model_kwargs: Dict[str, Any]):
"""Validates model kwargs for generation. Generate argument typos will also be caught here."""
# If a `Cache` instance is passed, checks whether the model is compatible with it
if isinstance(model_kwargs.get("past_key_values", None)... | |
190387 | import logging
from abc import ABC
from typing import Awaitable, Callable, List, Optional, Union
from urllib.parse import urljoin
import aiohttp
import tiktoken
from azure.core.credentials import AzureKeyCredential
from azure.core.credentials_async import AsyncTokenCredential
from azure.identity.aio import get_bearer_... | |
190392 | import json
from typing import IO, AsyncGenerator
from .page import Page
from .parser import Parser
class JsonParser(Parser):
"""
Concrete parser that can parse JSON into Page objects. A top-level object becomes a single Page, while a top-level array becomes multiple Page objects.
"""
async def pars... | |
190409 | import io
import pytest
from prepdocslib.jsonparser import JsonParser
@pytest.mark.asyncio
async def test_jsonparser_single_obj():
file = io.StringIO('{"test": "test"}')
file.name = "test.json"
jsonparser = JsonParser()
pages = [page async for page in jsonparser.parse(file)]
assert len(pages) ==... | |
190434 | import io
import openai
import openai.types
import pytest
from azure.core.credentials import AzureKeyCredential
from azure.search.documents.aio import SearchClient
from azure.search.documents.indexes.aio import SearchIndexClient
from azure.search.documents.indexes.models import (
SearchFieldDataType,
SearchInd... | |
190648 | ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 225.1/225.1 kB 11.7 MB/s eta 0:00:00
[19:24:01+0000] Downloading PyJWT-2.8.0-py3-none-any.whl (22 kB)
[19:24:07+0000] Installing collected packages: pytz, fixedint, azure-common, zipp, wrapt, urllib3, tzdata, typing-extensions, types-pytz, types-pillow, tqdm, tenacity, sniffio, si... | |
190651 | # Local development of Chat App
You can only run locally **after** having successfully run the `azd up` command. If you haven't yet, follow the steps in [Azure deployment](../README.md#azure-deployment) above.
1. Run `azd auth login`
2. Change dir to `app`
3. Run `./start.ps1` or `./start.sh` or run the "VS Code Task... | |
190657 | # Productionizing the Chat App
This sample is designed to be a starting point for your own production application,
but you should do a thorough review of the security and performance before deploying
to production. Here are some things to consider:
* [Azure resource configuration](#azure-resource-configuration)
* [Ad... | |
190832 | import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { ChatOpenAI } from "@langchain/openai";
import { PromptTemplate } from "@langchain/core/prompts";
export const runtime = "edge";
const TEMPLATE = `Extract the requested fields from the input.
The field "entity" refers to the ... | |
190850 | `# QA and Chat over Documents
Chat and Question-Answering (QA) over \`data\` are popular LLM use-cases.
\`data\` can include many things, including:
* \`Unstructured data\` (e.g., PDFs)
* \`Structured data\` (e.g., SQL)
* \`Code\` (e.g., Python)
Below we will review Chat and QA on \`Unstructured data\`.
.
\`stuff\` is commonly used because it simply "stuffs" all retrieved documents into the prompt.
The [loadQAChain](/docs/modules/chains/document/) methods are easy ways to pass docu... | |
190852 | . Note that if you want to change whether the agent remembers intermediate steps,
how the long the retained buffer is, or anything like that you should change this part.
\`\`\`typescript
import { OpenAIAgentTokenBufferMemory } from "langchain/agents/toolkits";
const memory = new OpenAIAgentTokenBufferMemory({
llm: ... | |
190861 | # Development Instructions
This project uses the testing, build and release standards specified
by the PyPA organization and documented at
https://packaging.python.org.
## Setup
Set up a virtual environment and install the project's requirements
and dev requirements:
```
python3 -m venv venv # Only need to do ... | |
190904 | <p align="center">
<a href="https://trychroma.com"><img src="https://user-images.githubusercontent.com/891664/227103090-6624bf7d-9524-4e05-9d2c-c28d5d451481.png" alt="Chroma logo"></a>
</p>
<p align="center">
<b>Chroma - the open-source embedding database</b>. <br />
This package is for the the Python HTTP c... | |
190974 | ## chromadb
Chroma is the open-source embedding database. Chroma makes it easy to build LLM apps by making knowledge, facts, and skills pluggable for LLMs.
This package gives you a JS/TS interface to talk to a backend Chroma DB over REST.
[Learn more about Chroma](https://github.com/chroma-core/chroma)
- [💬 Commun... | |
190990 | import {
afterAll,
beforeAll,
beforeEach,
describe,
expect,
test,
} from "@jest/globals";
import { DOCUMENTS, EMBEDDINGS, IDS, METADATAS } from "./data";
import { ChromaValueError, InvalidCollectionError } from "../src/Errors";
import { DefaultEmbeddingFunction } from "../src/embeddings/DefaultEmbeddingFunc... | |
191321 | from typing import Dict, Optional
import logging
from chromadb.api.client import Client as ClientCreator
from chromadb.api.client import AdminClient as AdminClientCreator
from chromadb.api.async_client import AsyncClient as AsyncClientCreator
from chromadb.auth.token_authn import TokenTransportHeader
import chromadb.co... | |
191325 | from abc import abstractmethod
from typing import Dict, Optional, Type
from overrides import overrides, EnforceOverrides
class ChromaError(Exception, EnforceOverrides):
trace_id: Optional[str] = None
def code(self) -> int:
"""Return an appropriate HTTP response code for this error"""
return 4... | |
191408 | from typing import Any, Dict, List, Optional, cast
from hypothesis import given, settings, HealthCheck
import pytest
from chromadb.api import ClientAPI
from chromadb.test.property import invariants
from chromadb.api.types import (
Document,
Embedding,
Embeddings,
GetResult,
IDs,
Metadata,
Me... | |
191516 | import logging
from typing import Mapping, Optional, cast
from chromadb.api.types import Documents, EmbeddingFunction, Embeddings
logger = logging.getLogger(__name__)
class OpenAIEmbeddingFunction(EmbeddingFunction[Documents]):
def __init__(
self,
api_key: Optional[str] = None,
model_nam... | |
191518 | import logging
from typing import Any, Dict, cast
from chromadb.api.types import Documents, EmbeddingFunction, Embeddings
logger = logging.getLogger(__name__)
class SentenceTransformerEmbeddingFunction(EmbeddingFunction[Documents]):
# Since we do dynamic imports we have to type this as Any
models: Dict[str,... | |
191566 | from typing import Optional, Union, TypeVar, List, Dict, Any, Tuple, cast
from numpy.typing import NDArray
import numpy as np
from typing_extensions import TypedDict, Protocol, runtime_checkable
from enum import Enum
from pydantic import Field
import chromadb.errors as errors
from chromadb.types import (
Metadata,
... | |
191587 | class AsyncCollection(CollectionCommon["AsyncServerAPI"]):
async def add(
self,
ids: OneOrMany[ID],
embeddings: Optional[
Union[
OneOrMany[Embedding],
OneOrMany[PyEmbedding],
]
] = None,
metadatas: Optional[OneOrMany[Met... | |
191592 | from typing import TYPE_CHECKING, Optional, Union
import numpy as np
from chromadb.api.models.CollectionCommon import CollectionCommon
from chromadb.api.types import (
URI,
CollectionMetadata,
Embedding,
PyEmbedding,
Include,
Metadata,
Document,
Image,
Where,
IDs,
GetResult,... | |
191752 | use chroma_distance::DistanceFunction;
use criterion::{criterion_group, criterion_main, Criterion};
fn distance_metrics(c: &mut Criterion) {
c.bench_function("distance_metrics", |b| {
let mut x: Vec<f32> = Vec::with_capacity(786);
for _ in 0..x.capacity() {
x.push(rand::random());
... | |
191774 | fn main() -> Result<(), Box<dyn std::error::Error>> {
// Tell cargo to rerun this build script if the bindings change.
println!("cargo:rerun-if-changed=bindings.cpp");
// Compile the hnswlib bindings.
cc::Build::new()
.cpp(true)
.file("bindings.cpp")
.flag("-std=c++11")
.... | |
192089 | ---
title: "🔍 Troubleshooting"
---
This page is a list of common gotchas or issues and how to fix them.
If you don't see your problem listed here, please also search the [Github Issues](https://github.com/chroma-core/chroma/issues).
## Using .get or .query, embeddings say `None`
This is actually not an error. Embe... | |
192104 | ---
title: OpenAI
---
{% tabs group="code-lang" hideContent=true %}
{% tab label="Python" %}
{% /tab %}
{% tab label="Javascript" %}
{% /tab %}
{% /tabs %}
Chroma provides a convenient wrapper around OpenAI's embedding API. This embedding function runs remotely on OpenAI's servers, and requires an API key. You can ge... | |
192109 | ---
title: 🦜️🔗 Langchain
---
## Langchain - Python
- [LangChain + Chroma](https://blog.langchain.dev/langchain-chroma/) on the LangChain blog
- [Harrison's `chroma-langchain` demo repo](https://github.com/hwchase17/chroma-langchain)
- [question answering over documents](https://github.com/hwchase17/chroma-langcha... | |
192117 | ---
title: Hugging Face
---
{% tabs group="code-lang" hideContent=true %}
{% tab label="Python" %}
{% /tab %}
{% tab label="Javascript" %}
{% /tab %}
{% /tabs %}
Chroma also provides a convenient wrapper around HuggingFace's embedding API. This embedding function runs remotely on HuggingFace's servers, and requires a... | |
192121 | ---
title: '🧬 Embeddings'
---
Embeddings are the A.I-native way to represent any kind of data, making them the perfect fit for working with all kinds of A.I-powered tools and algorithms. They can represent text, images, and soon audio and video. There are many options for creating embeddings, whether locally using an... | |
192128 | ---
title: "🧪 Usage Guide"
---
{% tabs group="code-lang" hideContent=true %}
{% tab label="Python" %}
{% /tab %}
{% tab label="Javascript" %}
{% /tab %}
{% /tabs %}
---
## Initiating a persistent Chroma client
{% tabs group="code-lang" hideTabs=true %}
{% tab label="Python" %}
```python
import chromadb
```
Yo... | |
192129 | llections
Chroma lets you manage collections of embeddings, using the `collection` primitive.
### Creating, inspecting, and deleting Collections
Chroma uses collection names in the url, so there are a few restrictions on naming them:
- The length of the name must be between 3 and 63 characters.
- The name must star... | |
192130 | ollection
{% tabs group="code-lang" hideTabs=true %}
{% tab label="Python" %}
Add data to Chroma with `.add`.
Raw documents:
```python
collection.add(
documents=["lorem ipsum...", "doc2", "doc3", ...],
metadatas=[{"chapter": "3", "verse": "16"}, {"chapter": "3", "verse": "5"}, {"chapter": "29", "verse": "11... | |
192131 | ion
You can query by a set of `query_embeddings`.
{% tabs group="code-lang" hideTabs=true %}
{% tab label="Python" %}
Chroma collections can be queried in a variety of ways, using the `.query` method.
```python
collection.query(
query_embeddings=[[11.1, 12.1, 13.1],[1.1, 2.3, 3.2], ...],
n_results=10,
w... | |
192132 | collection
{% tabs group="code-lang" hideTabs=true %}
{% tab label="Python" %}
Any property of records in a collection can be updated using `.update`.
```python
collection.update(
ids=["id1", "id2", "id3", ...],
embeddings=[[1.1, 2.3, 3.2], [4.5, 6.9, 4.4], [1.1, 2.3, 3.2], ...],
metadatas=[{"chapter": "... | |
192142 | overhaul - April 20, 2024
**If you are not using Chroma's [built-in auth system](https://docs.trychroma.com/deployment/auth), you do not need to take any action.**
This release overhauls and simplifies our authentication and authorization systems.
If you are you using Chroma's built-in auth system, you will need to u... | |
192143 | ation from >0.4.0 to 0.4.0 - July 17, 2023
What's new in this version?
- New easy way to create clients
- Changed storage method
- `.persist()` removed, `.reset()` no longer on by default
**New Clients**
```python
### in-memory ephemeral client
# before
import chromadb
client = chromadb.Client()
# after
import ch... | |
192180 | ---
title: "📖 API Cheatsheet"
---
# 📖 API Cheatsheet
{% note type="note" %}
This is a quick cheatsheet of the API. For full API docs, refer to the JS and Python docs in the sidebar.
{% /note %}
---
{% tabs group="code-lang" hideContent=true %}
{% tab label="Python" %}
{% /tab %}
{% tab label="Javascript" %}
{% /t... | |
192181 | ---
title: Collection
---
# Collection Objects
```python
class Collection(BaseModel)
```
# count
```python
def count() -> int
```
The total number of embeddings added to the database
**Returns**:
- `int` - The total number of embeddings added to the database
# add
```python
def add(ids: OneOrMany[ID],
... | |
192185 | ---
title: Client
---
## configure
```python
def configure(**kwargs) -> None
```
Override Chroma's default settings, environment variables or .env files
## EphemeralClient
```python
def EphemeralClient(settings: Optional[Settings] = None,
tenant: str = DEFAULT_TENANT,
datab... | |
192193 | import argparse
import os
from typing import List
import google.generativeai as genai
import chromadb
from chromadb.utils import embedding_functions
model = genai.GenerativeModel("gemini-pro")
def build_prompt(query: str, context: List[str]) -> str:
"""
Builds a prompt for the LLM. #
This function buil... | |
192194 | import os
import argparse
from tqdm import tqdm
import chromadb
from chromadb.utils import embedding_functions
import google.generativeai as genai
def main(
documents_directory: str = "documents",
collection_name: str = "documents_collection",
persist_directory: str = ".",
) -> None:
# Read all file... | |
192210 | import asyncio
import sys
import uuid
from pathlib import Path
import chromadb
import xai_sdk
from pypdf import PdfReader
from langchain_text_splitters import RecursiveCharacterTextSplitter, SentenceTransformersTokenTextSplitter
from tqdm import tqdm
from chromadb.utils.embedding_functions.sentence_transformer_embedd... | |
192217 | {
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"id": "initial_id",
"metadata": {
"collapsed": true,
"ExecuteTime": {
"end_time": "2023-08-30T12:48:38.227653Z",
"start_time": "2023-08-30T12:48:27.744069Z"
}
},
"outputs": [
{
"name": "stderr",
"output_ty... | |
192219 | {
"cells": [
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"# Local Peristence Demo\n",
"This notebook demonstrates how to configure Chroma to persist to disk, then load it back in. "
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
... | |
192220 | {
"cells": [
{
"cell_type": "markdown",
"id": "eae631e46b4c1115",
"metadata": {
"collapsed": false
},
"source": [
"# Chroma Authentication\n",
"\n",
"This tutorial aims to explain how authentication can be setup in Chroma.\n",
"\n",
"> ... | |
192230 | {
"cells": [
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
" # Alternative Embeddings\n",
" \n",
" This notebook demonstrates how to use alternative embedding functions.\n",
" "
]
},
{
"cell_type": "code",
... | |
192234 | {
"cells": [
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"# Where Filtering\n",
"This notebook demonstrates how to use where filtering to filter the data returned from get or query."
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.