Project 3: docchat
Due: Wednesday, November 11 at 11:59pm · Worth: 41 points (+2 extra credit; maximum 43/41)
You’ll extend your command-line chatbot so it can answer questions about local files. The model can request a tool, and your Python code reads the file or searches its contents and sends the result back. You’ll also test that the model gets the right result. In the next project you’ll add tools for editing code.
Start
Continue in the docchat repository from the More Project Setup lab. Keep its chat.py, Chat class, tests, and installable chat command. Activate its Python environment, then reinstall from the repository root:
python -m pip install -e . -r requirements.txtDownload tool_roundtrip.py and run python tool_roundtrip.py in the folder where you saved it. This small example runs a word_count tool using a simulated model request, without an API key. Read it to see how a tool name and JSON arguments become a Python function call, and how the result gets paired with the request’s tool_call_id. Keep this practice file outside your submitted repository.
Tools
Put each tool in its own file under tools/, with a function of the same name. Write doctests as you implement them.
| File | Required behavior |
|---|---|
tools/calculate.py |
Evaluate arithmetic expressions containing numbers, spaces, parentheses, and supported arithmetic operators. Reject names and function calls. |
tools/ls.py |
List the current folder with no argument, or the supplied folder with one argument. Return names in sorted order. |
tools/cat.py |
Return the complete contents of a text file. Return an explanation for a missing file or unreadable text instead of crashing. |
tools/grep.py |
Take a regex and a path, which may contain globs. Return every matching line from every matching file. Return no output when nothing matches. |
glob.glob finds matching paths, and re.search checks each line against a regex. For grep, start by searching for a word such as TODO, then try patterns from the regex reading. For calculate, the Groq tool-calling guide has an example using eval. Validate the expression before evaluating it, since unrestricted eval can execute other Python code.
All file tools must check paths with a shared is_path_safe(path) helper before accessing them. Allow relative paths inside the working folder. Reject absolute paths and paths containing a .. component, such as ../notes.txt or docs/../../notes.txt.
Conversation
Every tool must work in two ways:
- Manual commands:
/ls toolsrunslsdirectly, prints its result, and saves that result in the conversation for the next question. Support/calculate,/ls,/cat, and/grep. These commands must work without an API key or model request. - Automatic calls: an ordinary question goes to the model along with descriptions of the available tools. When the model requests a tool, run it and return its result to the model. Continue until the model gives an answer, then save and print that answer.
For each automatic tool call, save the assistant message that requested it. Next, append the tool’s result with the same tool_call_id. Keep every request and result in the history you send back to the model. A single assistant message can request several tools, and the model can ask for more after seeing the results.
Use the synchronous Groq/OpenAI chat-completions interface without streaming. Send messages and tools to client.chat.completions.create, then get the assistant’s full reply from choices[0].message. Its tool_calls field tells you whether to run any tools. To append this reply to messages, use message.model_dump(exclude_none=True). This converts the reply object to a dictionary and keeps its tool requests. Each tool’s argument names in the schema must match the Python function’s parameter names. See the Groq guide for the API format.
Create the client when making a model request, so importing chat.py or running a manual command does not require an API key. Test both routes with a fake model response before trying a live conversation.
Tests and Installation
Give every Python file, function, and class a short docstring explaining its purpose. Functions and classes also need doctests showing their behavior. Methods may use the examples in their class docstring. Keep the main program in chat.py and each tool in its own file.
Your doctests must cover every executable line in the four required tool files. Include successful reads, missing files, invalid text encodings, rejected paths, and empty searches. Create test files in temporary directories so your tests do not depend on your own documents. For conversation tests, patch the model request and check that the next request contains the tool result with its matching ID. Check manual commands too, including whether their results reach the next model request.
Check that your doctests fail when a tool returns the wrong result. The grader tries these replacements:
| Tool | Replacement return value |
|---|---|
calculate |
'0' |
ls |
'missing.txt' |
cat |
'wrong contents' |
grep |
'no matches' |
Temporarily replace one function’s body, after its docstring, with the corresponding return statement. Run python -m doctest -v tools/NAME.py and check that a test fails, then restore your implementation. Your original doctests must pass before each replacement is tried.
To install the tools alongside chat.py, create an empty tools/__init__.py and update the existing table in pyproject.toml:
[tool.setuptools]
py-modules = ["chat"]
packages = ["tools"]Keep the existing package metadata, dependencies, and chat entry point. Use package imports such as from tools.cat import cat. Reinstall, then launch chat from a different folder and try /ls .. End input with Ctrl+D on macOS/Linux or Git Bash, or Ctrl+Z then Enter in PowerShell. The installed command must find its tools and exit cleanly.
Run these checks from the repository root:
python -m pip install -e . -r requirements.txt
python -m pip install pytest coverage flake8
python -m pytest --doctest-modules tools chat.py
python -m coverage run --include='tools/calculate.py,tools/ls.py,tools/cat.py,tools/grep.py' -m pytest --doctest-modules tools
python -m coverage report -m
python -m flake8 chat.py tools --ignore=E501The coverage requirement applies only to those four tool files. Use a raw docstring (r'''...''') when doctests contain escapes such as \n. Keep live model replies out of exact-output tests.
Try Your Previous Projects
Add your webpage, Markdown compiler, and eBay scraper as Git submodules under test_projects. A submodule records another repository’s location and version inside yours. From the docchat repository root, run these commands with your actual username and repository names:
git submodule add https://github.com/YOUR_USERNAME/lab-homepage.git test_projects/lab-homepage
git submodule add https://github.com/YOUR_USERNAME/markdown-compiler.git test_projects/markdown-compiler
git submodule add https://github.com/YOUR_USERNAME/ebay-scraper.git test_projects/ebay-scraperCommit .gitmodules and the three submodule entries. After cloning on another computer, git submodule update --init --recursive downloads their files.
Give your README a title, a short description, and one recorded conversation for each project. Start each code block from the docchat root, using the exact path from .gitmodules:
$ cd test_projects/markdown-compiler
$ chat
chat> /ls .
Continue with the actual listing, a question about that project, and the answer you received. Add a sentence explaining what you learned. Repeat for the other two projects.
Grading
The base project is worth 41 points, graded automatically:
-
Setup and an installed
chatcommand that includes its tools, runs/ls .offline from another folder, and exits on end-of-input. -
calculate,ls,cat, andgrep(3 points each). -
Automatic tool calls and manual commands, including conversation history.
-
Shared path checks used by every file tool.
-
Docstrings, doctest examples, and file layout.
-
Doctests detect the four incorrect replacements (0.25 points each).
-
100% doctest coverage on the four required tool files.
-
Three previous projects declared as submodules.
-
README sessions and repository hygiene. Keep
.env, hard-coded credentials,.DS_Store,.coverage, and__pycache__out of the submission.
The grader uses temporary files and fake model responses, with no API calls. It checks the README’s paths and commands, but does not grade the wording of model replies or fetch the submodules. The grading environment includes groq, openai, python-dotenv, coverage, flake8, PyYAML, and the standard library. Keep additional dependencies for extensions out of the base program’s imports and execution path.
Extra Credit
Choose from the options below for up to 2 extra-credit points, for a maximum of 43/41. Completing more options does not raise the cap.
This cap applies to the next offering of the project. For the current Gradescope assignment, use the extra-credit rules posted there.
Extra credit is graded from your code, tests, and a short recorded demonstration. For each option, include a test of normal behavior and one failure or edge case. Mock external services in tests, and show the real feature working in the recording.
-
chat "question"answers and exits without opening the interactive prompt. Demonstrate a question that requires a file tool. Test that the full question reaches the model and the final answer is printed. -
Choose between Groq and at least one other provider with
--provider. Both must support the file tools. Demonstrate the same document question with each, and test provider selection and a missing-key error. A second model on the same provider does not count. -
Add
/compactto summarize and shorten the conversation while retaining information needed for follow-up questions. Show the history before and after compaction, then ask a question that depends on an earlier turn. Test replacement of history and recovery when summarization fails. -
Complete slash-command names and file or folder arguments. Demonstrate an ambiguous prefix and a nested path. Test the completion candidates, including a prefix with no matches.
-
Generate and play audio for the assistant’s actual reply. Demonstrate a document question answered aloud. Test that the reply reaches speech generation and that an audio failure leaves the text answer available.
-
Record a question from the microphone, transcribe it, and send it through the existing chat and tool loop. Give the user a way to start and stop recording. Demonstrate a spoken document question, and test that an empty recording does not send a chat request.
-
Install and run your assistant as an Android or iOS app on a device or emulator. It must open a document folder available to the app and answer questions using its file tools. Include build and launch instructions, a recording of document selection and a conversation, and tests of document access and message handling. Opening the desktop program through a remote terminal does not count.
One recording may demonstrate several features. Put the selected features, test commands, and recording links in an Extra credit section of your README. Explain how to configure any extra dependencies or credentials without including keys. Tests may use mocks, but a mocked demonstration does not establish that the feature works.
Submit
Commit and sync your source, tests, requirements.txt, pyproject.toml, .gitmodules, submodule entries, and README. Submit the repository and branch through Gradescope’s GitHub option. The autograder reports the base score out of 41. Extra credit is reviewed separately and added to that score. No extra-credit submission.toml is needed. The course’s cumulative late policy applies.
FAQs
I appended a tool result. Why does the grader say the tool request is missing?
Save both messages: first the assistant’s request, then your tool’s result. If completion is the API response, append completion.choices[0].message.model_dump(exclude_none=True) to self.messages before running the requested tools. Keep that message even when its content is None, because the request is in tool_calls. Each result needs the matching request’s tool_call_id.
How do I patch the model to return several different replies?
Pass side_effect=[first_reply, second_reply] to patch.object for the client’s create method. Each call returns the next object in the list. For a tool conversation, the first object should request a tool and the second should contain the answer. Use the response objects shown in the LLM reading, and add another response for each additional model request your test expects.
Why does /ls ask for an API key?
Your client may be created during import or before you check for a slash command. Create it inside the function that sends a model request. Manual tools should run directly and save their results for the next ordinary chat message.
Why does a mock’s first call seem to contain messages added later?
Mocks record references to arguments. If you pass self.messages and then append to that same list, inspecting the recorded argument later shows the changed list. In the mock’s side_effect function, save a copy.deepcopy of the messages when each request arrives. That lets you check the history the model actually received on each turn.