django_ai_assistant.helpers.assistants¶
AIAssistant
¶
Base class for AI Assistants. Subclasses must define at least the following attributes:
- id: str
- name: str
- instructions: str
- model: str
Subclasses can override the public methods to customize the behavior of the assistant.
Tools can be added to the assistant by decorating methods with @method_tool
.
Check the docs Tutorial for more info on how to build an AI Assistant.
Source code in django_ai_assistant/helpers/assistants.py
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 |
|
id: str
class-attribute
¶
Class variable with the id of the assistant. Used to select the assistant to use.
Must be unique across the whole Django project and match the pattern '^[a-zA-Z0-9_-]+$'.
name: str
class-attribute
¶
Class variable with the name of the assistant. Should be a friendly name to optionally display to users.
instructions: str
instance-attribute
¶
Instructions for the AI assistant knowing what to do. This is the LLM system prompt.
model: str
instance-attribute
¶
LLM model name to use for the assistant.
Should be a valid model name from OpenAI, because the default get_llm
method uses OpenAI.
get_llm
can be overridden to use a different LLM implementation.
temperature: float = 1.0
class-attribute
instance-attribute
¶
Temperature to use for the assistant LLM model.
Defaults to 1.0
.
has_rag: bool = False
class-attribute
instance-attribute
¶
Whether the assistant uses RAG (Retrieval-Augmented Generation) or not.
Defaults to False
.
When True, the assistant will use a retriever to get documents to provide as context to the LLM.
For this to work, the instructions
should contain a placeholder for the context,
which is {context}
by default.
Additionally, the assistant class should implement the get_retriever
method to return
the retriever to use.
_method_tools: Sequence[BaseTool]
instance-attribute
¶
List of @method_tool
tools the assistant can use. Automatically set by the constructor.
_registry: dict[str, type[AIAssistant]] = {}
class-attribute
¶
Registry of all AIAssistant subclasses by their id.
Automatically populated by when a subclass is declared.
Use get_cls_registry
and get_cls
to access the registry.
_user: Any | None = user
instance-attribute
¶
The current user the assistant is helping. A model instance.
Set by the constructor. When API views are used, this is set to the current request user.
Can be used in any @method_tool
to customize behavior.
_request: Any | None = request
instance-attribute
¶
The current Django request the assistant was initialized with. A request instance.
Set by the constructor.
Can be used in any @method_tool
to customize behavior.
_view: Any | None = view
instance-attribute
¶
The current Django view the assistant was initialized with. A view instance.
Set by the constructor.
Can be used in any @method_tool
to customize behavior.
_init_kwargs: dict[str, Any] = kwargs
instance-attribute
¶
Extra keyword arguments passed to the constructor.
Set by the constructor.
Can be used in any @method_tool
to customize behavior.
__init__(*, user=None, request=None, view=None, **kwargs)
¶
Initialize the AIAssistant instance.
Optionally set the current user, request, and view for the assistant.
Those can be used in any @method_tool
to customize behavior.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
user |
Any | None
|
The current user the assistant is helping. A model instance.
Defaults to |
None
|
request |
Any | None
|
The current Django request the assistant was initialized with.
A request instance. Defaults to |
None
|
view |
Any | None
|
The current Django view the assistant was initialized with.
A view instance. Defaults to |
None
|
**kwargs |
Any
|
Extra keyword arguments passed to the constructor. Stored in |
{}
|
Source code in django_ai_assistant/helpers/assistants.py
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 |
|
get_cls_registry()
classmethod
¶
Get the registry of AIAssistant classes.
Returns:
Type | Description |
---|---|
dict[str, type[AIAssistant]]
|
dict[str, type[AIAssistant]]: A dictionary mapping assistant ids to their classes. |
Source code in django_ai_assistant/helpers/assistants.py
188 189 190 191 192 193 194 195 |
|
get_cls(assistant_id)
classmethod
¶
Get the AIAssistant class for the given assistant ID.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
assistant_id |
str
|
The ID of the assistant to get. |
required |
Returns: type[AIAssistant]: The AIAssistant subclass for the given ID.
Source code in django_ai_assistant/helpers/assistants.py
197 198 199 200 201 202 203 204 205 206 |
|
clear_cls_registry()
classmethod
¶
Clear the registry of AIAssistant classes.
Source code in django_ai_assistant/helpers/assistants.py
208 209 210 211 212 |
|
get_instructions()
¶
Get the instructions for the assistant. By default, this is the instructions
attribute.
Override the instructions
attribute or this method to use different instructions.
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
The instructions for the assistant, i.e., the LLM system prompt. |
Source code in django_ai_assistant/helpers/assistants.py
214 215 216 217 218 219 220 221 |
|
get_model()
¶
Get the LLM model name for the assistant. By default, this is the model
attribute.
Used by the get_llm
method to create the LLM instance.
Override the model
attribute or this method to use a different LLM model.
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
The LLM model name for the assistant. |
Source code in django_ai_assistant/helpers/assistants.py
223 224 225 226 227 228 229 230 231 |
|
get_temperature()
¶
Get the temperature to use for the assistant LLM model.
By default, this is the temperature
attribute, which is 1.0
by default.
Used by the get_llm
method to create the LLM instance.
Override the temperature
attribute or this method to use a different temperature.
Returns:
Name | Type | Description |
---|---|---|
float |
float
|
The temperature to use for the assistant LLM model. |
Source code in django_ai_assistant/helpers/assistants.py
233 234 235 236 237 238 239 240 241 242 |
|
get_model_kwargs()
¶
Get additional keyword arguments to pass to the LLM model constructor.
Used by the get_llm
method to create the LLM instance.
Override this method to pass additional keyword arguments to the LLM model constructor.
Returns:
Type | Description |
---|---|
dict[str, Any]
|
dict[str, Any]: Additional keyword arguments to pass to the LLM model constructor. |
Source code in django_ai_assistant/helpers/assistants.py
244 245 246 247 248 249 250 251 252 |
|
get_prompt_template()
¶
Get the ChatPromptTemplate
for the Langchain chain to use.
The system prompt comes from the get_instructions
method.
The template includes placeholders for the instructions, chat {history}
, user {input}
,
and {agent_scratchpad}
, all which are necessary for the chain to work properly.
The chat history is filled by the chain using the message history from get_message_history
.
If the assistant uses RAG, the instructions should contain a placeholder
for the context, which is {context}
by default, defined by the get_context_placeholder
method.
Returns:
Name | Type | Description |
---|---|---|
ChatPromptTemplate |
ChatPromptTemplate
|
The chat prompt template for the Langchain chain. |
Source code in django_ai_assistant/helpers/assistants.py
254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 |
|
get_message_history(thread_id)
¶
Get the chat message history instance for the given thread_id
.
The Langchain chain uses the return of this method to get the thread messages
for the assistant, filling the history
placeholder in the get_prompt_template
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
thread_id |
Any | None
|
The thread ID for the chat message history.
If |
required |
Returns:
Name | Type | Description |
---|---|---|
BaseChatMessageHistory |
BaseChatMessageHistory
|
The chat message history instance for the given |
Source code in django_ai_assistant/helpers/assistants.py
283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 |
|
get_llm()
¶
Get the Langchain LLM instance for the assistant. By default, this uses the OpenAI implementation.
get_model
, get_temperature
, and get_model_kwargs
are used to create the LLM instance.
Override this method to use a different LLM implementation.
Returns:
Name | Type | Description |
---|---|---|
BaseChatModel |
BaseChatModel
|
The LLM instance for the assistant. |
Source code in django_ai_assistant/helpers/assistants.py
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 |
|
get_tools()
¶
Get the list of method tools the assistant can use.
By default, this is the _method_tools
attribute, which are all @method_tool
s.
Override and call super to add additional tools, such as any langchain_community tools.
Returns:
Type | Description |
---|---|
Sequence[BaseTool]
|
Sequence[BaseTool]: The list of tools the assistant can use. |
Source code in django_ai_assistant/helpers/assistants.py
322 323 324 325 326 327 328 329 330 331 |
|
get_document_separator()
¶
Get the RAG document separator to use in the prompt. Only used when has_rag=True
.
Defaults to "\n\n"
, which is the Langchain default.
Override this method to use a different separator.
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
a separator for documents in the prompt. |
Source code in django_ai_assistant/helpers/assistants.py
333 334 335 336 337 338 339 340 341 |
|
get_document_prompt()
¶
Get the PromptTemplate template to use when rendering RAG documents in the prompt.
Only used when has_rag=True
.
Defaults to PromptTemplate.from_template("{page_content}")
, which is the Langchain default.
Override this method to use a different template.
Returns:
Name | Type | Description |
---|---|---|
PromptTemplate |
PromptTemplate
|
a prompt template for RAG documents. |
Source code in django_ai_assistant/helpers/assistants.py
343 344 345 346 347 348 349 350 351 352 |
|
get_context_placeholder()
¶
Get the RAG context placeholder to use in the prompt when has_rag=True
.
Defaults to "context"
. Override this method to use a different placeholder.
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
the RAG context placeholder to use in the prompt. |
Source code in django_ai_assistant/helpers/assistants.py
354 355 356 357 358 359 360 361 |
|
get_retriever()
¶
Get the RAG retriever to use for fetching documents.
Must be implemented by subclasses when has_rag=True
.
Returns:
Name | Type | Description |
---|---|---|
BaseRetriever |
BaseRetriever
|
the RAG retriever to use for fetching documents. |
Source code in django_ai_assistant/helpers/assistants.py
363 364 365 366 367 368 369 370 371 372 |
|
get_contextualize_prompt()
¶
Get the contextualize prompt template for the assistant.
This is used when has_rag=True
and there are previous messages in the thread.
Since the latest user question might reference the chat history,
the LLM needs to generate a new standalone question,
and use that question to query the retriever for relevant documents.
By default, this is a prompt that asks the LLM to reformulate the latest user question without the chat history.
Override this method to use a different contextualize prompt.
See get_history_aware_retriever
for how this prompt is used.
Returns:
Name | Type | Description |
---|---|---|
ChatPromptTemplate |
ChatPromptTemplate
|
The contextualize prompt template for the assistant. |
Source code in django_ai_assistant/helpers/assistants.py
374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 |
|
get_history_aware_retriever()
¶
Get the history-aware retriever Langchain chain for the assistant.
This is used when has_rag=True
to fetch documents based on the chat history.
By default, this is a chain that checks if there is chat history, and if so, it uses the chat history to generate a new standalone question to query the retriever for relevant documents.
When there is no chat history, it just passes the input to the retriever.
Override this method to use a different history-aware retriever chain.
Read more about the history-aware retriever in the Langchain docs.
Returns:
Type | Description |
---|---|
Runnable[dict, RetrieverOutput]
|
Runnable[dict, RetrieverOutput]: a history-aware retriever Langchain chain. |
Source code in django_ai_assistant/helpers/assistants.py
405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 |
|
as_chain(thread_id)
¶
Create the Langchain chain for the assistant.
This chain is an agent that supports chat history, tool calling, and RAG (if has_rag=True
).
as_chain
uses many other methods to create the chain.
Prefer to override the other methods to customize the chain for the assistant. Only override this method if you need to customize the chain at a lower level.
The chain input is a dictionary with the key "input"
containing the user message.
The chain output is a dictionary with the key "output"
containing the assistant response,
along with the key "history"
containing the previous chat history.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
thread_id |
Any | None
|
The thread ID for the chat message history.
If |
required |
Returns:
Type | Description |
---|---|
Runnable[dict, dict]
|
Runnable[dict, dict]: The Langchain chain for the assistant. |
Source code in django_ai_assistant/helpers/assistants.py
435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 |
|
invoke(*args, thread_id, **kwargs)
¶
Invoke the assistant Langchain chain with the given arguments and keyword arguments.
This is the lower-level method to run the assistant.
The chain is created by the as_chain
method.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
*args |
Any
|
Positional arguments to pass to the chain.
Make sure to include a |
()
|
thread_id |
Any | None
|
The thread ID for the chat message history.
If |
required |
**kwargs |
Any
|
Keyword arguments to pass to the chain. |
{}
|
Returns:
Name | Type | Description |
---|---|---|
dict |
dict
|
The output of the assistant chain,
structured like |
Source code in django_ai_assistant/helpers/assistants.py
520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 |
|
run(message, thread_id, **kwargs)
¶
Run the assistant with the given message and thread ID.
This is the higher-level method to run the assistant.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
message |
str
|
The user message to pass to the assistant. |
required |
thread_id |
Any | None
|
The thread ID for the chat message history.
If |
required |
**kwargs |
Any
|
Additional keyword arguments to pass to the chain. |
{}
|
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
The assistant response to the user message. |
Source code in django_ai_assistant/helpers/assistants.py
540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 |
|
as_tool(description)
¶
Create a tool from the assistant.
This is useful to compose assistants.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
description |
str
|
The description for the tool. |
required |
Returns:
Name | Type | Description |
---|---|---|
BaseTool |
BaseTool
|
A tool that runs the assistant. The tool name is this assistant's id. |
Source code in django_ai_assistant/helpers/assistants.py
565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 |
|