langroid 0.1.59__tar.gz → 0.1.60__tar.gz
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.
- {langroid-0.1.59 → langroid-0.1.60}/PKG-INFO +1 -1
- {langroid-0.1.59 → langroid-0.1.60}/langroid/agent/chat_agent.py +3 -1
- {langroid-0.1.59 → langroid-0.1.60}/langroid/language_models/base.py +121 -0
- langroid-0.1.60/langroid/language_models/config.py +13 -0
- {langroid-0.1.59 → langroid-0.1.60}/langroid/language_models/openai_gpt.py +31 -23
- langroid-0.1.60/langroid/language_models/prompt_formatter/base.py +42 -0
- langroid-0.1.60/langroid/language_models/prompt_formatter/llama2_formatter.py +75 -0
- langroid-0.1.60/langroid/vector_store/__init__.py +0 -0
- {langroid-0.1.59 → langroid-0.1.60}/pyproject.toml +1 -1
- {langroid-0.1.59 → langroid-0.1.60}/setup.py +2 -1
- {langroid-0.1.59 → langroid-0.1.60}/LICENSE +0 -0
- {langroid-0.1.59 → langroid-0.1.60}/README.md +0 -0
- {langroid-0.1.59 → langroid-0.1.60}/langroid/__init__.py +0 -0
- {langroid-0.1.59 → langroid-0.1.60}/langroid/agent/__init__.py +0 -0
- {langroid-0.1.59 → langroid-0.1.60}/langroid/agent/base.py +0 -0
- {langroid-0.1.59 → langroid-0.1.60}/langroid/agent/chat_document.py +0 -0
- {langroid-0.1.59 → langroid-0.1.60}/langroid/agent/helpers.py +0 -0
- {langroid-0.1.59 → langroid-0.1.60}/langroid/agent/junk +0 -0
- {langroid-0.1.59 → langroid-0.1.60}/langroid/agent/special/__init__.py +0 -0
- {langroid-0.1.59 → langroid-0.1.60}/langroid/agent/special/doc_chat_agent.py +0 -0
- {langroid-0.1.59 → langroid-0.1.60}/langroid/agent/special/recipient_validator_agent.py +0 -0
- {langroid-0.1.59 → langroid-0.1.60}/langroid/agent/special/retriever_agent.py +0 -0
- {langroid-0.1.59 → langroid-0.1.60}/langroid/agent/special/sql/__init__.py +0 -0
- {langroid-0.1.59 → langroid-0.1.60}/langroid/agent/special/sql/sql_chat_agent.py +0 -0
- {langroid-0.1.59 → langroid-0.1.60}/langroid/agent/special/sql/utils/__init__.py +0 -0
- {langroid-0.1.59 → langroid-0.1.60}/langroid/agent/special/sql/utils/description_extractors.py +0 -0
- {langroid-0.1.59 → langroid-0.1.60}/langroid/agent/special/sql/utils/populate_metadata.py +0 -0
- {langroid-0.1.59 → langroid-0.1.60}/langroid/agent/special/sql/utils/system_message.py +0 -0
- {langroid-0.1.59 → langroid-0.1.60}/langroid/agent/special/sql/utils/tools.py +0 -0
- {langroid-0.1.59 → langroid-0.1.60}/langroid/agent/special/table_chat_agent.py +0 -0
- {langroid-0.1.59 → langroid-0.1.60}/langroid/agent/task.py +0 -0
- {langroid-0.1.59 → langroid-0.1.60}/langroid/agent/tool_message.py +0 -0
- {langroid-0.1.59 → langroid-0.1.60}/langroid/agent/tools/__init__.py +0 -0
- {langroid-0.1.59 → langroid-0.1.60}/langroid/agent/tools/google_search_tool.py +0 -0
- {langroid-0.1.59 → langroid-0.1.60}/langroid/agent/tools/recipient_tool.py +0 -0
- {langroid-0.1.59 → langroid-0.1.60}/langroid/agent_config.py +0 -0
- {langroid-0.1.59 → langroid-0.1.60}/langroid/cachedb/__init__.py +0 -0
- {langroid-0.1.59 → langroid-0.1.60}/langroid/cachedb/base.py +0 -0
- {langroid-0.1.59 → langroid-0.1.60}/langroid/cachedb/momento_cachedb.py +0 -0
- {langroid-0.1.59 → langroid-0.1.60}/langroid/cachedb/redis_cachedb.py +0 -0
- {langroid-0.1.59 → langroid-0.1.60}/langroid/embedding_models/__init__.py +0 -0
- {langroid-0.1.59 → langroid-0.1.60}/langroid/embedding_models/base.py +0 -0
- {langroid-0.1.59 → langroid-0.1.60}/langroid/embedding_models/clustering.py +0 -0
- {langroid-0.1.59 → langroid-0.1.60}/langroid/embedding_models/models.py +0 -0
- {langroid-0.1.59 → langroid-0.1.60}/langroid/language_models/__init__.py +0 -0
- {langroid-0.1.59 → langroid-0.1.60}/langroid/language_models/azure_openai.py +0 -0
- {langroid-0.1.59/langroid/parsing → langroid-0.1.60/langroid/language_models/prompt_formatter}/__init__.py +0 -0
- {langroid-0.1.59 → langroid-0.1.60}/langroid/language_models/utils.py +0 -0
- {langroid-0.1.59 → langroid-0.1.60}/langroid/mytypes.py +0 -0
- {langroid-0.1.59/langroid/prompts → langroid-0.1.60/langroid/parsing}/__init__.py +0 -0
- {langroid-0.1.59 → langroid-0.1.60}/langroid/parsing/agent_chats.py +0 -0
- {langroid-0.1.59 → langroid-0.1.60}/langroid/parsing/code-parsing.md +0 -0
- {langroid-0.1.59 → langroid-0.1.60}/langroid/parsing/code_parser.py +0 -0
- {langroid-0.1.59 → langroid-0.1.60}/langroid/parsing/json.py +0 -0
- {langroid-0.1.59 → langroid-0.1.60}/langroid/parsing/para_sentence_split.py +0 -0
- {langroid-0.1.59 → langroid-0.1.60}/langroid/parsing/parser.py +0 -0
- {langroid-0.1.59 → langroid-0.1.60}/langroid/parsing/pdf_parser.py +0 -0
- {langroid-0.1.59 → langroid-0.1.60}/langroid/parsing/repo_loader.py +0 -0
- {langroid-0.1.59 → langroid-0.1.60}/langroid/parsing/table_loader.py +0 -0
- {langroid-0.1.59 → langroid-0.1.60}/langroid/parsing/url_loader.py +0 -0
- {langroid-0.1.59 → langroid-0.1.60}/langroid/parsing/url_loader_cookies.py +0 -0
- {langroid-0.1.59 → langroid-0.1.60}/langroid/parsing/urls.py +0 -0
- {langroid-0.1.59 → langroid-0.1.60}/langroid/parsing/utils.py +0 -0
- {langroid-0.1.59 → langroid-0.1.60}/langroid/parsing/web_search.py +0 -0
- {langroid-0.1.59/langroid/scripts → langroid-0.1.60/langroid/prompts}/__init__.py +0 -0
- {langroid-0.1.59 → langroid-0.1.60}/langroid/prompts/dialog.py +0 -0
- {langroid-0.1.59 → langroid-0.1.60}/langroid/prompts/prompts_config.py +0 -0
- {langroid-0.1.59 → langroid-0.1.60}/langroid/prompts/templates.py +0 -0
- {langroid-0.1.59 → langroid-0.1.60}/langroid/prompts/transforms.py +0 -0
- {langroid-0.1.59/langroid/utils → langroid-0.1.60/langroid/scripts}/__init__.py +0 -0
- {langroid-0.1.59/langroid/utils/llms → langroid-0.1.60/langroid/utils}/__init__.py +0 -0
- {langroid-0.1.59 → langroid-0.1.60}/langroid/utils/configuration.py +0 -0
- {langroid-0.1.59 → langroid-0.1.60}/langroid/utils/constants.py +0 -0
- {langroid-0.1.59 → langroid-0.1.60}/langroid/utils/docker.py +0 -0
- {langroid-0.1.59 → langroid-0.1.60}/langroid/utils/globals.py +0 -0
- {langroid-0.1.59/langroid/utils/output → langroid-0.1.60/langroid/utils/llms}/__init__.py +0 -0
- {langroid-0.1.59 → langroid-0.1.60}/langroid/utils/llms/strings.py +0 -0
- {langroid-0.1.59 → langroid-0.1.60}/langroid/utils/logging.py +0 -0
- {langroid-0.1.59/langroid/utils/web → langroid-0.1.60/langroid/utils/output}/__init__.py +0 -0
- {langroid-0.1.59 → langroid-0.1.60}/langroid/utils/output/printing.py +0 -0
- {langroid-0.1.59 → langroid-0.1.60}/langroid/utils/pydantic_utils.py +0 -0
- {langroid-0.1.59 → langroid-0.1.60}/langroid/utils/system.py +0 -0
- {langroid-0.1.59/langroid/vector_store → langroid-0.1.60/langroid/utils/web}/__init__.py +0 -0
- {langroid-0.1.59 → langroid-0.1.60}/langroid/utils/web/login.py +0 -0
- {langroid-0.1.59 → langroid-0.1.60}/langroid/utils/web/selenium_login.py +0 -0
- {langroid-0.1.59 → langroid-0.1.60}/langroid/vector_store/base.py +0 -0
- {langroid-0.1.59 → langroid-0.1.60}/langroid/vector_store/chromadb.py +0 -0
- {langroid-0.1.59 → langroid-0.1.60}/langroid/vector_store/qdrant_cloud.py +0 -0
- {langroid-0.1.59 → langroid-0.1.60}/langroid/vector_store/qdrantdb.py +0 -0
@@ -393,11 +393,13 @@ class ChatAgent(Agent):
|
|
393
393
|
)
|
394
394
|
|
395
395
|
if output_len < self.config.llm.min_output_tokens:
|
396
|
-
|
396
|
+
logger.warning(
|
397
397
|
f"""
|
398
398
|
Tried to shorten prompt history for chat mode
|
399
399
|
but the feasible output length {output_len} is still
|
400
400
|
less than the minimum output length {self.config.llm.min_output_tokens}.
|
401
|
+
Your chat history is too long for this model,
|
402
|
+
and the response may be truncated.
|
401
403
|
"""
|
402
404
|
)
|
403
405
|
with StreamingIfAllowed(self.llm):
|
@@ -1,5 +1,6 @@
|
|
1
1
|
import asyncio
|
2
2
|
import json
|
3
|
+
import logging
|
3
4
|
from abc import ABC, abstractmethod
|
4
5
|
from enum import Enum
|
5
6
|
from typing import Any, Dict, List, Optional, Tuple, Type, Union
|
@@ -9,6 +10,7 @@ from pydantic import BaseModel, BaseSettings
|
|
9
10
|
|
10
11
|
from langroid.cachedb.momento_cachedb import MomentoCacheConfig
|
11
12
|
from langroid.cachedb.redis_cachedb import RedisCacheConfig
|
13
|
+
from langroid.language_models.config import Llama2FormatterConfig, PromptFormatterConfig
|
12
14
|
from langroid.mytypes import Document
|
13
15
|
from langroid.parsing.agent_chats import parse_message
|
14
16
|
from langroid.parsing.json import top_level_json_field
|
@@ -20,9 +22,60 @@ from langroid.prompts.templates import (
|
|
20
22
|
from langroid.utils.configuration import settings
|
21
23
|
from langroid.utils.output.printing import show_if_debug
|
22
24
|
|
25
|
+
logger = logging.getLogger(__name__)
|
26
|
+
|
27
|
+
|
28
|
+
class LocalModelConfig(BaseModel):
|
29
|
+
"""
|
30
|
+
Configuration for local model available via
|
31
|
+
an OpenAI-compatible API.
|
32
|
+
|
33
|
+
Support local LLM endpoint that spoofs the OpenAI API.
|
34
|
+
Examples of libraries that enable this are:
|
35
|
+
- llama-cpp-python (LCP)
|
36
|
+
- text-generation-webui (TGW) (from oobabooga or "ooba" for short)
|
37
|
+
Typically these allow spinning up a server that listens on
|
38
|
+
http://localhost:8000/v1
|
39
|
+
and we can continue using our OpenAI-API-based python code, except we
|
40
|
+
set openai.api_base to this URL.
|
41
|
+
|
42
|
+
These endpoints usually support both /completions and /chat/completions requests.
|
43
|
+
Supporting /chat/completions is more complex because each family of local model
|
44
|
+
has its own (finicky) formatting for turns and roles in a chat.
|
45
|
+
The TGW lib has an extensive set of templates for various model families,
|
46
|
+
and the template is auto-detected from the model, at least for common models,
|
47
|
+
so we can directly use the /chat/completions endpoint, and it works well (at
|
48
|
+
least on llama2 models). However, when in doubt,
|
49
|
+
we can always do our own formatting of the chat history and use the /completions
|
50
|
+
endpoint instead. This is what we do for LCP models. In this case,
|
51
|
+
we need to set `use_completion_for_chat` to True.
|
52
|
+
With a model served via TGW, for chats we can set this to either True or False
|
53
|
+
(in which case we rely on the TGW templates correctly formatting the chat history).
|
54
|
+
|
55
|
+
Both of the above libs assume a single model is available at the endpoint.
|
56
|
+
As far as I know, they do not support run-time switching of models.
|
57
|
+
There is another library that we can potentially integrate, `localAI`,
|
58
|
+
which does have model switching, and can be very useful, e.g.
|
59
|
+
when we want different agents to use different models.
|
60
|
+
|
61
|
+
All of the above considerations are outside of this interface, however.
|
62
|
+
All we care about here is the endpoint url.
|
63
|
+
"""
|
64
|
+
|
65
|
+
# OPENAI_LOCAL.* env vars can be used to set these in .env file or environment
|
66
|
+
|
67
|
+
api_base: str = "http://localhost:8000/v1"
|
68
|
+
model: str = "local" # usually not needed
|
69
|
+
model_type: str = "llama2"
|
70
|
+
formatter: None | PromptFormatterConfig = Llama2FormatterConfig()
|
71
|
+
context_length: int = 2048 # default for llama-cpp-python
|
72
|
+
use_chat_for_completion: bool = False
|
73
|
+
use_completion_for_chat: bool = True
|
74
|
+
|
23
75
|
|
24
76
|
class LLMConfig(BaseSettings):
|
25
77
|
type: str = "openai"
|
78
|
+
local: None | LocalModelConfig = None
|
26
79
|
timeout: int = 20 # timeout for API requests
|
27
80
|
chat_model: Optional[str] = None
|
28
81
|
completion_model: Optional[str] = None
|
@@ -32,6 +85,7 @@ class LLMConfig(BaseSettings):
|
|
32
85
|
# if input length + max_output_tokens > context length of model,
|
33
86
|
# we will try shortening requested output
|
34
87
|
min_output_tokens: int = 64
|
88
|
+
use_completion_for_chat: bool = False # use completion model for chat?
|
35
89
|
use_chat_for_completion: bool = True # use chat model for completion?
|
36
90
|
stream: bool = False # stream output from API?
|
37
91
|
cache_config: None | RedisCacheConfig | MomentoCacheConfig = None
|
@@ -223,6 +277,73 @@ class LanguageModel(ABC):
|
|
223
277
|
).get(config.type, openai)
|
224
278
|
return cls(config) # type: ignore
|
225
279
|
|
280
|
+
@staticmethod
|
281
|
+
def user_assistant_pairs(lst: List[str]) -> List[Tuple[str, str]]:
|
282
|
+
"""
|
283
|
+
Given an even-length sequence of strings, split into a sequence of pairs
|
284
|
+
|
285
|
+
Args:
|
286
|
+
lst (List[str]): sequence of strings
|
287
|
+
|
288
|
+
Returns:
|
289
|
+
List[Tuple[str,str]]: sequence of pairs of strings
|
290
|
+
"""
|
291
|
+
evens = lst[::2]
|
292
|
+
odds = lst[1::2]
|
293
|
+
return list(zip(evens, odds))
|
294
|
+
|
295
|
+
@staticmethod
|
296
|
+
def get_chat_history_components(
|
297
|
+
messages: List[LLMMessage],
|
298
|
+
) -> Tuple[str, List[Tuple[str, str]], str]:
|
299
|
+
"""
|
300
|
+
From the chat history, extract system prompt, user-assistant turns, and
|
301
|
+
final user msg.
|
302
|
+
|
303
|
+
Args:
|
304
|
+
messages (List[LLMMessage]): List of messages in the chat history
|
305
|
+
|
306
|
+
Returns:
|
307
|
+
Tuple[str, List[Tuple[str,str]], str]:
|
308
|
+
system prompt, user-assistant turns, final user msg
|
309
|
+
|
310
|
+
"""
|
311
|
+
# Handle various degenerate cases
|
312
|
+
messages = [m for m in messages] # copy
|
313
|
+
DUMMY_SYS_PROMPT = "You are a helpful assistant."
|
314
|
+
DUMMY_USER_PROMPT = "Follow the instructions above."
|
315
|
+
if len(messages) == 0 or messages[0].role != Role.SYSTEM:
|
316
|
+
logger.warning("No system msg, creating dummy system prompt")
|
317
|
+
messages.insert(0, LLMMessage(content=DUMMY_SYS_PROMPT, role=Role.SYSTEM))
|
318
|
+
system_prompt = messages[0].content
|
319
|
+
|
320
|
+
# now we have messages = [Sys,...]
|
321
|
+
if len(messages) == 1:
|
322
|
+
logger.warning(
|
323
|
+
"Got only system message in chat history, creating dummy user prompt"
|
324
|
+
)
|
325
|
+
messages.append(LLMMessage(content=DUMMY_USER_PROMPT, role=Role.USER))
|
326
|
+
|
327
|
+
# now we have messages = [Sys, msg, ...]
|
328
|
+
|
329
|
+
if messages[1].role != Role.USER:
|
330
|
+
messages.insert(1, LLMMessage(content=DUMMY_USER_PROMPT, role=Role.USER))
|
331
|
+
|
332
|
+
# now we have messages = [Sys, user, ...]
|
333
|
+
if messages[-1].role != Role.USER:
|
334
|
+
logger.warning(
|
335
|
+
"Last message in chat history is not a user message,"
|
336
|
+
" creating dummy user prompt"
|
337
|
+
)
|
338
|
+
messages.append(LLMMessage(content=DUMMY_USER_PROMPT, role=Role.USER))
|
339
|
+
|
340
|
+
# now we have messages = [Sys, user, ..., user]
|
341
|
+
# so we omit the first and last elements and make pairs of user-asst messages
|
342
|
+
conversation = [m.content for m in messages[1:-1]]
|
343
|
+
user_prompt = messages[-1].content
|
344
|
+
pairs = LanguageModel.user_assistant_pairs(conversation)
|
345
|
+
return system_prompt, pairs, user_prompt
|
346
|
+
|
226
347
|
@abstractmethod
|
227
348
|
def set_stream(self, stream: bool) -> bool:
|
228
349
|
"""Enable or disable streaming output from API.
|
@@ -0,0 +1,13 @@
|
|
1
|
+
from pydantic import BaseSettings
|
2
|
+
|
3
|
+
|
4
|
+
class PromptFormatterConfig(BaseSettings):
|
5
|
+
type: str = "llama2"
|
6
|
+
|
7
|
+
class Config:
|
8
|
+
env_prefix = "FORMAT_"
|
9
|
+
case_sensitive = False
|
10
|
+
|
11
|
+
|
12
|
+
class Llama2FormatterConfig(PromptFormatterConfig):
|
13
|
+
use_bos_eos: bool = False
|
@@ -22,6 +22,9 @@ from langroid.language_models.base import (
|
|
22
22
|
LLMTokenUsage,
|
23
23
|
Role,
|
24
24
|
)
|
25
|
+
from langroid.language_models.prompt_formatter.base import (
|
26
|
+
PromptFormatter,
|
27
|
+
)
|
25
28
|
from langroid.language_models.utils import (
|
26
29
|
async_retry_with_exponential_backoff,
|
27
30
|
retry_with_exponential_backoff,
|
@@ -50,45 +53,26 @@ class OpenAICompletionModel(str, Enum):
|
|
50
53
|
LOCAL = "local" # dummy for any local model
|
51
54
|
|
52
55
|
|
53
|
-
class LocalModelConfig(BaseModel):
|
54
|
-
"""
|
55
|
-
Configuration for local model available via
|
56
|
-
an OpenAI-compatible API.
|
57
|
-
"""
|
58
|
-
|
59
|
-
# OPENAI_LOCAL.API_BASE env var can be used to set this
|
60
|
-
api_base: str = "http://localhost:8000/v1"
|
61
|
-
# OPENAI_LOCAL.CONTEXT_LENGTH env var can be used to set this
|
62
|
-
context_length: int = 2048 # default for llama-cpp-python
|
63
|
-
|
64
|
-
|
65
56
|
class OpenAIGPTConfig(LLMConfig):
|
66
57
|
type: str = "openai"
|
67
|
-
# This allows local configs to be set via OPENAI_LOCAL.* env vars
|
68
|
-
local: LocalModelConfig = LocalModelConfig()
|
69
58
|
api_base: str | None = None # used for local or other non-OpenAI models
|
70
59
|
max_output_tokens: int = 1024
|
71
60
|
min_output_tokens: int = 64
|
72
61
|
timeout: int = 20
|
73
62
|
temperature: float = 0.2
|
74
|
-
chat_model: OpenAIChatModel = OpenAIChatModel.GPT4
|
75
|
-
completion_model: OpenAICompletionModel = OpenAICompletionModel.GPT4
|
63
|
+
chat_model: str | OpenAIChatModel = OpenAIChatModel.GPT4
|
64
|
+
completion_model: str | OpenAICompletionModel = OpenAICompletionModel.GPT4
|
76
65
|
context_length: Dict[str, int] = {
|
77
66
|
OpenAIChatModel.GPT3_5_TURBO: 4096,
|
78
67
|
OpenAIChatModel.GPT4: 8192,
|
79
68
|
OpenAIChatModel.GPT4_NOFUNC: 8192,
|
80
69
|
OpenAICompletionModel.TEXT_DA_VINCI_003: 4096,
|
81
|
-
# 2048 is default in llama-cpp-python, but can be set
|
82
|
-
# via cmd line, e.g.
|
83
|
-
# python3 -m llama-cpp.server --n_ctx 4096
|
84
|
-
OpenAICompletionModel.LOCAL: 2048,
|
85
70
|
}
|
86
71
|
cost_per_1k_tokens: Dict[str, Tuple[float, float]] = {
|
87
72
|
# (input/prompt cost, output/completion cost)
|
88
73
|
OpenAIChatModel.GPT3_5_TURBO: (0.0015, 0.002),
|
89
74
|
OpenAIChatModel.GPT4: (0.03, 0.06), # 8K context
|
90
75
|
OpenAIChatModel.GPT4_NOFUNC: (0.03, 0.06),
|
91
|
-
OpenAIChatModel.LOCAL: (0.0, 0.0),
|
92
76
|
}
|
93
77
|
|
94
78
|
# all of the non-dict vars above can be set via env vars,
|
@@ -122,10 +106,16 @@ class OpenAIGPT(LanguageModel):
|
|
122
106
|
if settings.nofunc:
|
123
107
|
self.chat_model = OpenAIChatModel.GPT4_NOFUNC
|
124
108
|
self.api_base: str | None = None
|
125
|
-
if config.
|
109
|
+
if config.local:
|
110
|
+
self.config.chat_model = config.local.model
|
111
|
+
self.config.use_completion_for_chat = config.local.use_completion_for_chat
|
112
|
+
self.config.use_chat_for_completion = config.local.use_chat_for_completion
|
126
113
|
self.api_key = "sx-xxx"
|
127
114
|
self.api_base = config.local.api_base
|
128
|
-
config.context_length = {
|
115
|
+
config.context_length = {config.local.model: config.local.context_length}
|
116
|
+
config.cost_per_1k_tokens = {
|
117
|
+
config.local.model: (0.0, 0.0),
|
118
|
+
}
|
129
119
|
else:
|
130
120
|
# TODO: get rid of this and add `api_key` to the OpenAIGPTConfig
|
131
121
|
# so we can get it from the OPENAI_API_KEY env var
|
@@ -433,6 +423,24 @@ class OpenAIGPT(LanguageModel):
|
|
433
423
|
functions: Optional[List[LLMFunctionSpec]] = None,
|
434
424
|
function_call: str | Dict[str, str] = "auto",
|
435
425
|
) -> LLMResponse:
|
426
|
+
if self.config.use_completion_for_chat:
|
427
|
+
# only makes sense for local models
|
428
|
+
if self.config.local is None or self.config.local.formatter is None:
|
429
|
+
raise ValueError(
|
430
|
+
"""
|
431
|
+
`formatter` must be specified in config to use completion for chat.
|
432
|
+
"""
|
433
|
+
)
|
434
|
+
formatter = PromptFormatter.create(self.config.local.formatter)
|
435
|
+
if isinstance(messages, str):
|
436
|
+
messages = [
|
437
|
+
LLMMessage(
|
438
|
+
role=Role.SYSTEM, content="You are a helpful assistant."
|
439
|
+
),
|
440
|
+
LLMMessage(role=Role.USER, content=messages),
|
441
|
+
]
|
442
|
+
prompt = formatter.format(messages)
|
443
|
+
return self.generate(prompt=prompt, max_tokens=max_tokens)
|
436
444
|
try:
|
437
445
|
return self._chat(messages, max_tokens, functions, function_call)
|
438
446
|
except Exception as e:
|
@@ -0,0 +1,42 @@
|
|
1
|
+
import logging
|
2
|
+
from abc import ABC, abstractmethod
|
3
|
+
from typing import List
|
4
|
+
|
5
|
+
from langroid.language_models.base import LLMMessage
|
6
|
+
from langroid.language_models.config import PromptFormatterConfig
|
7
|
+
|
8
|
+
logger = logging.getLogger(__name__)
|
9
|
+
|
10
|
+
|
11
|
+
class PromptFormatter(ABC):
|
12
|
+
"""
|
13
|
+
Abstract base class for a prompt formatter
|
14
|
+
"""
|
15
|
+
|
16
|
+
def __init__(self, config: PromptFormatterConfig):
|
17
|
+
self.config = config
|
18
|
+
|
19
|
+
@staticmethod
|
20
|
+
def create(config: PromptFormatterConfig) -> "PromptFormatter":
|
21
|
+
from langroid.language_models.prompt_formatter.llama2_formatter import (
|
22
|
+
Llama2Formatter,
|
23
|
+
)
|
24
|
+
|
25
|
+
formatter_class = dict(llama2=Llama2Formatter).get(config.type, Llama2Formatter)
|
26
|
+
return formatter_class(config)
|
27
|
+
|
28
|
+
@abstractmethod
|
29
|
+
def format(self, messages: List[LLMMessage]) -> str:
|
30
|
+
"""
|
31
|
+
Convert sequence of messages (system, user, assistant, user, assistant...user)
|
32
|
+
to a single prompt formatted according to the specific format type,
|
33
|
+
to be used in a /completions endpoint.
|
34
|
+
|
35
|
+
Args:
|
36
|
+
messages (List[LLMMessage]): chat history as a sequence of messages
|
37
|
+
|
38
|
+
Returns:
|
39
|
+
(str): formatted version of chat history
|
40
|
+
|
41
|
+
"""
|
42
|
+
pass
|
@@ -0,0 +1,75 @@
|
|
1
|
+
import logging
|
2
|
+
from typing import List, Tuple
|
3
|
+
|
4
|
+
from langroid.language_models.base import LanguageModel, LLMMessage
|
5
|
+
from langroid.language_models.config import Llama2FormatterConfig
|
6
|
+
from langroid.language_models.prompt_formatter.base import PromptFormatter
|
7
|
+
|
8
|
+
logger = logging.getLogger(__name__)
|
9
|
+
|
10
|
+
|
11
|
+
BOS: str = ""
|
12
|
+
EOS: str = ""
|
13
|
+
B_INST: str = "[INST]"
|
14
|
+
E_INST: str = "[/INST]"
|
15
|
+
B_SYS: str = "<<SYS>>\n"
|
16
|
+
E_SYS: str = "\n<</SYS>>\n\n"
|
17
|
+
SPECIAL_TAGS: List[str] = [B_INST, E_INST, BOS, EOS, "<<SYS>>", "<</SYS>>"]
|
18
|
+
|
19
|
+
|
20
|
+
class Llama2Formatter(PromptFormatter):
|
21
|
+
def __int__(self, config: Llama2FormatterConfig) -> None:
|
22
|
+
super().__init__(config)
|
23
|
+
self.config: Llama2FormatterConfig = config
|
24
|
+
|
25
|
+
def format(self, messages: List[LLMMessage]) -> str:
|
26
|
+
sys_msg, chat_msgs, user_msg = LanguageModel.get_chat_history_components(
|
27
|
+
messages
|
28
|
+
)
|
29
|
+
return self._get_prompt_from_components(sys_msg, chat_msgs, user_msg)
|
30
|
+
|
31
|
+
def _get_prompt_from_components(
|
32
|
+
self,
|
33
|
+
system_prompt: str,
|
34
|
+
chat_history: List[Tuple[str, str]],
|
35
|
+
user_message: str,
|
36
|
+
) -> str:
|
37
|
+
"""
|
38
|
+
For llama2 models, convert chat history into a single
|
39
|
+
prompt for Llama2 models, for use in the /completions endpoint
|
40
|
+
(as opposed to the /chat/completions endpoint).
|
41
|
+
See:
|
42
|
+
https://www.reddit.com/r/LocalLLaMA/comments/155po2p/get_llama_2_prompt_format_right/
|
43
|
+
https://github.com/facebookresearch/llama/blob/main/llama/generation.py#L44
|
44
|
+
|
45
|
+
Args:
|
46
|
+
system_prompt (str): system prompt, typically specifying role/task.
|
47
|
+
chat_history (List[Tuple[str,str]]): List of (user, assistant) pairs
|
48
|
+
user_message (str): user message, at the end of the chat, i.e. the message
|
49
|
+
for which we want to generate a response.
|
50
|
+
|
51
|
+
Returns:
|
52
|
+
str: Prompt for Llama2 models
|
53
|
+
|
54
|
+
Typical structure of the formatted prompt:
|
55
|
+
Note important that the first [INST], [/INST] surrounds the system prompt,
|
56
|
+
together with the first user message. A lot of libs seem to miss this detail.
|
57
|
+
|
58
|
+
<s>[INST] <<SYS>>
|
59
|
+
You are are a helpful... bla bla.. assistant
|
60
|
+
<</SYS>>
|
61
|
+
|
62
|
+
Hi there! [/INST] Hello! How can I help you today? </s><s>[INST]
|
63
|
+
What is a neutron star? [/INST] A neutron star is a ... </s><s>
|
64
|
+
[INST] Okay cool, thank you! [/INST] You're welcome! </s><s>
|
65
|
+
[INST] Ah, I have one more question.. [/INST]
|
66
|
+
"""
|
67
|
+
bos = BOS if self.config.use_bos_eos else ""
|
68
|
+
eos = EOS if self.config.use_bos_eos else ""
|
69
|
+
text = f"{bos}{B_INST} {B_SYS}{system_prompt}{E_SYS}"
|
70
|
+
for user_input, response in chat_history:
|
71
|
+
text += (
|
72
|
+
f"{user_input.strip()} {E_INST} {response.strip()} {eos}{bos} {B_INST} "
|
73
|
+
)
|
74
|
+
text += f"{user_message.strip()} {E_INST}"
|
75
|
+
return text
|
File without changes
|
@@ -11,6 +11,7 @@ packages = \
|
|
11
11
|
'langroid.cachedb',
|
12
12
|
'langroid.embedding_models',
|
13
13
|
'langroid.language_models',
|
14
|
+
'langroid.language_models.prompt_formatter',
|
14
15
|
'langroid.parsing',
|
15
16
|
'langroid.prompts',
|
16
17
|
'langroid.scripts',
|
@@ -79,7 +80,7 @@ extras_require = \
|
|
79
80
|
|
80
81
|
setup_kwargs = {
|
81
82
|
'name': 'langroid',
|
82
|
-
'version': '0.1.
|
83
|
+
'version': '0.1.60',
|
83
84
|
'description': 'Harness LLMs with Multi-Agent Programming',
|
84
85
|
'long_description': '<div align="center">\n <img src="docs/assets/langroid-card-lambda-ossem-rust-1200-630.png" alt="Logo" \n width="400" align="center">\n</div>\n\n<div align="center">\n\n[](https://pypi.org/project/langroid/)\n[](https://github.com/langroid/langroid/actions/workflows/pytest.yml)\n[](https://codecov.io/gh/langroid/langroid)\n[](https://github.com/langroid/langroid/actions/workflows/validate.yml)\n[](https://github.com/langroid/langroid/actions/workflows/mkdocs-deploy.yml)\n\n[](https://langroid.github.io/langroid)\n[](https://discord.gg/ZU36McDgDs)\n[](https://colab.research.google.com/github/langroid/langroid/blob/main/examples/langroid_quick_examples.ipynb)\n\n[](https://hub.docker.com/r/langroid/langroid)\n\n[](https://github.com/langroid/langroid/actions/workflows/docker-publish.yml)\n\n[](https://langroid.substack.com/p/langroid-harness-llms-with-multi-agent-programming)\n\n[](https://news.ycombinator.com/submitlink?u=https%3A%2F%2Fgithub.com%2Flangroid%2Flangroid&t=Harness%20LLMs%20with%20Multi-Agent%20Programming)\n[](https://www.reddit.com/submit?url=https%3A%2F%2Fgithub.com%2Flangroid%2Flangroid&title=Harness%20LLMs%20with%20Multi-Agent%20Programming)\n[](https://twitter.com/intent/tweet?text=Langroid%20is%20a%20powerful,%20elegant%20new%20framework%20to%20easily%20build%20%23LLM%20applications.%20You%20set%20up%20LLM-powered%20Agents%20with%20vector-stores,%20assign%20tasks,%20and%20have%20them%20collaboratively%20solve%20problems%20via%20message-transformations.%20https://github.com/langroid/langroid)\n[](https://www.linkedin.com/shareArticle?mini=true&url=https://github.com/langroid/langroid&title=Langroid:%20A%20Powerful,%20Elegant%20Framework&summary=Langroid%20is%20a%20powerful,%20elegant%20new%20framework%20to%20easily%20build%20%23LLM%20applications.%20You%20set%20up%20LLM-powered%20Agents%20with%20vector-stores,%20assign%20tasks,%20and%20have%20them%20collaboratively%20solve%20problems%20via%20message-transformations.)\n\n\n</div>\n\n<h3 align="center">\n <a target="_blank" \n href="https://langroid.github.io/langroid/" rel="dofollow">\n <strong>Documentation</strong></a>\n ·\n <a target="_blank" href="https://github.com/langroid/langroid-examples" rel="dofollow">\n <strong>Examples Repo</strong></a>\n ·\n <a target="_blank" href="https://discord.gg/ZU36McDgDs" rel="dofollow">\n <strong>Discord</strong></a>\n ·\n <a target="_blank" href="./CONTRIBUTING.md" rel="dofollow">\n <strong>Contributing</strong></a>\n\n <br />\n</h3>\n\n`Langroid` is an intuitive, lightweight, extensible and principled\nPython framework to easily build LLM-powered applications. \nYou set up Agents, equip them with optional components (LLM, \nvector-store and methods), assign them tasks, and have them \ncollaboratively solve a problem by exchanging messages. \nThis Multi-Agent paradigm is inspired by the\n[Actor Framework](https://en.wikipedia.org/wiki/Actor_model)\n(but you do not need to know anything about this!). \n\nLangroid is a fresh take on LLM app-development, where considerable thought has gone \ninto simplifying the developer experience. It does not use `Langchain` or `Llama-Index`.\n\nWe welcome contributions -- See the [contributions](./CONTRIBUTING.md) document\nfor ideas on what to contribute.\n\n**Questions, Feedback, Ideas? Join us on [Discord](https://discord.gg/ZU36McDgDs)!**\n\n<details>\n<summary> <b>:fire: Updates/Releases</b></summary>\n\n- **Sep 2023:**\n - **Use with local LLama Models:** see tutorial [here](https://langroid.github.io/langroid/tutorials/llama/)\n - **Langroid Blog/Newsletter Launched!**: First post is [here](https://substack.com/notes/post/p-136704592) -- Please subscribe to stay updated. \n - **0.1.56:** Support Azure OpenAI. \n - **0.1.55:** Improved [`SQLChatAgent`](https://github.com/langroid/langroid/blob/main/langroid/agent/special/sql/sql_chat_agent.py) that efficiently retrieves relevant schema info when translating natural language to SQL. \n- **Aug 2023:**\n - **[Hierarchical computation](https://langroid.github.io/langroid/examples/agent-tree/)** example using Langroid agents and task orchestration.\n - **0.1.51:** Support for global state, see [test_global_state.py](tests/main/test_global_state.py).\n - **:whale: Langroid Docker image**, available, see instructions below.\n - [**RecipientTool**](langroid/agent/tools/recipient_tool.py) enables (+ enforces) LLM to \nspecify an intended recipient when talking to 2 or more agents. \nSee [this test](tests/main/test_recipient_tool.py) for example usage.\n - **Example:** [Answer questions](examples/docqa/chat-search.py) using Google Search + vecdb-retrieval from URL contents. \n - **0.1.39:** [`GoogleSearchTool`](langroid/agent/tools/google_search_tool.py) to enable Agents (their LLM) to do Google searches via function-calling/tools.\n See [this chat example](examples/basic/chat-search.py) for how easy it is to add this tool to an agent.\n - **Colab notebook** to try the quick-start examples: [](https://colab.research.google.com/github/langroid/langroid/blob/main/examples/langroid_quick_examples.ipynb) \n - **0.1.37:** Added [`SQLChatAgent`](langroid/agent/special/sql_chat_agent.py) -- thanks to our latest contributor [Rithwik Babu](https://github.com/rithwikbabu)!\n - Multi-agent Example: [Autocorrect chat](examples/basic/autocorrect.py)\n- **July 2023:** \n - **0.1.30:** Added [`TableChatAgent`](langroid/agent/special/table_chat_agent.py) to \n [chat](examples/data-qa/table_chat.py) with tabular datasets (dataframes, files, URLs): LLM generates Pandas code,\n and code is executed using Langroid\'s tool/function-call mechanism. \n - **Demo:** 3-agent system for Audience [Targeting](https://langroid.github.io/langroid/demos/targeting/audience-targeting/).\n - **0.1.27**: Added [support](langroid/cachedb/momento_cachedb.py) \n for [Momento Serverless Cache](https://www.gomomento.com/) as an alternative to Redis.\n - **0.1.24**: [`DocChatAgent`](langroid/agent/special/doc_chat_agent.py) \n now [accepts](langroid/parsing/pdf_parser.py) PDF files or URLs.\n\n</details>\n\n# :rocket: Demo\nSuppose you want to extract structured information about the key terms \nof a commercial lease document. You can easily do this with Langroid using a two-agent system,\nas we show in the [langroid-examples](https://github.com/langroid/langroid-examples/blob/main/examples/docqa/chat_multi_extract.py) repo.\nThe demo showcases just a few of the many features of Langroid, such as:\n- Multi-agent collaboration: `LeaseExtractor` is in charge of the task, and its LLM (GPT4) generates questions \nto be answered by the `DocAgent`.\n- Retrieval augmented question-answering, with **source-citation**: `DocAgent` LLM (GPT4) uses retrieval from a vector-store to \nanswer the `LeaseExtractor`\'s questions, cites the specific excerpt supporting the answer. \n- Function-calling (also known as tool/plugin): When it has all the information it \nneeds, the `LeaseExtractor` LLM presents the information in a structured \nformat using a Function-call. \n\nHere is what it looks like in action:\n\n\n\n\n# :zap: Highlights\n\n- **Agents as first-class citizens:** The [Agent](https://langroid.github.io/langroid/reference/agent/base/#langroid.agent.base.Agent) class encapsulates LLM conversation state,\n and optionally a vector-store and tools. Agents are a core abstraction in Langroid;\n Agents act as _message transformers_, and by default provide 3 _responder_ methods, one corresponding to each entity: LLM, Agent, User.\n- **Tasks:** A [Task](https://langroid.github.io/langroid/reference/agent/task/) class wraps an Agent, and gives the agent instructions (or roles, or goals), \n manages iteration over an Agent\'s responder methods, \n and orchestrates multi-agent interactions via hierarchical, recursive\n task-delegation. The `Task.run()` method has the same \n type-signature as an Agent\'s responder\'s methods, and this is key to how \n a task of an agent can delegate to other sub-tasks: from the point of view of a Task,\n sub-tasks are simply additional responders, to be used in a round-robin fashion \n after the agent\'s own responders.\n- **Modularity, Reusabilily, Loose coupling:** The `Agent` and `Task` abstractions allow users to design\n Agents with specific skills, wrap them in Tasks, and combine tasks in a flexible way.\n- **LLM Support**: Langroid supports OpenAI LLMs including GPT-3.5-Turbo,\n GPT-4.\n- **Caching of LLM responses:** Langroid supports [Redis](https://redis.com/try-free/) and \n [Momento](https://www.gomomento.com/) to cache LLM responses.\n- **Vector-stores**: [Qdrant](https://qdrant.tech/) and [Chroma](https://www.trychroma.com/) are currently supported.\n Vector stores allow for Retrieval-Augmented-Generation (RAG).\n- **Grounding and source-citation:** Access to external documents via vector-stores \n allows for grounding and source-citation.\n- **Observability, Logging, Lineage:** Langroid generates detailed logs of multi-agent interactions and\n maintains provenance/lineage of messages, so that you can trace back\n the origin of a message.\n- **Tools/Plugins/Function-calling**: Langroid supports OpenAI\'s recently\n released [function calling](https://platform.openai.com/docs/guides/gpt/function-calling)\n feature. In addition, Langroid has its own native equivalent, which we\n call **tools** (also known as "plugins" in other contexts). Function\n calling and tools have the same developer-facing interface, implemented\n using [Pydantic](https://docs.pydantic.dev/latest/),\n which makes it very easy to define tools/functions and enable agents\n to use them. Benefits of using Pydantic are that you never have to write\n complex JSON specs for function calling, and when the LLM\n hallucinates malformed JSON, the Pydantic error message is sent back to\n the LLM so it can fix it!\n\n--- \n\n# :gear: Installation and Setup\n\n:whale: For a simpler setup, see the Docker section below, which lets you get started just\nby setting up environment variables in a `.env` file.\n\n### Install `langroid`\nLangroid requires Python 3.11+. We recommend using a virtual environment.\nUse `pip` to install `langroid` (from PyPi) to your virtual environment:\n```bash\npip install langroid\n```\nThe core Langroid package lets you use OpenAI Embeddings models via their API. \nIf you instead want to use the `all-MiniLM-L6-v2` embeddings model\nfrom from HuggingFace, install Langroid like this:\n```bash\npip install langroid[hf-embeddings]\n```\nNote that this will install `torch` and `sentence-transformers` libraries.\n\n<details>\n<summary><b>Optional Installs for using SQL Chat with a PostgreSQL DB </b></summary>\n\nIf you are using `SQLChatAgent` \n(e.g. the script [`examples/data-qa/sql-chat/sql_chat.py`](examples/data-qa/sql-chat/sql_chat.py)),\nwith a postgres db, you will need to:\n\n- Install PostgreSQL dev libraries for your platform, e.g.\n - `sudo apt-get install libpq-dev` on Ubuntu,\n - `brew install postgresql` on Mac, etc.\n- Install langroid with the postgres extra, e.g. `pip install langroid[postgres]`\n or `poetry add langroid[postgres]` or `poetry install -E postgres`.\n If this gives you an error, try `pip install psycopg2-binary` in your virtualenv.\n</details>\n\n### Set up environment variables (API keys, etc)\n\nTo get started, all you need is an OpenAI API Key.\nIf you don\'t have one, see [this OpenAI Page](https://help.openai.com/en/collections/3675940-getting-started-with-openai-api).\nCurrently only OpenAI models are supported. Others will be added later\n(Pull Requests welcome!).\n\nIn the root of the repo, copy the `.env-template` file to a new file `.env`: \n```bash\ncp .env-template .env\n```\nThen insert your OpenAI API Key. \nYour `.env` file should look like this:\n```bash\nOPENAI_API_KEY=your-key-here-without-quotes\n````\n\nAlternatively, you can set this as an environment variable in your shell\n(you will need to do this every time you open a new shell):\n```bash\nexport OPENAI_API_KEY=your-key-here-without-quotes\n```\n\n\n<details>\n<summary><b>Optional Setup Instructions (click to expand) </b></summary>\n\nAll of the following environment variable settings are optional, and some are only needed \nto use specific features (as noted below).\n\n- **Qdrant** Vector Store API Key, URL. This is only required if you want to use Qdrant cloud.\n You can sign up for a free 1GB account at [Qdrant cloud](https://cloud.qdrant.io).\n If you skip setting up these, Langroid will use Qdrant in local-storage mode.\n Alternatively [Chroma](https://docs.trychroma.com/) is also currently supported. \n We use the local-storage version of Chroma, so there is no need for an API key.\n Langroid uses Qdrant by default.\n- **Redis** Password, host, port: This is optional, and only needed to cache LLM API responses\n using Redis Cloud. Redis [offers](https://redis.com/try-free/) a free 30MB Redis account\n which is more than sufficient to try out Langroid and even beyond.\n If you don\'t set up these, Langroid will use a pure-python \n Redis in-memory cache via the [Fakeredis](https://fakeredis.readthedocs.io/en/latest/) library.\n- **Momento** Serverless Caching of LLM API responses (as an alternative to Redis). \n To use Momento instead of Redis:\n - enter your Momento Token in the `.env` file, as the value of `MOMENTO_AUTH_TOKEN` (see example file below),\n - in the `.env` file set `CACHE_TYPE=momento` (instead of `CACHE_TYPE=redis` which is the default).\n- **GitHub** Personal Access Token (required for apps that need to analyze git\n repos; token-based API calls are less rate-limited). See this\n [GitHub page](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens).\n- **Google Custom Search API Credentials:** Only needed to enable an Agent to use the `GoogleSearchTool`.\n To use Google Search as an LLM Tool/Plugin/function-call, \n you\'ll need to set up \n [a Google API key](https://developers.google.com/custom-search/v1/introduction#identify_your_application_to_google_with_api_key),\n then [setup a Google Custom Search Engine (CSE) and get the CSE ID](https://developers.google.com/custom-search/docs/tutorial/creatingcse).\n (Documentation for these can be challenging, we suggest asking GPT4 for a step-by-step guide.)\n After obtaining these credentials, store them as values of \n `GOOGLE_API_KEY` and `GOOGLE_CSE_ID` in your `.env` file. \n Full documentation on using this (and other such "stateless" tools) is coming soon, but \n in the meantime take a peek at this [chat example](examples/basic/chat-search.py), which \n shows how you can easily equip an Agent with a `GoogleSearchtool`.\n \n\n\nIf you add all of these optional variables, your `.env` file should look like this:\n```bash\nOPENAI_API_KEY=your-key-here-without-quotes\nGITHUB_ACCESS_TOKEN=your-personal-access-token-no-quotes\nCACHE_TYPE=redis # or momento\nREDIS_PASSWORD=your-redis-password-no-quotes\nREDIS_HOST=your-redis-hostname-no-quotes\nREDIS_PORT=your-redis-port-no-quotes\nMOMENTO_AUTH_TOKEN=your-momento-token-no-quotes # instead of REDIS* variables\nQDRANT_API_KEY=your-key\nQDRANT_API_URL=https://your.url.here:6333 # note port number must be included\nGOOGLE_API_KEY=your-key\nGOOGLE_CSE_ID=your-cse-id\n```\n</details>\n\n<details>\n<summary><b>Optional setup instructions for Microsoft Azure OpenAI(click to expand)</b></summary> \n\nWhen using Azure OpenAI, additional environment variables are required in the \n`.env` file.\nThis page [Microsoft Azure OpenAI](https://learn.microsoft.com/en-us/azure/ai-services/openai/chatgpt-quickstart?tabs=command-line&pivots=programming-language-python#environment-variables)\nprovides more information, and you can set each environment variable as follows:\n\n- `AZURE_API_KEY`, from the value of `API_KEY`\n- `AZURE_OPENAI_API_BASE` from the value of `ENDPOINT`, typically looks like `https://your.domain.azure.com`.\n- For `AZURE_OPENAI_API_VERSION`, you can use the default value in `.env-template`, and latest version can be found [here](https://learn.microsoft.com/en-us/azure/ai-services/openai/whats-new#azure-openai-chat-completion-general-availability-ga)\n- `AZURE_OPENAI_DEPLOYMENT_NAME` is the name of the deployed model, which is defined by the user during the model setup \n- `AZURE_GPT_MODEL_NAME` GPT-3.5-Turbo or GPT-4 model names that you chose when you setup your Azure OpenAI account.\n\n</details>\n\n---\n\n# :whale: Docker Instructions\n\nWe provide a containerized version of the [`langroid-examples`](https://github.com/langroid/langroid-examples) \nrepository via this [Docker Image](https://hub.docker.com/r/langroid/langroid).\nAll you need to do is set up environment variables in the `.env` file.\nPlease follow these steps to setup the container:\n\n```bash\n# get the .env file template from `langroid` repo\nwget https://github.com/langroid/langroid/blob/main/.env-template .env\n\n# Edit the .env file with your favorite editor (here nano), \n# and add API keys as explained above\nnano .env\n\n# launch the container\ndocker run -it -v ./.env:/.env langroid/langroid\n\n# Use this command to run any of the scripts in the `examples` directory\npython examples/<Path/To/Example.py> \n``` \n\n\n\n# :tada: Usage Examples\n\nThese are quick teasers to give a glimpse of what you can do with Langroid\nand how your code would look. \n\n:warning: The code snippets below are intended to give a flavor of the code\nand they are **not** complete runnable examples! For that we encourage you to \nconsult the [`langroid-examples`](https://github.com/langroid/langroid-examples) \nrepository.\n\n:information_source: The various LLM prompts and instructions in Langroid\nhave been tested to work well with GPT4.\nSwitching to GPT3.5-Turbo is easy via a config flag\n(e.g., `cfg = OpenAIGPTConfig(chat_model=OpenAIChatModel.GPT3_5_TURBO)`),\nand may suffice for some applications, but in general you may see inferior results.\n\n\n:book: Also see the\n[`Getting Started Guide`](https://langroid.github.io/langroid/quick-start/)\nfor a detailed tutorial.\n\n\n\nClick to expand any of the code examples below.\nAll of these can be run in a Colab notebook:\n[](https://colab.research.google.com/github/langroid/langroid/blob/main/examples/langroid_quick_examples.ipynb)\n\n<details>\n<summary> <b> Direct interaction with OpenAI LLM </b> </summary>\n\n```python\nfrom langroid.language_models.openai_gpt import ( \n OpenAIGPTConfig, OpenAIChatModel, OpenAIGPT,\n)\nfrom langroid.language_models.base import LLMMessage, Role\n\ncfg = OpenAIGPTConfig(chat_model=OpenAIChatModel.GPT4)\n\nmdl = OpenAIGPT(cfg)\n\nmessages = [\n LLMMessage(content="You are a helpful assistant", role=Role.SYSTEM), \n LLMMessage(content="What is the capital of Ontario?", role=Role.USER),\n]\nresponse = mdl.chat(messages, max_tokens=200)\nprint(response.message)\n```\n</details>\n\n<details>\n<summary> <b> Define an agent, set up a task, and run it </b> </summary>\n\n```python\nfrom langroid.agent.chat_agent import ChatAgent, ChatAgentConfig\nfrom langroid.agent.task import Task\nfrom langroid.language_models.openai_gpt import OpenAIChatModel, OpenAIGPTConfig\n\nconfig = ChatAgentConfig(\n llm = OpenAIGPTConfig(\n chat_model=OpenAIChatModel.GPT4,\n ),\n vecdb=None, # no vector store\n)\nagent = ChatAgent(config)\n# get response from agent\'s LLM, and put this in an interactive loop...\n# answer = agent.llm_response("What is the capital of Ontario?")\n # ... OR instead, set up a task (which has a built-in loop) and run it\ntask = Task(agent, name="Bot") \ntask.run() # ... a loop seeking response from LLM or User at each turn\n```\n</details>\n\n<details>\n<summary><b> Three communicating agents </b></summary>\n\nA toy numbers game, where when given a number `n`:\n- `repeater_agent`\'s LLM simply returns `n`,\n- `even_agent`\'s LLM returns `n/2` if `n` is even, else says "DO-NOT-KNOW"\n- `odd_agent`\'s LLM returns `3*n+1` if `n` is odd, else says "DO-NOT-KNOW"\n\nFirst define the 3 agents, and set up their tasks with instructions:\n\n```python\nfrom langroid.utils.constants import NO_ANSWER\nfrom langroid.agent.chat_agent import ChatAgent, ChatAgentConfig\nfrom langroid.agent.task import Task\nfrom langroid.language_models.openai_gpt import OpenAIChatModel, OpenAIGPTConfig\nconfig = ChatAgentConfig(\n llm = OpenAIGPTConfig(\n chat_model=OpenAIChatModel.GPT4,\n ),\n vecdb = None,\n)\nrepeater_agent = ChatAgent(config)\nrepeater_task = Task(\n repeater_agent,\n name = "Repeater",\n system_message="""\n Your job is to repeat whatever number you receive.\n """,\n llm_delegate=True, # LLM takes charge of task\n single_round=False, \n)\neven_agent = ChatAgent(config)\neven_task = Task(\n even_agent,\n name = "EvenHandler",\n system_message=f"""\n You will be given a number. \n If it is even, divide by 2 and say the result, nothing else.\n If it is odd, say {NO_ANSWER}\n """,\n single_round=True, # task done after 1 step() with valid response\n)\n\nodd_agent = ChatAgent(config)\nodd_task = Task(\n odd_agent,\n name = "OddHandler",\n system_message=f"""\n You will be given a number n. \n If it is odd, return (n*3+1), say nothing else. \n If it is even, say {NO_ANSWER}\n """,\n single_round=True, # task done after 1 step() with valid response\n)\n```\nThen add the `even_task` and `odd_task` as sub-tasks of `repeater_task`, \nand run the `repeater_task`, kicking it off with a number as input:\n```python\nrepeater_task.add_sub_task([even_task, odd_task])\nrepeater_task.run("3")\n```\n\n</details>\n\n<details>\n<summary><b> Simple Tool/Function-calling example </b></summary>\n\nLangroid leverages Pydantic to support OpenAI\'s\n[Function-calling API](https://platform.openai.com/docs/guides/gpt/function-calling)\nas well as its own native tools. The benefits are that you don\'t have to write\nany JSON to specify the schema, and also if the LLM hallucinates a malformed\ntool syntax, Langroid sends the Pydantic validation error (suitiably sanitized) \nto the LLM so it can fix it!\n\nSimple example: Say the agent has a secret list of numbers, \nand we want the LLM to find the smallest number in the list. \nWe want to give the LLM a `probe` tool/function which takes a\nsingle number `n` as argument. The tool handler method in the agent\nreturns how many numbers in its list are at most `n`.\n\nFirst define the tool using Langroid\'s `ToolMessage` class:\n\n\n```python\nfrom langroid.agent.tool_message import ToolMessage\nclass ProbeTool(ToolMessage):\n request: str = "probe" # specifies which agent method handles this tool\n purpose: str = """\n To find how many numbers in my list are less than or equal to \n the <number> you specify.\n """ # description used to instruct the LLM on when/how to use the tool\n number: int # required argument to the tool\n```\n\nThen define a `SpyGameAgent` as a subclass of `ChatAgent`, \nwith a method `probe` that handles this tool:\n\n```python\nfrom langroid.agent.chat_agent import ChatAgent, ChatAgentConfig\nclass SpyGameAgent(ChatAgent):\n def __init__(self, config: ChatAgentConfig):\n super().__init__(config)\n self.numbers = [3, 4, 8, 11, 15, 25, 40, 80, 90]\n\n def probe(self, msg: ProbeTool) -> str:\n # return how many numbers in self.numbers are less or equal to msg.number\n return str(len([n for n in self.numbers if n <= msg.number]))\n```\n\nWe then instantiate the agent and enable it to use and respond to the tool:\n\n```python\nfrom langroid.language_models.openai_gpt import OpenAIChatModel, OpenAIGPTConfig\nspy_game_agent = SpyGameAgent(\n ChatAgentConfig(\n name="Spy",\n llm = OpenAIGPTConfig(\n chat_model=OpenAIChatModel.GPT4,\n ),\n vecdb=None,\n use_tools=False, # don\'t use Langroid native tool\n use_functions_api=True, # use OpenAI function-call API\n )\n)\nspy_game_agent.enable_message(ProbeTool)\n```\n\nFor a full working example see the\n[chat-agent-tool.py](https://github.com/langroid/langroid-examples/blob/main/examples/quick-start/chat-agent-tool.py)\nscript in the `langroid-examples` repo.\n</details>\n\n<details>\n<summary> <b>Tool/Function-calling to extract structured information from text </b> </summary>\n\nSuppose you want an agent to extract \nthe key terms of a lease, from a lease document, as a nested JSON structure.\nFirst define the desired structure via Pydantic models:\n\n```python\nfrom pydantic import BaseModel\nclass LeasePeriod(BaseModel):\n start_date: str\n end_date: str\n\n\nclass LeaseFinancials(BaseModel):\n monthly_rent: str\n deposit: str\n\nclass Lease(BaseModel):\n period: LeasePeriod\n financials: LeaseFinancials\n address: str\n```\n\nThen define the `LeaseMessage` tool as a subclass of Langroid\'s `ToolMessage`.\nNote the tool has a required argument `terms` of type `Lease`:\n\n```python\nclass LeaseMessage(ToolMessage):\n request: str = "lease_info"\n purpose: str = """\n Collect information about a Commercial Lease.\n """\n terms: Lease\n```\n\nThen define a `LeaseExtractorAgent` with a method `lease_info` that handles this tool,\ninstantiate the agent, and enable it to use and respond to this tool:\n\n```python\nclass LeaseExtractorAgent(ChatAgent):\n def lease_info(self, message: LeaseMessage) -> str:\n print(\n f"""\n DONE! Successfully extracted Lease Info:\n {message.terms}\n """\n )\n return json.dumps(message.terms.dict())\n \nlease_extractor_agent = LeaseExtractorAgent(\n ChatAgentConfig(\n llm=OpenAIGPTConfig(),\n use_functions_api=False,\n use_tools=True,\n )\n)\nlease_extractor_agent.enable_message(LeaseMessage)\n```\n\nSee the [`chat_multi_extract.py`](https://github.com/langroid/langroid-examples/blob/main/examples/docqa/chat_multi_extract.py)\nscript in the `langroid-examples` repo for a full working example.\n</details>\n\n<details>\n<summary><b> Chat with documents (file paths, URLs, etc) </b></summary>\n\nLangroid provides a specialized agent class `DocChatAgent` for this purpose.\nIt incorporates document sharding, embedding, storage in a vector-DB, \nand retrieval-augmented query-answer generation.\nUsing this class to chat with a collection of documents is easy.\nFirst create a `DocChatAgentConfig` instance, with a \n`doc_paths` field that specifies the documents to chat with.\n\n```python\nfrom langroid.agent.doc_chat_agent import DocChatAgentConfig\nconfig = DocChatAgentConfig(\n doc_paths = [\n "https://en.wikipedia.org/wiki/Language_model",\n "https://en.wikipedia.org/wiki/N-gram_language_model",\n "/path/to/my/notes-on-language-models.txt",\n ]\n llm = OpenAIGPTConfig(\n chat_model=OpenAIChatModel.GPT4,\n ),\n vecdb=VectorStoreConfig(\n type="qdrant",\n ),\n)\n```\n\nThen instantiate the `DocChatAgent` (this ingests the docs into the vector-store):\n\n```python\nagent = DocChatAgent(config)\n```\nThen we can either ask the agent one-off questions,\n```python\nagent.chat("What is a language model?")\n```\nor wrap it in a `Task` and run an interactive loop with the user:\n```python\nfrom langroid.task import Task\ntask = Task(agent)\ntask.run()\n```\n\nSee full working scripts in the \n[`docqa`](https://github.com/langroid/langroid-examples/tree/main/examples/docqa)\nfolder of the `langroid-examples` repo.\n</details>\n\n<details>\n<summary><b> :fire: Chat with tabular data (file paths, URLs, dataframes) </b></summary>\n\nUsing Langroid you can set up a `TableChatAgent` with a dataset (file path, URL or dataframe),\nand query it. The Agent\'s LLM generates Pandas code to answer the query, \nvia function-calling (or tool/plugin), and the Agent\'s function-handling method\nexecutes the code and returns the answer.\n\nHere is how you can do this:\n\n```python\nfrom langroid.agent.special.table_chat_agent import TableChatAgent, TableChatAgentConfig\nfrom langroid.agent.task import Task\nfrom langroid.language_models.openai_gpt import OpenAIChatModel, OpenAIGPTConfig\n```\n\nSet up a `TableChatAgent` for a data file, URL or dataframe\n(Ensure the data table has a header row; the delimiter/separator is auto-detected):\n```python\ndataset = "https://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-red.csv"\n# or dataset = "/path/to/my/data.csv"\n# or dataset = pd.read_csv("/path/to/my/data.csv")\nagent = TableChatAgent(\n config=TableChatAgentConfig(\n data=dataset, \n llm=OpenAIGPTConfig(\n chat_model=OpenAIChatModel.GPT4,\n ),\n )\n)\n```\nSet up a task, and ask one-off questions like this: \n\n```python\ntask = Task(\n agent, \n name = "DataAssistant",\n default_human_response="", # to avoid waiting for user input\n)\nresult = task.run(\n "What is the average alcohol content of wines with a quality rating above 7?",\n turns=2 # return after user question, LLM fun-call/tool response, Agent code-exec result\n) \nprint(result.content)\n```\nOr alternatively, set up a task and run it in an interactive loop with the user:\n\n```python\ntask = Task(agent, name="DataAssistant")\ntask.run()\n``` \n\nFor a full working example see the \n[`table_chat.py`](https://github.com/langroid/langroid-examples/tree/main/examples/data-qa/table_chat.py)\nscript in the `langroid-examples` repo.\n\n\n</details>\n\n---\n\n# :heart: Thank you to our [supporters](https://github.com/langroid/langroid/stargazers)\n\nIf you like this project, please give it a star ⭐ and 📢 spread the word in your network or social media:\n\n[](https://twitter.com/intent/tweet?text=Langroid%20is%20a%20powerful,%20elegant%20new%20framework%20to%20easily%20build%20%23LLM%20applications.%20You%20set%20up%20LLM-powered%20Agents%20with%20vector-stores,%20assign%20tasks,%20and%20have%20them%20collaboratively%20solve%20problems%20via%20message-transformations.%20https://github.com/langroid/langroid)\n[](https://www.linkedin.com/shareArticle?mini=true&url=https://github.com/langroid/langroid&title=Langroid:%20A%20Powerful,%20Elegant%20Framework&summary=Langroid%20is%20a%20powerful,%20elegant%20new%20framework%20to%20easily%20build%20%23LLM%20applications.%20You%20set%20up%20LLM-powered%20Agents%20with%20vector-stores,%20assign%20tasks,%20and%20have%20them%20collaboratively%20solve%20problems%20via%20message-transformations.)\n[](https://news.ycombinator.com/submitlink?u=https%3A%2F%2Fgithub.com%2Flangroid%2Flangroid&t=Harness%20LLMs%20with%20Multi-Agent%20Programming)\n[](https://www.reddit.com/submit?url=https%3A%2F%2Fgithub.com%2Flangroid%2Flangroid&title=Harness%20LLMs%20with%20Multi-Agent%20Programming)\n\n\n\n\nYour support will help build Langroid\'s momentum and community.\n\n\n\n\n# Langroid Co-Founders\n\n- [Prasad Chalasani](https://www.linkedin.com/in/pchalasani/) (IIT BTech/CS, CMU PhD/ML; Independent ML Consultant)\n- [Somesh Jha](https://www.linkedin.com/in/somesh-jha-80208015/) (IIT BTech/CS, CMU PhD/CS; Professor of CS, U Wisc at Madison)\n\n\n\n',
|
85
86
|
'author': 'Prasad Chalasani',
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
{langroid-0.1.59 → langroid-0.1.60}/langroid/agent/special/sql/utils/description_extractors.py
RENAMED
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|