Module 1 Graded Assignment Error in last 2 Notebook Cells

Got error similar to below in the last couple of cells but was able to finish the graded assignment as the cells with the actual assignments worked. Unfortunately just did not enjoy the Ahaa moment of playing with different queries . 



####### ERROR OUTPUT MESSAGE BELOW ####### 


---------------------------------------------------------------------------
BadRequestError                           Traceback (most recent call last)
Cell In[19], line 1
----> 1 print(llm_call(query, use_rag = True))

Cell In[17], line 19, in llm_call(query, top_k, use_rag, prompt)
     16 prompt = generate_final_prompt(query, top_k, use_rag, prompt)
     18 # Call the LLM
---> 19 generated_response = generate_with_single_input(prompt)
     21 # Get the content
     22 generated_message = generated_response['content']

File ~/work/utils.py:104, in generate_with_single_input(prompt, role, top_p, temperature, max_tokens, model, together_api_key, **kwargs)
    102         payload['temperature'] = None
    103     client = Together(api_key =  together_api_key)
--> 104     json_dict = client.chat.completions.create(**payload).model_dump()
    105     json_dict['choices'][-1]['message']['role'] = json_dict['choices'][-1]['message']['role'].lower()
    106 try:

File /usr/local/lib/python3.12/site-packages/together/_utils/_utils.py:282, in required_args.<locals>.inner.<locals>.wrapper(*args, **kwargs)
    280             msg = f"Missing required argument: {quote(missing[0])}"
    281     raise TypeError(msg)
--> 282 return func(*args, **kwargs)

File /usr/local/lib/python3.12/site-packages/together/resources/chat/completions.py:562, in CompletionsResource.create(self, messages, model, chat_template_kwargs, compliance, context_length_exceeded_behavior, echo, frequency_penalty, function_call, logit_bias, logprobs, max_tokens, min_p, n, presence_penalty, reasoning, reasoning_effort, repetition_penalty, response_format, safety_model, seed, stop, stream, temperature, tool_choice, tools, top_k, top_p, extra_headers, extra_query, extra_body, timeout)
    515 @required_args(["messages", "model"], ["messages", "model", "stream"])
    516 def create(
    517     self,
   (...)    560     timeout: float | httpx.Timeout | None | NotGiven = not_given,
    561 ) -> ChatCompletion | Stream[ChatCompletionChunk]:
--> 562     return self._post(
    563         "/chat/completions",
    564         body=maybe_transform(
    565             {
    566                 "messages": messages,
    567                 "model": model,
    568                 "chat_template_kwargs": chat_template_kwargs,
    569                 "compliance": compliance,
    570                 "context_length_exceeded_behavior": context_length_exceeded_behavior,
    571                 "echo": echo,
    572                 "frequency_penalty": frequency_penalty,
    573                 "function_call": function_call,
    574                 "logit_bias": logit_bias,
    575                 "logprobs": logprobs,
    576                 "max_tokens": max_tokens,
    577                 "min_p": min_p,
    578                 "n": n,
    579                 "presence_penalty": presence_penalty,
    580                 "reasoning": reasoning,
    581                 "reasoning_effort": reasoning_effort,
    582                 "repetition_penalty": repetition_penalty,
    583                 "response_format": response_format,
    584                 "safety_model": safety_model,
    585                 "seed": seed,
    586                 "stop": stop,
    587                 "stream": stream,
    588                 "temperature": temperature,
    589                 "tool_choice": tool_choice,
    590                 "tools": tools,
    591                 "top_k": top_k,
    592                 "top_p": top_p,
    593             },
    594             completion_create_params.CompletionCreateParamsStreaming
    595             if stream
    596             else completion_create_params.CompletionCreateParamsNonStreaming,
    597         ),
    598         options=make_request_options(
    599             extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
    600         ),
    601         cast_to=ChatCompletion,
    602         stream=stream or False,
    603         stream_cls=Stream[ChatCompletionChunk],
    604     )

File /usr/local/lib/python3.12/site-packages/together/_base_client.py:1280, in SyncAPIClient.post(self, path, cast_to, body, content, options, files, stream, stream_cls)
   1271     warnings.warn(
   1272         "Passing raw bytes as `body` is deprecated and will be removed in a future version. "
   1273         "Please pass raw bytes via the `content` parameter instead.",
   1274         DeprecationWarning,
   1275         stacklevel=2,
   1276     )
   1277 opts = FinalRequestOptions.construct(
   1278     method="post", url=path, json_data=body, content=content, files=to_httpx_files(files), **options
   1279 )
-> 1280 return cast(ResponseT, self.request(cast_to, opts, stream=stream, stream_cls=stream_cls))

File /usr/local/lib/python3.12/site-packages/together/_base_client.py:1067, in SyncAPIClient.request(self, cast_to, options, stream, stream_cls)
   1064             err.response.read()
   1066         log.debug("Re-raising status error")
-> 1067         raise self._make_status_error_from_response(err.response) from None
   1069     break
   1071 assert response is not None, "could not resolve response (should never happen)"

BadRequestError: Error code: 400 - {'error': {'type': 'invalid_request_error', 'code': 'process_messages_failed', 'message': 'Failed to apply chat template: Failed to render template: invalid operation: No user query found in messages. (in chat:79)', 'param': None}}

hi @Adithya_Rajaraman

kindly follow these steps

  1. clear out your notebook’s kernel output.
  2. Reconnect the kernel.
  3. Now re-run each cell from beginning till end individually successfully.
  4. Click on the save emicon :floppy_disk: on the left upper corner.
  5. Finally submit.

Let me know if issue still persist, we might have to review your codes then.

Regards
Dr. Deepti

Hi @Adithya_Rajaraman,

This is a known bug in utils.py (restarting the kernel alone will not fix it), and you can patch it locally to play with different queries in those last two demo cells.

generate_with_single_input() in utils.py defaults to role='assistant', whereas the chat model hosted on Together AI strictly requires at least one message with role='user' to render its chat template. That mismatch triggers the 400 BadRequestError: No user query found in messages error.

Since the demo cells in the notebook are frozen ("editable": false), use either workaround below (also tracked in this earlier thread):

Option 1: Patch utils.py so the original demo cells work

  1. Click File -> Open... in the top Jupyter menu and open utils.py.
  2. In def generate_with_single_input(...), change role: str = 'assistant' to role: str = 'user' and save the file.
  3. Back in the notebook, run Kernel -> Restart & Clear Output and run the cells again.

Option 2: Test in a new scratch cell
Insert a new cell at the bottom (select the last cell and press B) and pass role="user" explicitly:

def llm_call_fixed(query, top_k=5, use_rag=True, prompt=None):
    prompt = generate_final_prompt(query, top_k, use_rag, prompt)
    return generate_with_single_input(prompt, role="user")["content"]

print(llm_call_fixed(query, use_rag=True))

Since your grade is already recorded, you do not need to resubmit after experimenting (if you ever do resubmit, delete any extra scratch cells first).

@Mubsi

is this the same error, you mentioned that has been fixed??

So the learner has to just refresh and get fresh copy of notebook by clicking on restore original version, to get the updated corrected notebook right??

regards
dr. deepti

This should be fixed now.

Yes