aisberg 0.2.0__py3-none-any.whl → 0.2.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
aisberg/config.py CHANGED
@@ -1,5 +1,4 @@
1
1
  from typing import Union
2
-
3
2
  from pydantic_settings import BaseSettings, SettingsConfigDict
4
3
 
5
4
 
@@ -15,9 +14,10 @@ class Settings(BaseSettings):
15
14
  s3_secret_access_key: Union[str, None] = None
16
15
  s3_endpoint: Union[str, None] = None
17
16
 
18
- # Pour indiquer le fichier .env
19
- model_config = SettingsConfigDict(env_file=".env", env_file_encoding="utf-8")
17
+ # Config Pydantic
18
+ model_config = SettingsConfigDict(
19
+ env_file=".env", env_file_encoding="utf-8", extra="ignore"
20
+ )
20
21
 
21
22
 
22
- # Singleton partagé dans tout le SDK
23
23
  settings = Settings()
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: aisberg
3
- Version: 0.2.0
3
+ Version: 0.2.2
4
4
  Summary: Aisberg SDK for Python - A simple and powerful SDK to interact with the Aisberg API
5
5
  Author: Free Pro
6
6
  Author-email: Mathis Lambert <mathis.lambert@freepro.com>
@@ -1,7 +1,7 @@
1
1
  aisberg/__init__.py,sha256=jMX3F2Fh5JobAkRMKGAcOpmNdoxSthgR4v_oM-Yw1l0,141
2
2
  aisberg/async_client.py,sha256=0hO2lzdP2Vcb4qV619aJLrsxeXmfYj5wo0mog1bda5Q,3816
3
3
  aisberg/client.py,sha256=W1i9mh-o7f283kz2s9B2nHBCegJGN0Lgf1q0lAMNx9I,3853
4
- aisberg/config.py,sha256=6qSucVFxCBD9TiISDh2bTt7QlrjwvptTwEtcbj4Wt8k,610
4
+ aisberg/config.py,sha256=R1dvL14YeO_0VRr1nUiirWRFN8xY0Nkthurtxnnoc34,587
5
5
  aisberg/exceptions.py,sha256=T1ioitOczdkmW3-8XfPG0ta_O2WqzS1iQtzhDBucb5Y,515
6
6
  aisberg/utils.py,sha256=4wkrpC5gz8PJWw3kZqaRbd3KekrI37zlDC__JiAVitw,3552
7
7
  aisberg/abstract/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
@@ -32,15 +32,8 @@ aisberg/modules/workflows.py,sha256=AxyBwCnZkRdgKHUOAoYXMAJH6J7K-qaL1psZ-f-MKhI,
32
32
  aisberg/requests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
33
33
  aisberg/requests/async_requests.py,sha256=4J6Gj6vY5AD9lXhSTdYdAKQIqsqH9m1uaKc7XLDKWx8,2849
34
34
  aisberg/requests/sync_requests.py,sha256=ov7GDgx4C-oQ9xEZ7VQsGVY1fnuqRpPwjS0H_yH1yb8,2839
35
- aisberg-0.2.0.dist-info/licenses/LICENSE,sha256=dCGgiGa4f14s5mzTYnj1wIZNqGRVG2bUYyyk7nzKlEo,406
36
- tests/integration/test_collections_integration.py,sha256=HSs-Mhh5JNx2V6EeKo--G3xZq7pMk3z3gLReX7FJidg,3883
37
- tests/unit/test_collections_sync.py,sha256=DyizG4MIYNtBOC9TlsFdLlH5vz7USA12K9Uydlcydoo,3199
38
- tmp/test.py,sha256=8H3GxLztspwyt3_wLPtQkwdiLl--qqAn8ZaEUsXbwDE,743
39
- tmp/test_async.py,sha256=BaY3MkOIDXsersjYgnfaI43kZ42KDj5Andq5u-yO82s,4168
40
- tmp/test_collection.py,sha256=wV8AnxuaTsHxlzVPigG_qW6kr57lMkKH_bBm9eFfJ-I,1893
41
- tmp/test_doc_parse.py,sha256=G8-jpZY2cuauzUK9oEvEHjE7Dgjf6LlPFg9F8WyF49g,1188
42
- tmp/test_sync.py,sha256=87QSz728gvjTXz2JykjF0U_mNsunDYrWsXYDjkBybI8,4929
43
- aisberg-0.2.0.dist-info/METADATA,sha256=BZzpCVk1OsZQEw9oomWeK8Q50BPVi_YeCvY4JXvPX4E,5604
44
- aisberg-0.2.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
45
- aisberg-0.2.0.dist-info/top_level.txt,sha256=7_CasmLkyF_h1CVRncNuAjam-DMIeMu1Rev_LpVcWoA,18
46
- aisberg-0.2.0.dist-info/RECORD,,
35
+ aisberg-0.2.2.dist-info/licenses/LICENSE,sha256=dCGgiGa4f14s5mzTYnj1wIZNqGRVG2bUYyyk7nzKlEo,406
36
+ aisberg-0.2.2.dist-info/METADATA,sha256=GsIDsQLP8zBATgBXSXGziMDs2ax9RTMRGEUacFxUJpg,5604
37
+ aisberg-0.2.2.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
38
+ aisberg-0.2.2.dist-info/top_level.txt,sha256=Q5EmjFuum10zWgRsk-c4cGKe25F8J7HYvga4AtTwYXQ,8
39
+ aisberg-0.2.2.dist-info/RECORD,,
@@ -0,0 +1 @@
1
+ aisberg
@@ -1,3 +0,0 @@
1
- aisberg
2
- tests
3
- tmp
@@ -1,115 +0,0 @@
1
- import pytest
2
- import pytest_asyncio
3
-
4
- from aisberg.modules import AsyncCollectionsModule, SyncCollectionsModule
5
-
6
-
7
- ## Fixtures for asynchronous tests
8
- @pytest_asyncio.fixture
9
- async def async_parent():
10
- from aisberg import AisbergAsyncClient
11
-
12
- return await AisbergAsyncClient().initialize()
13
-
14
-
15
- @pytest_asyncio.fixture
16
- async def async_collections_module(async_parent):
17
- return AsyncCollectionsModule(parent=async_parent, client=async_parent._client)
18
-
19
-
20
- ## Fixtures for synchronous tests
21
- @pytest.fixture()
22
- def sync_parent():
23
- from aisberg import AisbergClient
24
-
25
- return AisbergClient()
26
-
27
-
28
- @pytest.fixture
29
- def sync_collections_module(sync_parent):
30
- return SyncCollectionsModule(parent=sync_parent, client=sync_parent._client)
31
-
32
-
33
- ## ---------------------------------------------------------
34
- ## Tests for asynchronous collections module
35
- ## ---------------------------------------------------------
36
- @pytest.mark.asyncio
37
- async def test_async_list_returns_groups(async_collections_module):
38
- result = await async_collections_module.list()
39
- assert isinstance(result, list)
40
- assert len(result) > 0, "Aucune collection trouvée sur l'API réelle."
41
- assert hasattr(result[0], "group")
42
- assert hasattr(result[0], "collections")
43
-
44
-
45
- @pytest.mark.asyncio
46
- async def test_async_get_by_group(async_collections_module):
47
- groups = await async_collections_module.list()
48
- group_id = groups[0].group
49
- collections = await async_collections_module.get_by_group(group_id)
50
- assert isinstance(collections, list)
51
- assert len(collections) > 0
52
- assert hasattr(collections[0], "name")
53
-
54
-
55
- @pytest.mark.asyncio
56
- async def test_async_details(async_collections_module):
57
- groups = await async_collections_module.list()
58
- group_id = groups[0].group
59
- collection = groups[0].collections[0]
60
- details = await async_collections_module.details(
61
- collection_id=collection.name, group_id=group_id
62
- )
63
- assert hasattr(details, "name")
64
- assert hasattr(details, "group")
65
- assert details.name == collection.name
66
- assert details.group == group_id
67
- assert isinstance(details.points, list)
68
-
69
-
70
- @pytest.mark.asyncio
71
- async def test_async_get_by_group_not_found(async_collections_module):
72
- with pytest.raises(ValueError):
73
- await async_collections_module.get_by_group("THIS_GROUP_DOES_NOT_EXIST")
74
-
75
-
76
- ## ---------------------------------------------------------
77
- ## Tests for synchronous collections module
78
- ## ---------------------------------------------------------
79
- def test_sync_list_returns_groups(sync_collections_module):
80
- result = sync_collections_module.list()
81
- assert isinstance(result, list)
82
- assert len(result) > 0, "Aucune collection trouvée sur l'API réelle."
83
- assert hasattr(result[0], "group")
84
- assert hasattr(result[0], "collections")
85
-
86
-
87
- def test_sync_get_by_group(sync_collections_module):
88
- # On prend le premier groupe connu
89
- groups = sync_collections_module.list()
90
- group_id = groups[0].group
91
- collections = sync_collections_module.get_by_group(group_id)
92
- assert isinstance(collections, list)
93
- assert len(collections) > 0
94
- assert hasattr(collections[0], "name")
95
-
96
-
97
- def test_sync_details(sync_collections_module):
98
- # On prend le premier groupe et sa première collection
99
- groups = sync_collections_module.list()
100
- group_id = groups[0].group
101
- collection = groups[0].collections[0]
102
- details = sync_collections_module.details(
103
- collection_id=collection.name, group_id=group_id
104
- )
105
- assert hasattr(details, "name")
106
- assert hasattr(details, "group")
107
- assert details.name == collection.name
108
- assert details.group == group_id
109
- assert isinstance(details.points, list)
110
-
111
-
112
- def test_sync_get_by_group_not_found(sync_collections_module):
113
- # On teste un groupe inexistant
114
- with pytest.raises(ValueError):
115
- sync_collections_module.get_by_group("THIS_GROUP_DOES_NOT_EXIST")
@@ -1,104 +0,0 @@
1
- import pytest
2
- from unittest.mock import patch, MagicMock
3
-
4
- from aisberg.models.collections import (
5
- GroupCollections,
6
- Collection,
7
- CollectionDetails,
8
- )
9
- from aisberg.modules import SyncCollectionsModule
10
-
11
-
12
- # Données factices pour les tests
13
- @pytest.fixture
14
- def mock_collections_data():
15
- return [
16
- GroupCollections(
17
- group="group1",
18
- collections=[
19
- Collection(name="col1"),
20
- Collection(name="col2"),
21
- ],
22
- ),
23
- GroupCollections(
24
- group="group2",
25
- collections=[
26
- Collection(name="col3"),
27
- ],
28
- ),
29
- ]
30
-
31
-
32
- @pytest.fixture
33
- def mock_points_data():
34
- return [
35
- {
36
- "id": "pt1",
37
- "payload": {
38
- "method": "m1",
39
- "norm": "normA",
40
- "filetype": "txt",
41
- "filename": "test.txt",
42
- "dense_encoder": "encoderA",
43
- "Category": "cat1",
44
- "text": "Ceci est un texte",
45
- "timestamp": "2024-06-21T10:00:00",
46
- "collection_name": "col1",
47
- "sparse_encoder": "spA",
48
- },
49
- }
50
- ]
51
-
52
-
53
- @pytest.fixture
54
- def module():
55
- # Un parent factice, client factice
56
- parent = MagicMock()
57
- client = MagicMock()
58
- return SyncCollectionsModule(parent, client)
59
-
60
-
61
- def test_list_collections(module, mock_collections_data):
62
- with patch("aisberg.api.endpoints.collections", return_value=mock_collections_data):
63
- result = module.list()
64
- assert isinstance(result, list)
65
- assert len(result) == 2
66
- assert result[0].group == "group1"
67
- assert result[1].collections[0].name == "col3"
68
-
69
-
70
- def test_list_collections_empty(module):
71
- with patch("aisberg.api.endpoints.collections", return_value=[]):
72
- result = module.list()
73
- assert result == []
74
-
75
-
76
- def test_get_by_group_success(module, mock_collections_data):
77
- with patch("aisberg.api.endpoints.collections", return_value=mock_collections_data):
78
- collections = module.get_by_group("group1")
79
- assert isinstance(collections, list)
80
- assert len(collections) == 2
81
- assert collections[0].name == "col1"
82
-
83
-
84
- def test_get_by_group_not_found(module, mock_collections_data):
85
- with patch("aisberg.api.endpoints.collections", return_value=mock_collections_data):
86
- with pytest.raises(ValueError, match="No collections found for group ID"):
87
- module.get_by_group("groupX")
88
-
89
-
90
- def test_details_success(module, mock_points_data):
91
- with patch("aisberg.api.endpoints.collection", return_value=mock_points_data):
92
- details = module.details("col1", "group1")
93
- assert isinstance(details, CollectionDetails)
94
- assert details.name == "col1"
95
- assert details.group == "group1"
96
- assert len(details.points) == 1
97
- assert details.points[0].id == "pt1"
98
- assert details.points[0].payload.text == "Ceci est un texte"
99
-
100
-
101
- def test_details_not_found(module):
102
- with patch("aisberg.api.endpoints.collection", return_value=None):
103
- with pytest.raises(ValueError, match="No collection found"):
104
- module.details("col2", "group1")
tmp/test.py DELETED
@@ -1,33 +0,0 @@
1
- from aisberg import AisbergClient, AisbergAsyncClient
2
- import asyncio
3
-
4
-
5
- client = AisbergClient()
6
-
7
-
8
- # r = client.workflows.run("3de964bb-c98c-4c3a-9b27-8a2c6c8edc57", {})
9
- # print(r)
10
-
11
-
12
- async def main():
13
- async_client = AisbergAsyncClient()
14
- # r = await async_client.workflows.run(
15
- # "943925fc-6561-4a01-8450-ada3ad7793f0",
16
- # {
17
- # "input": "Code la suite de Fibonacci en Python",
18
- # },
19
- # )
20
- # print(r.response)
21
- models = await async_client.models.list()
22
- print(models)
23
-
24
- res = await async_client.chat.complete(
25
- "salut ",
26
- model="Qwen/Qwen3-30B-A3B",
27
- temperature=0.1,
28
- )
29
- print(res.choices[0].message.content)
30
-
31
-
32
- if __name__ == "__main__":
33
- asyncio.run(main())
tmp/test_async.py DELETED
@@ -1,126 +0,0 @@
1
- from aisberg import AisbergAsyncClient
2
- from aisberg.models.chat import SystemMessage, HumanMessage, AIMessage
3
- from aisberg.models.tools import make_tool
4
-
5
- aisberg = AisbergAsyncClient()
6
-
7
-
8
- def rag_example():
9
- # Example of using the AisbergClient to perform a RAG operation
10
- collections = aisberg.collections.get_by_group("free-pro")
11
- for collection in collections:
12
- print(f"Collection: {collection.name}")
13
- chosen_collection = str(input("Enter the collection name to use: "))
14
- query = str(input("Enter your query: "))
15
-
16
- print("\n\nRetrieving documents...\n")
17
- docs = aisberg.embeddings.retrieve(
18
- query=query,
19
- collections_names=[chosen_collection],
20
- limit=5,
21
- )
22
-
23
- print("\nReranking documents...\n")
24
- reranked_docs = aisberg.embeddings.rerank(
25
- query=query,
26
- documents=docs,
27
- model="BAAI/bge-reranker-v2-m3",
28
- threshold=0.75, # Keep only 75% accurate documents
29
- )
30
-
31
- print("\nGenerating response...\n")
32
- response = aisberg.chat.complete(
33
- input=f"Answer the following question using the provided documents: {query}\n\nDocuments:\n{reranked_docs}\n\nAnswer:",
34
- model="Llama4-Scout-Q4",
35
- temperature=0.1,
36
- )
37
-
38
- print(response.choices[0].message.content)
39
-
40
-
41
- def chat_example():
42
- # Example of using the AisbergClient to perform a chat operation
43
- print("\n\nChat with the AI assistant. Type 'exit' to quit.\n")
44
-
45
- history: list = [
46
- SystemMessage(
47
- content="You are a helpful assistant. You can answer questions and provide information on various topics."
48
- )
49
- ]
50
-
51
- while True:
52
- query = str(input("You : "))
53
-
54
- if query.lower() == "exit":
55
- print("Exiting chat. Goodbye!")
56
- break
57
-
58
- history.append(HumanMessage(content=query))
59
-
60
- response = aisberg.chat.complete(
61
- input=history,
62
- model="Llama4-Scout-Q4",
63
- temperature=0.1,
64
- )
65
- print(f"Assistant: {response.choices[0].message.content}")
66
- history.append(AIMessage(content=response.choices[0].message.content))
67
- print("\n")
68
-
69
-
70
- def tool_call():
71
- def get_weather(location: str) -> str:
72
- # Simulate a tool call to get weather information
73
- return (
74
- f"Tool Response : The weather in {location} is sunny with a high of 25°C."
75
- )
76
-
77
- def get_shipment_status(shipment_id: str) -> str:
78
- return f"Tool Response : The shipment status for {shipment_id} is in transit and expected to arrive on time."
79
-
80
- tools = [
81
- make_tool(
82
- name="get_weather",
83
- description="Get the current weather in a given location",
84
- params={"location": "The location to get the weather for"},
85
- ),
86
- make_tool(
87
- name="get_shipment_status",
88
- description="Get the shipment status",
89
- params={"shipment_id": "The ID of the shipment to check status for"},
90
- ),
91
- ]
92
-
93
- aisberg.tools.register("get_weather", get_weather)
94
- aisberg.tools.register("get_shipment_status", get_shipment_status)
95
-
96
- print("Hello! I can help you with various tasks.")
97
- while True:
98
- user_input = str(input("> "))
99
- response = aisberg.chat.complete(
100
- input=[
101
- SystemMessage(
102
- content="You are a helpful assistant. To answer questions accurately, you may call external tools when needed. Use `get_weather` to retrieve the current weather for a specific location and `get_shipment_status` to check the status of a shipment by its ID."
103
- ),
104
- HumanMessage(content=user_input),
105
- ],
106
- model="Llama4-Scout-Q4",
107
- temperature=0.5,
108
- tools=tools,
109
- auto_execute_tools=True,
110
- )
111
- print(f"Assistant: {response.choices[0].message.content}")
112
-
113
-
114
- def encode(text: str):
115
- embeddings = aisberg.embeddings.encode(
116
- input=text,
117
- model="BAAI/bge-m3",
118
- )
119
- print(f"Encoded text: {embeddings}")
120
-
121
-
122
- if __name__ == "__main__":
123
- rag_example()
124
- # chat_example()
125
- # tool_call()
126
- # encode("This is a test sentence for encoding.")
tmp/test_collection.py DELETED
@@ -1,65 +0,0 @@
1
- from aisberg import AisbergClient, AisbergAsyncClient
2
- import json
3
-
4
-
5
- def test_coll():
6
- client = AisbergClient()
7
- # client.collections.delete('test_aisberg_sdk')
8
- #
9
- # colls = client.collections.create('test_aisberg_sdk', {
10
- # "chunks": [
11
- # "This is a test chunk 1",
12
- # "This is a test chunk 2",
13
- # "This is a test chunk 3"
14
- # ],
15
- # "metadata": [
16
- # {"source": "test1.txt", "author": "Author 1"},
17
- # {"source": "test2.txt", "author": "Author 2"},
18
- # {"source": "test3.txt", "author": "Author 3"}
19
- # ]
20
- # })
21
-
22
-
23
- points = client.collections.insert_points('test_aisberg_sdk', {
24
- "chunks": [
25
- "LKFJELZFKJZLEsdfsdfKFJZLKEJF chunk 1",
26
- "LKFJELZFKJZsdfsdfLEKFJZLKEJF chunk 2",
27
- "LKFJELZFsdfsdfsdfKJZLEKFJZLsdfsdfKEJF chunk 3"
28
- ],
29
- "metadata": [
30
- {"source": "test1.txt", "author": "Author 1"},
31
- {"source": "test2.txt", "author": "Author 2"},
32
- {"source": "test3.txt", "author": "Author 3"}
33
- ]
34
- }).points
35
-
36
- print(f"### Collection Created: {points}\n")
37
-
38
- points_to_delete = []
39
- for i in range(2):
40
- points_to_delete.append(points[i].id)
41
- print(f"### Points to delete: {points_to_delete}\n")
42
- a = client.collections.delete_points('test_aisberg_sdk', points_to_delete)
43
- print(f"### Points Deleted: {a}\n")
44
-
45
- c = client.collections.clear('test_aisberg_sdk')
46
- print(f"### Collection Cleared: {c}\n")
47
-
48
-
49
-
50
-
51
- async def async_test_coll():
52
- client = AisbergAsyncClient()
53
- await client.collections.delete('test_aisberg_sdk')
54
-
55
- colls = await client.collections.create('test_aisberg_sdk', './tmp/test.json')
56
-
57
- print(f"### Collection Created: {colls}\n")
58
-
59
-
60
- if __name__ == "__main__":
61
- test_coll()
62
- #
63
- # import asyncio
64
- #
65
- # asyncio.run(async_test_coll())
tmp/test_doc_parse.py DELETED
@@ -1,36 +0,0 @@
1
- from aisberg import AisbergClient, AisbergAsyncClient
2
- import json
3
-
4
-
5
- def test_doc():
6
- client = AisbergClient()
7
- print(client.models.list())
8
- stt = str(input("STT model to use (default: tts-1.5): ") or "tts-1.5")
9
- docs = client.documents.parse(
10
- ["./tmp/test.mp3", "./tmp/test.png"],
11
- stt_model=stt,
12
- vlm_model="pixtral-12b-2409",
13
- input="Que vois tu en haut à droite de l'image ?"
14
- )
15
-
16
- print(f"### MP3 Content: {docs[0].content.data}\n")
17
- # print(f"### PDF Content: {docs[1].content.data}\n")
18
- # print(f"### JSON Content: {json.dumps(docs[2].content.data, indent=2)}\n")
19
-
20
-
21
- async def async_test_doc():
22
- client = AisbergAsyncClient()
23
- docs = await client.documents.parse(["./tmp/test.mp3", "./tmp/test.pdf", "./tmp/test.json"])
24
-
25
- img = await client.documents.parse("./tmp/test.png", input="Que vois tu en haut à droite de l'image ?")
26
-
27
- print(f"### MP3 Content: {docs[0].content.data}\n")
28
- print(f"### PDF Content: {docs[1].content.data}\n")
29
- print(f"### JSON Content: {json.dumps(docs[2].content.data, indent=2)}\n")
30
-
31
-
32
- if __name__ == "__main__":
33
- test_doc()
34
-
35
- # import asyncio
36
- # asyncio.run(async_test_doc())
tmp/test_sync.py DELETED
@@ -1,146 +0,0 @@
1
- from aisberg import AisbergClient
2
- from aisberg.models.chat import SystemMessage, HumanMessage, AIMessage
3
- from aisberg.models.tools import make_tool
4
-
5
- aisberg = AisbergClient()
6
-
7
-
8
- def rag_example():
9
- # Example of using the AisbergClient to perform a RAG operation
10
- collections = aisberg.collections.get_by_group("free-pro")
11
- for collection in collections:
12
- print(f"Collection: {collection.name}")
13
- chosen_collection = str(input("Enter the collection name to use: "))
14
- query = str(input("Enter your query: "))
15
-
16
- print("\n\nRetrieving documents...\n")
17
- docs = aisberg.embeddings.retrieve(
18
- query=query,
19
- collections_names=[chosen_collection],
20
- limit=5,
21
- )
22
-
23
- print("\nReranking documents...\n")
24
- reranked_docs = aisberg.embeddings.rerank(
25
- query=query,
26
- documents=docs,
27
- model="BAAI/bge-reranker-v2-m3",
28
- threshold=0.75, # Keep only 75% accurate documents
29
- )
30
-
31
- print("\nGenerating response...\n")
32
- response = aisberg.chat.complete(
33
- input=f"Answer the following question using the provided documents: {query}\n\nDocuments:\n{reranked_docs}\n\nAnswer:",
34
- model="Llama4-Scout-Q4",
35
- temperature=0.1,
36
- )
37
-
38
- print(response.choices[0].message.content)
39
-
40
-
41
- def chat_example():
42
- # Example of using the AisbergClient to perform a chat operation
43
- print("\n\nChat with the AI assistant. Type 'exit' to quit.\n")
44
-
45
- history: list = [
46
- SystemMessage(
47
- content="You are a helpful assistant. You can answer questions and provide information on various topics."
48
- )
49
- ]
50
-
51
- while True:
52
- query = str(input("You : "))
53
-
54
- if query.lower() == "exit":
55
- print("Exiting chat. Goodbye!")
56
- break
57
-
58
- history.append(HumanMessage(content=query))
59
-
60
- response = aisberg.chat.complete(
61
- input=history,
62
- model="Llama4-Scout-Q4",
63
- temperature=0.1,
64
- )
65
- print(f"Assistant: {response.choices[0].message.content}")
66
- history.append(AIMessage(content=response.choices[0].message.content))
67
- print("\n")
68
-
69
-
70
- def tool_call():
71
- def get_weather(location: str) -> str:
72
- # Simulate a tool call to get weather information
73
- return (
74
- f"Tool Response : The weather in {location} is sunny with a high of 25°C."
75
- )
76
-
77
- def get_shipment_status(shipment_id: str) -> str:
78
- return f"Tool Response : The shipment status for {shipment_id} is in transit and expected to arrive on time."
79
-
80
- tools = [
81
- make_tool(
82
- name="get_weather",
83
- description="Get the current weather in a given location",
84
- params={"location": "The location to get the weather for"},
85
- ),
86
- make_tool(
87
- name="get_shipment_status",
88
- description="Get the shipment status",
89
- params={"shipment_id": "The ID of the shipment to check status for"},
90
- ),
91
- ]
92
-
93
- aisberg.tools.register("get_weather", get_weather)
94
- aisberg.tools.register("get_shipment_status", get_shipment_status)
95
-
96
- print("Hello! I can help you with various tasks.")
97
- while True:
98
- user_input = str(input("> "))
99
- response = aisberg.chat.complete(
100
- input=[
101
- SystemMessage(
102
- content="You are a helpful assistant. To answer questions accurately, you may call external tools when needed. Use `get_weather` to retrieve the current weather for a specific location and `get_shipment_status` to check the status of a shipment by its ID."
103
- ),
104
- HumanMessage(content=user_input),
105
- ],
106
- model="Llama4-Scout-Q4",
107
- temperature=0.5,
108
- tools=tools,
109
- auto_execute_tools=True,
110
- )
111
- print(f"Assistant: {response.choices[0].message.content}")
112
-
113
-
114
- def encode(text: str):
115
- embeddings = aisberg.embeddings.encode(
116
- input=text,
117
- model="BAAI/bge-m3",
118
- )
119
- print(f"Encoded text: {embeddings}")
120
-
121
-
122
- if __name__ == "__main__":
123
- import sys
124
-
125
- argv = sys.argv[1:]
126
- if len(argv) > 0:
127
- match argv[0]:
128
- case "rag":
129
- rag_example()
130
- case "chat":
131
- chat_example()
132
- case "tool":
133
- tool_call()
134
- case "encode":
135
- encode("This is a test sentence for encoding.")
136
- case _:
137
- print("Usage: python test_sync.py [rag|chat|tool|encode]")
138
-
139
- else:
140
- print("Usage: python test_sync.py [rag|chat|tool|encode]")
141
- print("Available commands:")
142
- print(" rag - Run a RAG example")
143
- print(" chat - Start a chat session with the AI assistant")
144
- print(" tool - Demonstrate tool calling in chat")
145
- print(" encode - Encode a sample text using embeddings")
146
- print("Run with 'python test_sync.py [command]' to execute a specific example.")