Forge
Skip to main content
Scheduled maintenance Nov 24, 6:00–7:30 PM PST (Nov 25, 2:00–3:30 AM UTC). Expect ~30 minutes of delayed run history and metrics, and possible new run failures.

Getting started with Kimi 2.7 on CoreWeave Inference (Serverless)

Explore Kimi 2.7 through progressively more complex software engineering tasks while using Weave to trace, analyze, and evaluate every step.
Last updated: October 24, 2026

Most getting-started guides end after the first successful API call. You send a prompt, get a response, and move on. That doesn't tell you much about how a model performs on real engineering tasks.
Kimi 2.7 Code is Moonshot AI's latest coding-focused model, built for code generation, repository-scale reasoning, debugging, refactoring, and agent workflows. Compared to Kimi 2.6, it delivers stronger coding performance, improved agent capabilities, and better reasoning efficiency. According to Moonshot AI, Kimi 2.7 reduces thinking-token usage by roughly 30% compared to Kimi 2.6, which can lower both latency and cost in longer development workflows.
Rather than focusing on benchmark scores, this guide evaluates Kimi 2.7 the way a software team would. We'll start with a simple coding task, move to executable code generation, debug a multi-file project, test agentic repository workflows, and refactor an existing codebase. Each step increases in complexity and provides a different view of the model's capabilities.
Every request runs through CoreWeave Inference (Serverless) and is automatically captured by Weave. That gives us traces, token usage, latency metrics, and evaluation results for every task. Instead of relying on a few prompt examples, we'll use those traces to understand how the model behaves and where it performs best.
By the end, you'll have a working Kimi 2.7 setup, a set of software engineering test cases, and a repeatable evaluation workflow that can also be used to compare Kimi 2.7 against Kimi 2.6.

How CoreWeave Inference (Serverless) and Weave fit into the workflow

Before diving into the code, it helps to understand the role of the two W&B products used throughout this guide.
CoreWeave Inference (Serverless) provides access to Kimi 2.7 through an OpenAI-compatible API. You can use the same client, request format, and workflow you would use with any OpenAI-compatible model endpoint, while W&B handles the model serving layer.
Weave sits alongside the application and records every interaction with the model. Each request becomes a trace that includes the prompt, response, latency, token usage, and other metadata. Those traces make it easier to understand model behavior, investigate failures, and evaluate changes over time.
We'll use both throughout this tutorial:
  • CoreWeave Inference (Serverless) to run Kimi 2.7
  • Weave Traces to inspect model behavior

Throughout the tutorial, every request is sent through CoreWeave Inference (Serverless) and automatically traced with Weave. As the examples progress from simple code generation to repository debugging, agentic workflows, refactoring, and a small evaluation suite, the value of tracing becomes increasingly apparent. While a utility-function request is easy to inspect manually, repository-level debugging and refactoring involve multiple files, tool calls, and longer interactions. Weave provides visibility into those workflows by capturing prompts, responses, latency, token usage, and tool execution, turning one-off prompt testing into a measurable evaluation workflow.

Step 1: Connect Kimi 2.7 to CoreWeave Inference (Serverless)

Before testing Kimi 2.7, create a clean Python environment and install the packages used throughout this tutorial.

Create a virtual environment

py -3.11 -m venv .venv # Activate the environment # macOS/Linux source .venv/bin/activate # Windows PowerShell .\.venv\Scripts\Activate.ps1

Install dependencies

python -m pip install --upgrade pip pip install openai weave wandb pytest ipykernel python-dotenv python -m ipykernel install --user --name kimi-2-7-guide --display-name "Python 3.11 (Kimi 2.7 Guide)"

Configure credentials

Create a .env file in the project root:


WANDB_API_KEY=YOUR_WANDB_API_KEY WANDB_PROJECT=kimi-2.7-guide

Step 2: Generate a simple utility function

With the environment ready, let's start with a small coding task.
We'll ask Kimi 2.7 to generate a feature-flag parser that converts configuration strings into typed Python dictionaries.
Example input:
feature=search,enabled=true,rollout=25
Expected output:
{
"feature": "search",
"enabled": True,
"rollout": 25,
}

Generate the parser

The following example sends a prompt to Kimi 2.7 through CoreWeave Inference (Serverless). The request is wrapped in a weave.op, allowing Weave to automatically capture the prompt, response, token usage, and latency.
import os import weave from dotenv import dotenv_values from openai import OpenAI config = dotenv_values(".env") os.environ["WANDB_API_KEY"] = config["WANDB_API_KEY"] weave.init(config["WANDB_PROJECT"]) weave.integrations.patch_openai() client = OpenAI( base_url="https://api.inference.wandb.ai/v1", api_key=config["WANDB_API_KEY"], ) prompt = """ Write a Python function named parse_feature_flag_config. Input format: feature=search,enabled=true,rollout=25 Requirements: - Return a dictionary - Convert true/false to booleans - Convert integer values to integers - Raise ValueError for malformed key-value pairs - Output only Python code """ # Traced with W&B Weave @weave.op() def generate_code(user_prompt): response = client.chat.completions.create( model="moonshotai/Kimi-K2.7-Code", messages=[ {"role": "user", "content": user_prompt} ], ) return response.choices[0].message.content generated_code = generate_code(prompt) print(generated_code)
After the request completes, open the corresponding Weave trace and inspect:
  • The prompt sent to the model
  • The generated code
  • Input and output token usage
  • Request latency

Expected outcome


Kimi 2.7 generates a working parser and the request is automatically logged in Weave. We'll use the same tracing workflow throughout the rest of the guide as the tasks become more complex.
Image by author

Step 3: Generate production-style code

Next, move from a small utility function to executable code with real behavior to test. Ask Kimi 2.7 to generate a sliding-window rate limiter.
prompt = """ Write a Python class named SlidingWindowRateLimiter. Requirements: - Constructor accepts max_requests and window_seconds. - Method allow(user_id, timestamp) returns True or False. - Allow at most max_requests per user inside the time window. - Expire old requests outside the window. - Keep state separate for each user. - Output only Python code. """ generated_code = generate_code(prompt) print(generated_code)
Save the generated code as rateLimiter.py, then import it into the notebook and run a few validation tests.
@weave.op() def run_tests(): tests = [ test_allows_normal_traffic, test_blocks_burst_traffic, test_expires_old_requests, test_tracks_users_separately, ] results = [] for test in tests: try: test() except AssertionError: results.append((test.__name__, "FAIL")) except Exception as error: results.append( (test.__name__, f"ERROR: {type(error).__name__}") ) else: results.append((test.__name__, "PASS")) return results results = run_tests() for name, status in results: print(f"{status}: {name}")
Image by author
Image by author

Step 4: Debug a repository using long context

Now we move from single-file generation to repository-level debugging. The sample project is an authentication service with login, permissions, token handling, audit logs, notifications, and password reset logic.
Most tests pass, but two password reset tests fail: 2 failed, 11 passed
That makes this a useful long-context task. Kimi 2.7 needs to inspect several files, connect the failing tests to the password reset flow, and identify the root cause without changing unrelated login behavior.

Collect the project context

from pathlib import Path import subprocess PROJECT_ROOT = Path("auth_debug_demo") FILES_TO_INCLUDE = [ "app/settings.py", "app/models.py", "app/db.py", "app/auth.py", "app/permissions.py", "app/roles.py", "app/tokens.py", "app/password_reset.py", "app/audit.py", "app/notifications.py", "tests/test_password_reset.py", ] def read_project_files(root, files): sections = [] for file_path in files: path = root / file_path sections.append( f"\n\n### {file_path}\n```python\n{path.read_text(encoding='utf-8')}\n```" ) return "".join(sections) project_context = read_project_files(PROJECT_ROOT, FILES_TO_INCLUDE) print(f"Loaded {len(FILES_TO_INCLUDE)} files ({len(project_context):,} characters).") result = subprocess.run( ["py", "-m", "pytest", "auth_debug_demo/tests", "-q"], capture_output=True, text=True, ) pytest_output = result.stdout + "\n" + result.stderr print(pytest_output)

Ask Kimi 2.7 to debug the project

debug_prompt = f""" You are debugging a Python authentication project. Most tests pass, but the password reset tests fail. Find the root causes and propose a minimal, business-correct fix for both success and failure paths. Treat tests as evidence, not the specification; flag any expectation that conflicts with the intended behavior. Return: 1. The root cause 2. The affected files 3. The minimal fix 4. Why other authentication tests still pass 5. Which tests should pass or be updated after the fix Repository context: {project_context} Pytest output: {pytest_output} """ @weave.op() def debug_repository(user_prompt): response = client.chat.completions.create( model="moonshotai/Kimi-K2.7-Code", messages=[ {"role": "user", "content": user_prompt} ], ) return response.choices[0].message.content debug_report = debug_repository(debug_prompt) print(debug_report)

Expected outcome

Kimi 2.7 should identify the password reset failure across multiple files. A strong answer should explain why the reset token is rejected, why token state changes incorrectly after a failed password update, and which files need minimal changes.
The Weave trace should show the full project context, failing test output, model response, token usage, and latency.
Image by author
Image by author

Step 5: Simulate an agentic repository workflow

In Step 4, Kimi 2.7 received selected project files in one long prompt. That tested long-context debugging. Here, we make the workflow more agentic: the model can inspect files, run tests, edit existing files, rerun the suite, and return a final report.
The sample issue remains the password reset failure, but the repository now includes additional account-security and billing modules. Those files are intentional distractors. A useful coding agent should focus on the reset flow and avoid unrelated changes.

Define the issue

github_issue = """ You are a repository debugging agent. Run the full tests before the first write and preserve that baseline in your report. Inspect relevant files; do not guess or make unrelated improvements. Apply the smallest business-correct fix, including failure paths. Tests are evidence, not the specification: never weaken them to hide a defect, and justify any test change. Do not stop while a known correctness issue remains in the affected workflow; a green suite alone is insufficient. Resolve risks that contradict correct outcomes or failure semantics, and cover them with tests before finishing. After editing, run the full tests again. Base the final report on every write_file result and include the baseline, all changed files, final results, and remaining risks. Issue: Password reset links are rejected as invalid or expired. Some users also report that after a failed reset attempt, the reset token disappears and cannot be reused. Constraints: - Login behavior must remain unchanged. - Permissions must remain unchanged. - Billing must remain unchanged. - Account-security behavior must remain unchanged. """

Run the tool-enabled agent

The agent loop lets Kimi 2.7 request tools, execute them locally, and receive the results back as tool messages. The tools used here are list_files, read_file, run_tests, and write_file.
import json TOOL_FUNCTIONS = { "list_files": list_files, "read_file": read_file, "run_tests": run_tests, "write_file": write_file, } @weave.op() def debug_with_tools(issue, max_steps=20): messages = [{"role": "user", "content": issue}] for _ in range(max_steps): response = client.chat.completions.create( model="moonshotai/Kimi-K2.7-Code", messages=messages, tools=tools, ) message = response.choices[0].message messages.append(message.model_dump(exclude_none=True)) if not message.tool_calls: return message.content for tool_call in message.tool_calls: name = tool_call.function.name function = TOOL_FUNCTIONS.get(name) if function is None: result = {"error": f"Unknown tool: {name}"} else: try: arguments = json.loads(tool_call.function.arguments or "{}") result = function(**arguments) except Exception as error: result = { "error": type(error).__name__, "message": str(error), } messages.append({ "role": "tool", "tool_call_id": tool_call.id, "content": json.dumps(result), }) raise RuntimeError(f"Agent exceeded {max_steps} tool-call steps") agent_report = debug_with_tools(github_issue) print(agent_report)

Agent Outcome

The agent started by preserving the baseline:
21 passed, 2 failed
It then identified two production issues:
  • app/tokens.py validated reset tokens with the legacy signing secret.
  • app/password_reset.py deleted reset tokens before password persistence succeeded.
The model changed:
  • app/tokens.py
  • app/password_reset.py
  • tests/test_password_reset.py
It also confirmed that login, permissions, billing, and account-security behavior remained unchanged.
Image by author
Image by author

Agent evaluation findings

As part of the repository debugging workflow, we also evaluated how well the agent handled a realistic software engineering task. Beyond generating a patch, the goal was to investigate the correct files, preserve business behavior, validate the changes, and produce an accurate final report.
During the initial evaluation, the prompt focused too heavily on making the failing tests pass. In several runs, the model:
  • Weakened tests to obtain a green test suite.
  • Preserved incorrect business behavior.
  • Stopped despite unresolved correctness issues.
  • Produced reports that did not match the files it modified.
To address these issues, we strengthened the prompt with additional guardrails:
  • Treat tests as evidence, not the specification.
  • Do not weaken tests to hide defects.
  • Prioritize correct business behavior, including failure paths.
  • Run tests before and after editing.
  • Base the final report on the actual files that were modified.
With these guardrails in place, the agent consistently produced better results. It preserved the original baseline, fixed both production defects, verified the retry behavior, accurately reported every modified file, and finished with 23 genuinely passing tests.

Step 6: Refactor an existing project

With the password reset workflow fixed and the test suite back to 23 passing tests, we can evaluate another common engineering task: refactoring.
Instead of fixing bugs, Kimi 2.7 is asked to improve the implementation of app/password_reset.py and app/tokens.py while preserving behavior.
refactor_prompt = """ Refactor auth_debug_demo to improve maintainability without changing behavior. Use the available tools to inspect the code and run the full test suite before and after editing; preserve the 23-passing-test baseline. Modify only app/password_reset.py and app/tokens.py. You may extract helpers, add type hints, improve names, and make other appropriate refactors within that scope. Keep public APIs unchanged and do not modify tests. Report the changes, tools used, and final test results. """ refactor_report = debug_with_tools(refactor_prompt) print(refactor_report)
In this run, Kimi 2.7 extracted repeated validation and token-handling logic, added type hints, improved naming consistency, and reduced duplication across the password reset workflow.
The repository snapshots showed changes only in:
  • app/password_reset.py
  • app/tokens.py
The final test result remained unchanged: 23 passed
This demonstrates a different capability from debugging or agentic repair. The model was able to improve maintainability while preserving the existing behavior and API surface.
Image by author

Step 7: Build and run a software engineering evaluation suite

The previous sections evaluated Kimi 2.7 one task at a time. To make those results repeatable, we converted them into a small software-engineering benchmark and ran the same workload against both Kimi 2.6 and Kimi 2.7 Code using Weave Evaluations.
The suite contains four tasks:
Image by author
Each task was executed three times per model, resulting in 24 evaluation runs.
To keep the comparison fair, repository-based tasks use frozen fixtures. The debugging task always receives the same buggy repository context, while the refactoring task starts from a fresh copy of a fixed repository with 23 passing tests. This ensures that one run cannot affect the next.
We evaluated the benchmark with Weave Evaluations, which records scorer outputs, pass rates, latency, token usage, and per-example results for each benchmark run.

Run the evaluation:

The following code builds the benchmark dataset, defines the evaluation model and scorer, and runs the benchmark using Weave Evaluations.
from __future__ import annotations

import asyncio
import concurrent.futures
import traceback
from typing import Any

import weave

from evaluation_config import EVALUATION_VERSION, MODELS
from evaluation_suite import (
benchmark_examples,
call_kimi,
evaluate_refactoring,
init_tracking,
judge_debugging_answer,
print_summary,
rows_from_evaluation_result,
score_code_answer,
summarize,
)


def run_async(coro: Any) -> Any:
try:
asyncio.get_running_loop()
except RuntimeError:
return asyncio.run(coro)

with concurrent.futures.ThreadPoolExecutor(max_workers=1) as executor:
return executor.submit(asyncio.run, coro).result()


def build_dataset() -> weave.Dataset:
return weave.Dataset(
name=f"kimi_software_engineering_benchmark_v{EVALUATION_VERSION}",
rows=benchmark_examples(),
)


class KimiBenchmarkModel(weave.Model):
model_name: str
model_id: str

@weave.op()
def predict(
self,
task_name: str,
task_type: str,
prompt: str | None,
run_number: int,
target: dict[str, Any] | None = None,
id: str | None = None,
) -> dict[str, Any]:
del target, id
try:
if task_type == "refactoring":
return evaluate_refactoring(self.model_name, self.model_id, run_number)
if prompt is None:
raise ValueError(f"task {task_name} has no prompt")

response = call_kimi(self.model_id, prompt)
score = (
score_code_answer(task_name, response["text"])
if task_type == "code"
else judge_debugging_answer(response["text"])
)
return {
"model": self.model_name,
"model_id": self.model_id,
"task": task_name,
"run": run_number,
"passed": bool(score["passed"]),
"score": score,
"input_tokens": response["input_tokens"],
"output_tokens": response["output_tokens"],
"total_tokens": response["total_tokens"],
"latency_seconds": response["latency_seconds"],
"output": response["text"],
}
except Exception as error:
return {
"model": self.model_name,
"model_id": self.model_id,
"task": task_name,
"run": run_number,
"passed": False,
"error": {
"type": type(error).__name__,
"message": str(error),
"traceback": traceback.format_exc(),
},
}


@weave.op()
def benchmark_scorer(target: dict[str, Any], output: dict[str, Any]) -> dict[str, Any]:
task_type = target["task_type"]
result = {
"passed": bool(output.get("passed")),
"pass_rate": int(bool(output.get("passed"))),
"task_name": target["task_name"],
"task_type": task_type,
"latency_seconds": output.get("latency_seconds"),
"input_tokens": output.get("input_tokens"),
"output_tokens": output.get("output_tokens"),
"total_tokens": output.get("total_tokens"),
}

if output.get("error"):
result["error_type"] = output["error"].get("type")
if task_type == "debugging" and isinstance(output.get("score"), dict):
result["debugging_score"] = output["score"].get("score")
result["debugging_max_score"] = output["score"].get("max_score")
if task_type == "refactoring":
result["agent_steps"] = output.get("agent_steps")
judge = output.get("judge", {})
guards = output.get("guards", {})
if isinstance(judge, dict):
result["refactoring_score"] = judge.get("refactoring_score")
result["refactoring_approved"] = judge.get("approved_normalized")
if isinstance(guards, dict):
result["automatic_guards_passed"] = guards.get("automatic_guards_passed")
return result


def build_evaluation(dataset: weave.Dataset) -> weave.Evaluation:
return weave.Evaluation(
name=f"kimi_software_engineering_eval_v{EVALUATION_VERSION}",
dataset=dataset,
scorers=[benchmark_scorer],
)


def run_weave_evaluation() -> list[dict[str, Any]]:
init_tracking()
evaluation = build_evaluation(build_dataset())
rows = []

for model_name, model_id in MODELS.items():
model = KimiBenchmarkModel(model_name=model_name, model_id=model_id)
result = run_async(evaluation.evaluate(model))
rows.extend(rows_from_evaluation_result(result))
return rows


if __name__ == "__main__":
print_summary(summarize(run_weave_evaluation()))

While this tutorial uses a small evaluation suite designed to demonstrate the evaluation workflow rather than serve as a comprehensive benchmark, it provides a repeatable way to compare model behavior across the same engineering tasks.
Kimi 2.7 Code completed all 12 benchmark evaluations successfully, while Kimi 2.6 passed 11 of 12. The only difference occurred in the repository refactoring task, where Kimi 2.7 Code passed all three runs, and Kimi 2.6 passed two of three.
Image by author
Image by author
Kimi 2.7 Code was also consistently faster and more token-efficient across the evaluated tasks. On the repository debugging workload, average latency dropped from 220.6 seconds to 23.4 seconds, while average token usage decreased from approximately 15.1K tokens to 6.9K.

Repository debugging trace - Kimi 2.6:


Image by author

Repository debugging trace - Kimi 2.7 Code:


Image by author
For the same repository debugging workload, Kimi 2.7 Code completed the task with 7,741 total tokens and 27.3 seconds of latency, compared to 18,790 tokens and 285.8 seconds for Kimi 2.6.

Visualize the benchmark results

The following code logs an interactive W&B chart summarizing the average latency for each benchmark task.
import wandb
from weave_evaluation import run_weave_evaluation
from collections import defaultdict

rows = run_weave_evaluation()

labels = {
"feature_flag_parser": "Parser",
"rate_limiter": "Rate Limiter",
"repo_debugging": "Repo Debugging",
"repo_refactoring": "Repo Refactoring",
}

groups = defaultdict(list)
for r in rows:
if r.get("latency_seconds") is not None:
groups[(r["task"], r["model"])].append(r["latency_seconds"])

table = wandb.Table(
columns=["Task / Model", "Latency"],
data=[
[f"{labels[t]} | {m}", sum(groups[(t, m)]) / len(groups[(t, m)])]
for t in labels
for m in ["Kimi 2.6", "Kimi 2.7 Code"]
if groups[(t, m)]
],
)

wandb.log({
"latency_by_task_chart": wandb.plot.bar(
table, "Task / Model", "Latency",
title="Average Latency by Model and Task"
)
})


Note: The Kimi 2.6 repository refactoring latency is averaged over two successful runs because one evaluation ended with an API timeout.
The benchmark provides a traceable and repeatable workflow for comparing model versions on realistic software-engineering tasks. Rather than relying on isolated prompt examples, the same methodology can be reused to evaluate future model releases under consistent conditions.

Conclusion

In this guide, we connected Kimi 2.7 Code to CoreWeave Inference (Serverless) and explored its capabilities through progressively more complex software-engineering tasks. Starting with simple code generation, we moved to executable implementations, repository debugging, agentic workflows, refactoring, and finally a small evaluation suite comparing Kimi 2.6 and Kimi 2.7 Code.
Along the way, Weave captured traces, latency, token usage, tool calls, and evaluation results for every step, making it easier to understand how the model behaved as task complexity increased.
You now have everything needed to start building with Kimi 2.7 on CoreWeave Inference (Serverless), from simple code-generation tasks to repository-scale engineering workflows.