khoj 2.0.0b13.dev19__py3-none-any.whl → 2.0.0b14.dev7__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.
- khoj/interface/compiled/404/index.html +2 -2
- khoj/interface/compiled/_next/static/chunks/{2327-fe87dd989d71d0eb.js → 2327-438aaec1657c5ada.js} +1 -1
- khoj/interface/compiled/_next/static/chunks/{3260-43d3019b92c315bb.js → 3260-82d2521fab032ff1.js} +1 -1
- khoj/interface/compiled/_next/static/chunks/7127-9273a602fbda737e.js +1 -0
- khoj/interface/compiled/_next/static/chunks/app/agents/layout-0114c87d7ccf6d9b.js +1 -0
- khoj/interface/compiled/_next/static/chunks/app/agents/{page-e291b49977f43880.js → page-f04757fab73908a4.js} +1 -1
- khoj/interface/compiled/_next/static/chunks/app/automations/layout-8639ff99d6c2fec6.js +1 -0
- khoj/interface/compiled/_next/static/chunks/app/automations/{page-198b26df6e09bbb0.js → page-fb0e9353e86acd25.js} +1 -1
- khoj/interface/compiled/_next/static/chunks/app/chat/layout-2ff3e18a6feae92a.js +1 -0
- khoj/interface/compiled/_next/static/chunks/app/chat/page-fd693f65831a2f97.js +1 -0
- khoj/interface/compiled/_next/static/chunks/app/{page-1567cac7b79a7c59.js → page-89f5654035b07c00.js} +1 -1
- khoj/interface/compiled/_next/static/chunks/app/search/layout-78dd7cdd97510485.js +1 -0
- khoj/interface/compiled/_next/static/chunks/app/search/{page-3639e50ec3e9acfd.js → page-6ca71d3d56fc6935.js} +1 -1
- khoj/interface/compiled/_next/static/chunks/app/settings/{page-6081362437c82470.js → page-a798de3944f59629.js} +1 -1
- khoj/interface/compiled/_next/static/chunks/app/share/chat/layout-9781b62e39ca7785.js +1 -0
- khoj/interface/compiled/_next/static/chunks/app/share/chat/{page-e0dcb1762f8c8f88.js → page-07d7ff92aee0bb69.js} +1 -1
- khoj/interface/compiled/_next/static/chunks/{webpack-d60b0c57a6c38d0f.js → webpack-8087292aa01e8e55.js} +1 -1
- khoj/interface/compiled/_next/static/css/{23b26df423cd8a9c.css → a0c2fd63bb396f04.css} +1 -1
- khoj/interface/compiled/_next/static/css/ee66643a6a5bf71c.css +1 -0
- khoj/interface/compiled/_next/static/css/fbacbdfd5e7f3f0e.css +1 -0
- khoj/interface/compiled/agents/index.html +2 -2
- khoj/interface/compiled/agents/index.txt +2 -2
- khoj/interface/compiled/automations/index.html +2 -2
- khoj/interface/compiled/automations/index.txt +3 -3
- khoj/interface/compiled/chat/index.html +2 -2
- khoj/interface/compiled/chat/index.txt +5 -4
- khoj/interface/compiled/index.html +2 -2
- khoj/interface/compiled/index.txt +2 -2
- khoj/interface/compiled/search/index.html +2 -2
- khoj/interface/compiled/search/index.txt +2 -2
- khoj/interface/compiled/settings/index.html +2 -2
- khoj/interface/compiled/settings/index.txt +2 -2
- khoj/interface/compiled/share/chat/index.html +2 -2
- khoj/interface/compiled/share/chat/index.txt +2 -2
- khoj/processor/conversation/google/utils.py +59 -12
- khoj/processor/conversation/openai/gpt.py +65 -28
- khoj/processor/conversation/openai/utils.py +356 -24
- khoj/processor/conversation/prompts.py +16 -9
- khoj/processor/conversation/utils.py +4 -1
- khoj/routers/api_chat.py +5 -2
- khoj/routers/api_content.py +1 -1
- khoj/routers/helpers.py +18 -4
- khoj/routers/research.py +7 -5
- khoj/utils/constants.py +6 -0
- khoj/utils/helpers.py +6 -6
- {khoj-2.0.0b13.dev19.dist-info → khoj-2.0.0b14.dev7.dist-info}/METADATA +1 -1
- {khoj-2.0.0b13.dev19.dist-info → khoj-2.0.0b14.dev7.dist-info}/RECORD +52 -52
- khoj/interface/compiled/_next/static/chunks/7127-97b83757db125ba6.js +0 -1
- khoj/interface/compiled/_next/static/chunks/app/agents/layout-4e2a134ec26aa606.js +0 -1
- khoj/interface/compiled/_next/static/chunks/app/automations/layout-63603d2cb33279f7.js +0 -1
- khoj/interface/compiled/_next/static/chunks/app/chat/layout-ad4d1792ab1a4108.js +0 -1
- khoj/interface/compiled/_next/static/chunks/app/chat/page-9a75d7369f2a7cd2.js +0 -1
- khoj/interface/compiled/_next/static/chunks/app/search/layout-c02531d586972d7d.js +0 -1
- khoj/interface/compiled/_next/static/chunks/app/share/chat/layout-e8e5db7830bf3f47.js +0 -1
- khoj/interface/compiled/_next/static/css/2945c4a857922f3b.css +0 -1
- khoj/interface/compiled/_next/static/css/37a73b87f02df402.css +0 -1
- /khoj/interface/compiled/_next/static/{N-GdBSXoYe-DuObnbXVRO → suayGPC1Ee3s2bFUreGaV}/_buildManifest.js +0 -0
- /khoj/interface/compiled/_next/static/{N-GdBSXoYe-DuObnbXVRO → suayGPC1Ee3s2bFUreGaV}/_ssgManifest.js +0 -0
- {khoj-2.0.0b13.dev19.dist-info → khoj-2.0.0b14.dev7.dist-info}/WHEEL +0 -0
- {khoj-2.0.0b13.dev19.dist-info → khoj-2.0.0b14.dev7.dist-info}/entry_points.txt +0 -0
- {khoj-2.0.0b13.dev19.dist-info → khoj-2.0.0b14.dev7.dist-info}/licenses/LICENSE +0 -0
@@ -9,6 +9,9 @@ from khoj.processor.conversation.openai.utils import (
|
|
9
9
|
clean_response_schema,
|
10
10
|
completion_with_backoff,
|
11
11
|
get_structured_output_support,
|
12
|
+
is_openai_api,
|
13
|
+
responses_chat_completion_with_backoff,
|
14
|
+
responses_completion_with_backoff,
|
12
15
|
to_openai_tools,
|
13
16
|
)
|
14
17
|
from khoj.processor.conversation.utils import (
|
@@ -43,31 +46,52 @@ def send_message_to_model(
|
|
43
46
|
model_kwargs: Dict[str, Any] = {}
|
44
47
|
json_support = get_structured_output_support(model, api_base_url)
|
45
48
|
if tools and json_support == StructuredOutputSupport.TOOL:
|
46
|
-
model_kwargs["tools"] = to_openai_tools(tools)
|
49
|
+
model_kwargs["tools"] = to_openai_tools(tools, use_responses_api=is_openai_api(api_base_url))
|
47
50
|
elif response_schema and json_support >= StructuredOutputSupport.SCHEMA:
|
48
51
|
# Drop unsupported fields from schema passed to OpenAI APi
|
49
52
|
cleaned_response_schema = clean_response_schema(response_schema)
|
50
|
-
|
51
|
-
"
|
52
|
-
|
53
|
-
|
54
|
-
|
55
|
-
|
56
|
-
|
57
|
-
|
53
|
+
if is_openai_api(api_base_url):
|
54
|
+
model_kwargs["text"] = {
|
55
|
+
"format": {
|
56
|
+
"type": "json_schema",
|
57
|
+
"strict": True,
|
58
|
+
"name": response_schema.__name__,
|
59
|
+
"schema": cleaned_response_schema,
|
60
|
+
}
|
61
|
+
}
|
62
|
+
else:
|
63
|
+
model_kwargs["response_format"] = {
|
64
|
+
"type": "json_schema",
|
65
|
+
"json_schema": {
|
66
|
+
"schema": cleaned_response_schema,
|
67
|
+
"name": response_schema.__name__,
|
68
|
+
"strict": True,
|
69
|
+
},
|
70
|
+
}
|
58
71
|
elif response_type == "json_object" and json_support == StructuredOutputSupport.OBJECT:
|
59
72
|
model_kwargs["response_format"] = {"type": response_type}
|
60
73
|
|
61
74
|
# Get Response from GPT
|
62
|
-
|
63
|
-
|
64
|
-
|
65
|
-
|
66
|
-
|
67
|
-
|
68
|
-
|
69
|
-
|
70
|
-
|
75
|
+
if is_openai_api(api_base_url):
|
76
|
+
return responses_completion_with_backoff(
|
77
|
+
messages=messages,
|
78
|
+
model_name=model,
|
79
|
+
openai_api_key=api_key,
|
80
|
+
api_base_url=api_base_url,
|
81
|
+
deepthought=deepthought,
|
82
|
+
model_kwargs=model_kwargs,
|
83
|
+
tracer=tracer,
|
84
|
+
)
|
85
|
+
else:
|
86
|
+
return completion_with_backoff(
|
87
|
+
messages=messages,
|
88
|
+
model_name=model,
|
89
|
+
openai_api_key=api_key,
|
90
|
+
api_base_url=api_base_url,
|
91
|
+
deepthought=deepthought,
|
92
|
+
model_kwargs=model_kwargs,
|
93
|
+
tracer=tracer,
|
94
|
+
)
|
71
95
|
|
72
96
|
|
73
97
|
async def converse_openai(
|
@@ -163,13 +187,26 @@ async def converse_openai(
|
|
163
187
|
logger.debug(f"Conversation Context for GPT: {messages_to_print(messages)}")
|
164
188
|
|
165
189
|
# Get Response from GPT
|
166
|
-
|
167
|
-
|
168
|
-
|
169
|
-
|
170
|
-
|
171
|
-
|
172
|
-
|
173
|
-
|
174
|
-
|
175
|
-
|
190
|
+
if is_openai_api(api_base_url):
|
191
|
+
async for chunk in responses_chat_completion_with_backoff(
|
192
|
+
messages=messages,
|
193
|
+
model_name=model,
|
194
|
+
temperature=temperature,
|
195
|
+
openai_api_key=api_key,
|
196
|
+
api_base_url=api_base_url,
|
197
|
+
deepthought=deepthought,
|
198
|
+
tracer=tracer,
|
199
|
+
):
|
200
|
+
yield chunk
|
201
|
+
else:
|
202
|
+
# For non-OpenAI APIs, use the chat completion method
|
203
|
+
async for chunk in chat_completion_with_backoff(
|
204
|
+
messages=messages,
|
205
|
+
model_name=model,
|
206
|
+
temperature=temperature,
|
207
|
+
openai_api_key=api_key,
|
208
|
+
api_base_url=api_base_url,
|
209
|
+
deepthought=deepthought,
|
210
|
+
tracer=tracer,
|
211
|
+
):
|
212
|
+
yield chunk
|
@@ -21,6 +21,8 @@ from openai.types.chat.chat_completion_chunk import (
|
|
21
21
|
Choice,
|
22
22
|
ChoiceDelta,
|
23
23
|
)
|
24
|
+
from openai.types.responses import Response as OpenAIResponse
|
25
|
+
from openai.types.responses import ResponseFunctionToolCall, ResponseReasoningItem
|
24
26
|
from pydantic import BaseModel
|
25
27
|
from tenacity import (
|
26
28
|
before_sleep_log,
|
@@ -53,13 +55,31 @@ openai_clients: Dict[str, openai.OpenAI] = {}
|
|
53
55
|
openai_async_clients: Dict[str, openai.AsyncOpenAI] = {}
|
54
56
|
|
55
57
|
|
58
|
+
def _extract_text_for_instructions(content: Union[str, List, Dict, None]) -> str:
|
59
|
+
"""Extract plain text from a message content suitable for Responses API instructions."""
|
60
|
+
if content is None:
|
61
|
+
return ""
|
62
|
+
if isinstance(content, str):
|
63
|
+
return content
|
64
|
+
if isinstance(content, list):
|
65
|
+
texts: List[str] = []
|
66
|
+
for part in content:
|
67
|
+
if isinstance(part, dict) and part.get("type") == "input_text" and part.get("text"):
|
68
|
+
texts.append(str(part.get("text")))
|
69
|
+
return "\n\n".join(texts)
|
70
|
+
if isinstance(content, dict):
|
71
|
+
# If a single part dict was passed
|
72
|
+
if content.get("type") == "input_text" and content.get("text"):
|
73
|
+
return str(content.get("text"))
|
74
|
+
# Fallback to string conversion
|
75
|
+
return str(content)
|
76
|
+
|
77
|
+
|
56
78
|
@retry(
|
57
79
|
retry=(
|
58
80
|
retry_if_exception_type(openai._exceptions.APITimeoutError)
|
59
|
-
| retry_if_exception_type(openai._exceptions.APIError)
|
60
|
-
| retry_if_exception_type(openai._exceptions.APIConnectionError)
|
61
81
|
| retry_if_exception_type(openai._exceptions.RateLimitError)
|
62
|
-
| retry_if_exception_type(openai._exceptions.
|
82
|
+
| retry_if_exception_type(openai._exceptions.InternalServerError)
|
63
83
|
| retry_if_exception_type(ValueError)
|
64
84
|
),
|
65
85
|
wait=wait_random_exponential(min=1, max=10),
|
@@ -227,10 +247,8 @@ def completion_with_backoff(
|
|
227
247
|
@retry(
|
228
248
|
retry=(
|
229
249
|
retry_if_exception_type(openai._exceptions.APITimeoutError)
|
230
|
-
| retry_if_exception_type(openai._exceptions.APIError)
|
231
|
-
| retry_if_exception_type(openai._exceptions.APIConnectionError)
|
232
250
|
| retry_if_exception_type(openai._exceptions.RateLimitError)
|
233
|
-
| retry_if_exception_type(openai._exceptions.
|
251
|
+
| retry_if_exception_type(openai._exceptions.InternalServerError)
|
234
252
|
| retry_if_exception_type(ValueError)
|
235
253
|
),
|
236
254
|
wait=wait_exponential(multiplier=1, min=4, max=10),
|
@@ -390,6 +408,283 @@ async def chat_completion_with_backoff(
|
|
390
408
|
commit_conversation_trace(messages, aggregated_response, tracer)
|
391
409
|
|
392
410
|
|
411
|
+
@retry(
|
412
|
+
retry=(
|
413
|
+
retry_if_exception_type(openai._exceptions.APITimeoutError)
|
414
|
+
| retry_if_exception_type(openai._exceptions.RateLimitError)
|
415
|
+
| retry_if_exception_type(openai._exceptions.InternalServerError)
|
416
|
+
| retry_if_exception_type(ValueError)
|
417
|
+
),
|
418
|
+
wait=wait_random_exponential(min=1, max=10),
|
419
|
+
stop=stop_after_attempt(3),
|
420
|
+
before_sleep=before_sleep_log(logger, logging.DEBUG),
|
421
|
+
reraise=True,
|
422
|
+
)
|
423
|
+
def responses_completion_with_backoff(
|
424
|
+
messages: List[ChatMessage],
|
425
|
+
model_name: str,
|
426
|
+
temperature=0.6,
|
427
|
+
openai_api_key=None,
|
428
|
+
api_base_url=None,
|
429
|
+
deepthought: bool = False,
|
430
|
+
model_kwargs: dict = {},
|
431
|
+
tracer: dict = {},
|
432
|
+
) -> ResponseWithThought:
|
433
|
+
"""
|
434
|
+
Synchronous helper using the OpenAI Responses API in streaming mode under the hood.
|
435
|
+
Aggregates streamed deltas and returns a ResponseWithThought.
|
436
|
+
"""
|
437
|
+
client_key = f"{openai_api_key}--{api_base_url}"
|
438
|
+
client = openai_clients.get(client_key)
|
439
|
+
if not client:
|
440
|
+
client = get_openai_client(openai_api_key, api_base_url)
|
441
|
+
openai_clients[client_key] = client
|
442
|
+
|
443
|
+
formatted_messages = format_message_for_api(messages, api_base_url)
|
444
|
+
# Move the first system message to Responses API instructions
|
445
|
+
instructions: Optional[str] = None
|
446
|
+
if formatted_messages and formatted_messages[0].get("role") == "system":
|
447
|
+
instructions = _extract_text_for_instructions(formatted_messages[0].get("content")) or None
|
448
|
+
formatted_messages = formatted_messages[1:]
|
449
|
+
|
450
|
+
model_kwargs = deepcopy(model_kwargs)
|
451
|
+
model_kwargs["top_p"] = model_kwargs.get("top_p", 0.95)
|
452
|
+
# Configure thinking for openai reasoning models
|
453
|
+
if is_openai_reasoning_model(model_name, api_base_url):
|
454
|
+
temperature = 1
|
455
|
+
reasoning_effort = "medium" if deepthought else "low"
|
456
|
+
model_kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"}
|
457
|
+
# Remove unsupported params for reasoning models
|
458
|
+
model_kwargs.pop("top_p", None)
|
459
|
+
model_kwargs.pop("stop", None)
|
460
|
+
|
461
|
+
read_timeout = 300 if is_local_api(api_base_url) else 60
|
462
|
+
|
463
|
+
# Stream and aggregate
|
464
|
+
model_response: OpenAIResponse = client.responses.create(
|
465
|
+
input=formatted_messages,
|
466
|
+
instructions=instructions,
|
467
|
+
model=model_name,
|
468
|
+
temperature=temperature,
|
469
|
+
timeout=httpx.Timeout(30, read=read_timeout), # type: ignore
|
470
|
+
store=False,
|
471
|
+
include=["reasoning.encrypted_content"],
|
472
|
+
**model_kwargs,
|
473
|
+
)
|
474
|
+
if not model_response or not isinstance(model_response, OpenAIResponse) or not model_response.output:
|
475
|
+
raise ValueError(f"Empty response returned by {model_name}.")
|
476
|
+
|
477
|
+
raw_content = [item.model_dump() for item in model_response.output]
|
478
|
+
aggregated_text = model_response.output_text
|
479
|
+
thoughts = ""
|
480
|
+
tool_calls: List[ToolCall] = []
|
481
|
+
for item in model_response.output:
|
482
|
+
if isinstance(item, ResponseFunctionToolCall):
|
483
|
+
tool_calls.append(ToolCall(name=item.name, args=json.loads(item.arguments), id=item.call_id))
|
484
|
+
elif isinstance(item, ResponseReasoningItem):
|
485
|
+
thoughts = "\n\n".join([summary.text for summary in item.summary])
|
486
|
+
|
487
|
+
if tool_calls:
|
488
|
+
if thoughts and aggregated_text:
|
489
|
+
# If there are tool calls, aggregate thoughts and responses into thoughts
|
490
|
+
thoughts = "\n".join([f"*{line.strip()}*" for line in thoughts.splitlines() if line.strip()])
|
491
|
+
thoughts = f"{thoughts}\n\n{aggregated_text}"
|
492
|
+
else:
|
493
|
+
thoughts = thoughts or aggregated_text
|
494
|
+
# Json dump tool calls into aggregated response
|
495
|
+
aggregated_text = json.dumps([tool_call.__dict__ for tool_call in tool_calls])
|
496
|
+
|
497
|
+
# Usage/cost tracking
|
498
|
+
input_tokens = model_response.usage.input_tokens if model_response and model_response.usage else 0
|
499
|
+
output_tokens = model_response.usage.output_tokens if model_response and model_response.usage else 0
|
500
|
+
cost = 0
|
501
|
+
cache_read_tokens = 0
|
502
|
+
if model_response and model_response.usage and model_response.usage.input_tokens_details:
|
503
|
+
cache_read_tokens = model_response.usage.input_tokens_details.cached_tokens
|
504
|
+
input_tokens -= cache_read_tokens
|
505
|
+
tracer["usage"] = get_chat_usage_metrics(
|
506
|
+
model_name, input_tokens, output_tokens, cache_read_tokens, usage=tracer.get("usage"), cost=cost
|
507
|
+
)
|
508
|
+
|
509
|
+
# Validate final aggregated text (either message or tool-calls JSON)
|
510
|
+
if is_none_or_empty(aggregated_text):
|
511
|
+
logger.warning(f"No response by {model_name}\nLast Message by {messages[-1].role}: {messages[-1].content}.")
|
512
|
+
raise ValueError(f"Empty or no response by {model_name} over Responses API. Retry if needed.")
|
513
|
+
|
514
|
+
# Trace
|
515
|
+
tracer["chat_model"] = model_name
|
516
|
+
tracer["temperature"] = temperature
|
517
|
+
if is_promptrace_enabled():
|
518
|
+
commit_conversation_trace(messages, aggregated_text, tracer)
|
519
|
+
|
520
|
+
return ResponseWithThought(text=aggregated_text, thought=thoughts, raw_content=raw_content)
|
521
|
+
|
522
|
+
|
523
|
+
@retry(
|
524
|
+
retry=(
|
525
|
+
retry_if_exception_type(openai._exceptions.APITimeoutError)
|
526
|
+
| retry_if_exception_type(openai._exceptions.RateLimitError)
|
527
|
+
| retry_if_exception_type(openai._exceptions.InternalServerError)
|
528
|
+
| retry_if_exception_type(ValueError)
|
529
|
+
),
|
530
|
+
wait=wait_exponential(multiplier=1, min=4, max=10),
|
531
|
+
stop=stop_after_attempt(3),
|
532
|
+
before_sleep=before_sleep_log(logger, logging.WARNING),
|
533
|
+
reraise=False,
|
534
|
+
)
|
535
|
+
async def responses_chat_completion_with_backoff(
|
536
|
+
messages: list[ChatMessage],
|
537
|
+
model_name: str,
|
538
|
+
temperature,
|
539
|
+
openai_api_key=None,
|
540
|
+
api_base_url=None,
|
541
|
+
deepthought=False, # Unused; parity with legacy signature
|
542
|
+
tracer: dict = {},
|
543
|
+
) -> AsyncGenerator[ResponseWithThought, None]:
|
544
|
+
"""
|
545
|
+
Async streaming helper using the OpenAI Responses API.
|
546
|
+
Yields ResponseWithThought chunks as text/think deltas arrive.
|
547
|
+
"""
|
548
|
+
client_key = f"{openai_api_key}--{api_base_url}"
|
549
|
+
client = openai_async_clients.get(client_key)
|
550
|
+
if not client:
|
551
|
+
client = get_openai_async_client(openai_api_key, api_base_url)
|
552
|
+
openai_async_clients[client_key] = client
|
553
|
+
|
554
|
+
formatted_messages = format_message_for_api(messages, api_base_url)
|
555
|
+
# Move the first system message to Responses API instructions
|
556
|
+
instructions: Optional[str] = None
|
557
|
+
if formatted_messages and formatted_messages[0].get("role") == "system":
|
558
|
+
instructions = _extract_text_for_instructions(formatted_messages[0].get("content")) or None
|
559
|
+
formatted_messages = formatted_messages[1:]
|
560
|
+
|
561
|
+
model_kwargs: dict = {}
|
562
|
+
model_kwargs["top_p"] = model_kwargs.get("top_p", 0.95)
|
563
|
+
# Configure thinking for openai reasoning models
|
564
|
+
if is_openai_reasoning_model(model_name, api_base_url):
|
565
|
+
temperature = 1
|
566
|
+
reasoning_effort = "medium" if deepthought else "low"
|
567
|
+
model_kwargs["reasoning"] = {"effort": reasoning_effort, "summary": "auto"}
|
568
|
+
# Remove unsupported params for reasoning models
|
569
|
+
model_kwargs.pop("top_p", None)
|
570
|
+
model_kwargs.pop("stop", None)
|
571
|
+
|
572
|
+
read_timeout = 300 if is_local_api(api_base_url) else 60
|
573
|
+
|
574
|
+
aggregated_text = ""
|
575
|
+
last_final: Optional[OpenAIResponse] = None
|
576
|
+
# Tool call assembly buffers
|
577
|
+
tool_calls_args: Dict[str, str] = {}
|
578
|
+
tool_calls_name: Dict[str, str] = {}
|
579
|
+
tool_call_order: List[str] = []
|
580
|
+
|
581
|
+
async with client.responses.stream(
|
582
|
+
input=formatted_messages,
|
583
|
+
instructions=instructions,
|
584
|
+
model=model_name,
|
585
|
+
temperature=temperature,
|
586
|
+
timeout=httpx.Timeout(30, read=read_timeout),
|
587
|
+
**model_kwargs,
|
588
|
+
) as stream: # type: ignore
|
589
|
+
async for event in stream: # type: ignore
|
590
|
+
et = getattr(event, "type", "")
|
591
|
+
if et == "response.output_text.delta":
|
592
|
+
delta = getattr(event, "delta", "") or getattr(event, "output_text", "")
|
593
|
+
if delta:
|
594
|
+
aggregated_text += delta
|
595
|
+
yield ResponseWithThought(text=delta)
|
596
|
+
elif et == "response.reasoning.delta":
|
597
|
+
delta = getattr(event, "delta", "")
|
598
|
+
if delta:
|
599
|
+
yield ResponseWithThought(thought=delta)
|
600
|
+
elif et == "response.tool_call.created":
|
601
|
+
item = getattr(event, "item", None)
|
602
|
+
tool_id = (
|
603
|
+
getattr(event, "id", None)
|
604
|
+
or getattr(event, "tool_call_id", None)
|
605
|
+
or (getattr(item, "id", None) if item is not None else None)
|
606
|
+
)
|
607
|
+
name = (
|
608
|
+
getattr(event, "name", None)
|
609
|
+
or (getattr(item, "name", None) if item is not None else None)
|
610
|
+
or getattr(event, "tool_name", None)
|
611
|
+
)
|
612
|
+
if tool_id:
|
613
|
+
if tool_id not in tool_calls_args:
|
614
|
+
tool_calls_args[tool_id] = ""
|
615
|
+
tool_call_order.append(tool_id)
|
616
|
+
if name:
|
617
|
+
tool_calls_name[tool_id] = name
|
618
|
+
elif et == "response.tool_call.delta":
|
619
|
+
tool_id = getattr(event, "id", None) or getattr(event, "tool_call_id", None)
|
620
|
+
delta = getattr(event, "delta", None)
|
621
|
+
if hasattr(delta, "arguments"):
|
622
|
+
arg_delta = getattr(delta, "arguments", "")
|
623
|
+
else:
|
624
|
+
arg_delta = delta if isinstance(delta, str) else getattr(event, "arguments", "")
|
625
|
+
if tool_id and arg_delta:
|
626
|
+
tool_calls_args[tool_id] = tool_calls_args.get(tool_id, "") + arg_delta
|
627
|
+
if tool_id not in tool_call_order:
|
628
|
+
tool_call_order.append(tool_id)
|
629
|
+
elif et == "response.tool_call.completed":
|
630
|
+
item = getattr(event, "item", None)
|
631
|
+
tool_id = (
|
632
|
+
getattr(event, "id", None)
|
633
|
+
or getattr(event, "tool_call_id", None)
|
634
|
+
or (getattr(item, "id", None) if item is not None else None)
|
635
|
+
)
|
636
|
+
args_final = None
|
637
|
+
if item is not None:
|
638
|
+
args_final = getattr(item, "arguments", None) or getattr(item, "args", None)
|
639
|
+
if tool_id and args_final:
|
640
|
+
tool_calls_args[tool_id] = args_final if isinstance(args_final, str) else json.dumps(args_final)
|
641
|
+
if tool_id not in tool_call_order:
|
642
|
+
tool_call_order.append(tool_id)
|
643
|
+
# ignore other events for now
|
644
|
+
last_final = await stream.get_final_response()
|
645
|
+
|
646
|
+
# Usage/cost tracking after stream ends
|
647
|
+
input_tokens = last_final.usage.input_tokens if last_final and last_final.usage else 0
|
648
|
+
output_tokens = last_final.usage.output_tokens if last_final and last_final.usage else 0
|
649
|
+
cost = 0
|
650
|
+
tracer["usage"] = get_chat_usage_metrics(
|
651
|
+
model_name, input_tokens, output_tokens, usage=tracer.get("usage"), cost=cost
|
652
|
+
)
|
653
|
+
|
654
|
+
# If there are tool calls, package them into aggregated text for tracing parity
|
655
|
+
if tool_call_order:
|
656
|
+
packaged_tool_calls: List[ToolCall] = []
|
657
|
+
for tool_id in tool_call_order:
|
658
|
+
name = tool_calls_name.get(tool_id) or ""
|
659
|
+
args_str = tool_calls_args.get(tool_id, "")
|
660
|
+
try:
|
661
|
+
args = json.loads(args_str) if isinstance(args_str, str) else args_str
|
662
|
+
except Exception:
|
663
|
+
logger.warning(f"Failed to parse tool call arguments for {tool_id}: {args_str}")
|
664
|
+
args = {}
|
665
|
+
packaged_tool_calls.append(ToolCall(name=name, args=args, id=tool_id))
|
666
|
+
# Move any text into trace thought
|
667
|
+
tracer_text = aggregated_text
|
668
|
+
aggregated_text = json.dumps([tc.__dict__ for tc in packaged_tool_calls])
|
669
|
+
# Save for trace below
|
670
|
+
if tracer_text:
|
671
|
+
tracer.setdefault("_responses_stream_text", tracer_text)
|
672
|
+
|
673
|
+
if is_none_or_empty(aggregated_text):
|
674
|
+
logger.warning(f"No response by {model_name}\nLast Message by {messages[-1].role}: {messages[-1].content}.")
|
675
|
+
raise ValueError(f"Empty or no response by {model_name} over Responses API. Retry if needed.")
|
676
|
+
|
677
|
+
tracer["chat_model"] = model_name
|
678
|
+
tracer["temperature"] = temperature
|
679
|
+
if is_promptrace_enabled():
|
680
|
+
# If tool-calls were present, include any streamed text in the trace thought
|
681
|
+
trace_payload = aggregated_text
|
682
|
+
if tracer.get("_responses_stream_text"):
|
683
|
+
thoughts = tracer.pop("_responses_stream_text")
|
684
|
+
trace_payload = thoughts
|
685
|
+
commit_conversation_trace(messages, trace_payload, tracer)
|
686
|
+
|
687
|
+
|
393
688
|
def get_structured_output_support(model_name: str, api_base_url: str = None) -> StructuredOutputSupport:
|
394
689
|
if model_name.startswith("deepseek-reasoner"):
|
395
690
|
return StructuredOutputSupport.NONE
|
@@ -412,6 +707,12 @@ def format_message_for_api(raw_messages: List[ChatMessage], api_base_url: str) -
|
|
412
707
|
# Handle tool call and tool result message types
|
413
708
|
message_type = message.additional_kwargs.get("message_type")
|
414
709
|
if message_type == "tool_call":
|
710
|
+
if is_openai_api(api_base_url):
|
711
|
+
for part in message.content:
|
712
|
+
if "status" in part:
|
713
|
+
part.pop("status") # Drop unsupported tool call status field
|
714
|
+
formatted_messages.extend(message.content)
|
715
|
+
continue
|
415
716
|
# Convert tool_call to OpenAI function call format
|
416
717
|
content = []
|
417
718
|
for part in message.content:
|
@@ -450,14 +751,23 @@ def format_message_for_api(raw_messages: List[ChatMessage], api_base_url: str) -
|
|
450
751
|
if not tool_call_id:
|
451
752
|
logger.warning(f"Dropping tool result without valid tool_call_id: {part.get('name')}")
|
452
753
|
continue
|
453
|
-
|
454
|
-
|
455
|
-
|
456
|
-
|
457
|
-
|
458
|
-
|
459
|
-
|
460
|
-
|
754
|
+
if is_openai_api(api_base_url):
|
755
|
+
formatted_messages.append(
|
756
|
+
{
|
757
|
+
"type": "function_call_output",
|
758
|
+
"call_id": tool_call_id,
|
759
|
+
"output": part.get("content") or "No output",
|
760
|
+
}
|
761
|
+
)
|
762
|
+
else:
|
763
|
+
formatted_messages.append(
|
764
|
+
{
|
765
|
+
"role": "tool",
|
766
|
+
"tool_call_id": tool_call_id,
|
767
|
+
"name": part.get("name"),
|
768
|
+
"content": part.get("content") or "No output",
|
769
|
+
}
|
770
|
+
)
|
461
771
|
continue
|
462
772
|
if isinstance(message.content, list) and not is_openai_api(api_base_url):
|
463
773
|
assistant_texts = []
|
@@ -489,6 +799,11 @@ def format_message_for_api(raw_messages: List[ChatMessage], api_base_url: str) -
|
|
489
799
|
message.content.remove(part)
|
490
800
|
elif part["type"] == "image_url" and not part.get("image_url"):
|
491
801
|
message.content.remove(part)
|
802
|
+
# OpenAI models use the Responses API which uses slightly different content types
|
803
|
+
if part["type"] == "text":
|
804
|
+
part["type"] = "output_text" if message.role == "assistant" else "input_text"
|
805
|
+
if part["type"] == "image":
|
806
|
+
part["type"] = "output_image" if message.role == "assistant" else "input_image"
|
492
807
|
# If no valid content parts left, remove the message
|
493
808
|
if is_none_or_empty(message.content):
|
494
809
|
messages.remove(message)
|
@@ -513,7 +828,9 @@ def is_openai_reasoning_model(model_name: str, api_base_url: str = None) -> bool
|
|
513
828
|
"""
|
514
829
|
Check if the model is an OpenAI reasoning model
|
515
830
|
"""
|
516
|
-
return
|
831
|
+
return is_openai_api(api_base_url) and (
|
832
|
+
model_name.lower().startswith("o") or model_name.lower().startswith("gpt-5")
|
833
|
+
)
|
517
834
|
|
518
835
|
|
519
836
|
def is_non_streaming_model(model_name: str, api_base_url: str = None) -> bool:
|
@@ -609,6 +926,9 @@ async def astream_thought_processor(
|
|
609
926
|
if not chunk_data.get("object") or chunk_data.get("object") != "chat.completion.chunk":
|
610
927
|
logger.warning(f"Skipping invalid chunk with object field: {chunk_data.get('object', 'missing')}")
|
611
928
|
continue
|
929
|
+
# Handle unsupported service tiers like "on_demand" by Groq
|
930
|
+
if chunk.service_tier and chunk.service_tier == "on_demand":
|
931
|
+
chunk_data["service_tier"] = "auto"
|
612
932
|
|
613
933
|
tchunk = ChatCompletionWithThoughtsChunk.model_validate(chunk_data)
|
614
934
|
|
@@ -850,20 +1170,32 @@ def add_qwen_no_think_tag(formatted_messages: List[dict]) -> None:
|
|
850
1170
|
break
|
851
1171
|
|
852
1172
|
|
853
|
-
def to_openai_tools(tools: List[ToolDefinition]) -> List[Dict] | None:
|
1173
|
+
def to_openai_tools(tools: List[ToolDefinition], use_responses_api: bool) -> List[Dict] | None:
|
854
1174
|
"Transform tool definitions from standard format to OpenAI format."
|
855
|
-
|
856
|
-
|
857
|
-
|
858
|
-
|
1175
|
+
if use_responses_api:
|
1176
|
+
openai_tools = [
|
1177
|
+
{
|
1178
|
+
"type": "function",
|
859
1179
|
"name": tool.name,
|
860
1180
|
"description": tool.description,
|
861
1181
|
"parameters": clean_response_schema(tool.schema),
|
862
1182
|
"strict": True,
|
863
|
-
}
|
864
|
-
|
865
|
-
|
866
|
-
|
1183
|
+
}
|
1184
|
+
for tool in tools
|
1185
|
+
]
|
1186
|
+
else:
|
1187
|
+
openai_tools = [
|
1188
|
+
{
|
1189
|
+
"type": "function",
|
1190
|
+
"function": {
|
1191
|
+
"name": tool.name,
|
1192
|
+
"description": tool.description,
|
1193
|
+
"parameters": clean_response_schema(tool.schema),
|
1194
|
+
"strict": True,
|
1195
|
+
},
|
1196
|
+
}
|
1197
|
+
for tool in tools
|
1198
|
+
]
|
867
1199
|
|
868
1200
|
return openai_tools or None
|
869
1201
|
|
@@ -519,12 +519,13 @@ Q: {query}
|
|
519
519
|
|
520
520
|
extract_questions_system_prompt = PromptTemplate.from_template(
|
521
521
|
"""
|
522
|
-
You are Khoj, an extremely smart and helpful document search assistant with only the ability to retrieve information from the user's notes.
|
523
|
-
Construct search queries to retrieve relevant information to answer the user's question.
|
522
|
+
You are Khoj, an extremely smart and helpful document search assistant with only the ability to use natural language semantic search to retrieve information from the user's notes.
|
523
|
+
Construct upto {max_queries} search queries to retrieve relevant information to answer the user's question.
|
524
524
|
- You will be provided past questions(User), search queries(Assistant) and answers(A) for context.
|
525
|
-
-
|
526
|
-
- Break your search
|
527
|
-
- Add date filters to your search queries
|
525
|
+
- You can use context from previous questions and answers to improve your search queries.
|
526
|
+
- Break down your search into multiple search queries from a diverse set of lenses to retrieve all related documents. E.g who, what, where, when, why, how.
|
527
|
+
- Add date filters to your search queries when required to retrieve the relevant information. This is the only structured query filter you can use.
|
528
|
+
- Output 1 concept per query. Do not use boolean operators (OR/AND) to combine queries. They do not work and degrade search quality.
|
528
529
|
- When asked a meta, vague or random questions, search for a variety of broad topics to answer the user's question.
|
529
530
|
{personality_context}
|
530
531
|
What searches will you perform to answer the users question? Respond with a JSON object with the key "queries" mapping to a list of searches you would perform on the user's knowledge base. Just return the queries and nothing else.
|
@@ -535,22 +536,27 @@ User's Location: {location}
|
|
535
536
|
|
536
537
|
Here are some examples of how you can construct search queries to answer the user's question:
|
537
538
|
|
539
|
+
Illustrate - Using diverse perspectives to retrieve all relevant documents
|
538
540
|
User: How was my trip to Cambodia?
|
539
541
|
Assistant: {{"queries": ["How was my trip to Cambodia?", "Angkor Wat temple visit", "Flight to Phnom Penh", "Expenses in Cambodia", "Stay in Cambodia"]}}
|
540
542
|
A: The trip was amazing. You went to the Angkor Wat temple and it was beautiful.
|
541
543
|
|
544
|
+
Illustrate - Combining date filters with natural language queries to retrieve documents in relevant date range
|
542
545
|
User: What national parks did I go to last year?
|
543
546
|
Assistant: {{"queries": ["National park I visited in {last_new_year} dt>='{last_new_year_date}' dt<'{current_new_year_date}'"]}}
|
544
547
|
A: You visited the Grand Canyon and Yellowstone National Park in {last_new_year}.
|
545
548
|
|
549
|
+
Illustrate - Using broad topics to answer meta or vague questions
|
546
550
|
User: How can you help me?
|
547
551
|
Assistant: {{"queries": ["Social relationships", "Physical and mental health", "Education and career", "Personal life goals and habits"]}}
|
548
552
|
A: I can help you live healthier and happier across work and personal life
|
549
553
|
|
554
|
+
Illustrate - Combining location and date in natural language queries with date filters to retrieve relevant documents
|
550
555
|
User: Who all did I meet here yesterday?
|
551
556
|
Assistant: {{"queries": ["Met in {location} on {yesterday_date} dt>='{yesterday_date}' dt<'{current_date}'"]}}
|
552
557
|
A: Yesterday's note mentions your visit to your local beach with Ram and Shyam.
|
553
558
|
|
559
|
+
Illustrate - Combining broad, diverse topics with date filters to answer meta or vague questions
|
554
560
|
User: Share some random, interesting experiences from this month
|
555
561
|
Assistant: {{"queries": ["Exciting travel adventures from {current_month}", "Fun social events dt>='{current_month}-01' dt<'{current_date}'", "Intense emotional experiences in {current_month}"]}}
|
556
562
|
A: You had a great time at the local beach with your friends, attended a music concert and had a deep conversation with your friend, Khalid.
|
@@ -635,16 +641,17 @@ Here's some additional context about you:
|
|
635
641
|
|
636
642
|
plan_function_execution = PromptTemplate.from_template(
|
637
643
|
"""
|
638
|
-
You are Khoj, a smart, creative and meticulous researcher.
|
644
|
+
You are Khoj, a smart, creative and meticulous researcher.
|
639
645
|
Create a multi-step plan and intelligently iterate on the plan to complete the task.
|
646
|
+
Use the help of the provided tool AIs to accomplish the task assigned to you.
|
640
647
|
{personality_context}
|
641
648
|
|
642
649
|
# Instructions
|
643
|
-
-
|
644
|
-
- Break down your research process into independent, self-contained steps that can be executed sequentially using the available tool AIs to
|
645
|
-
- Always ask a new query that was not asked to the tool AI in a previous iteration. Build on the results of the previous iterations.
|
650
|
+
- Make detailed, self-contained requests to the tool AIs, one tool AI at a time, to gather information, perform actions etc.
|
651
|
+
- Break down your research process into independent, self-contained steps that can be executed sequentially using the available tool AIs to accomplish the user assigned task.
|
646
652
|
- Ensure that all required context is passed to the tool AIs for successful execution. Include any relevant stuff that has previously been attempted. They only know the context provided in your query.
|
647
653
|
- Think step by step to come up with creative strategies when the previous iteration did not yield useful results.
|
654
|
+
- Do not ask the user to confirm or clarify assumptions for information gathering tasks and non-destructive actions, as you can always adjust later — decide what the most reasonable assumption is, proceed with it, and document it for the user's reference after you finish acting.
|
648
655
|
- You are allowed upto {max_iterations} iterations to use the help of the provided tool AIs to accomplish the task assigned to you. Only stop when you have completed the task.
|
649
656
|
|
650
657
|
# Examples
|
@@ -68,6 +68,9 @@ model_to_prompt_size = {
|
|
68
68
|
"o3": 60000,
|
69
69
|
"o3-pro": 30000,
|
70
70
|
"o4-mini": 90000,
|
71
|
+
"gpt-5-2025-08-07": 120000,
|
72
|
+
"gpt-5-mini-2025-08-07": 120000,
|
73
|
+
"gpt-5-nano-2025-08-07": 120000,
|
71
74
|
# Google Models
|
72
75
|
"gemini-2.5-flash": 120000,
|
73
76
|
"gemini-2.5-pro": 60000,
|
@@ -328,7 +331,7 @@ def construct_tool_chat_history(
|
|
328
331
|
ConversationCommand.ReadWebpage: (
|
329
332
|
lambda iteration: list(iteration.onlineContext.keys()) if iteration.onlineContext else []
|
330
333
|
),
|
331
|
-
ConversationCommand.
|
334
|
+
ConversationCommand.PythonCoder: (
|
332
335
|
lambda iteration: list(iteration.codeContext.keys()) if iteration.codeContext else []
|
333
336
|
),
|
334
337
|
}
|