Protocol Compatibility Is the Key: Integrating Domestic LLMs with AI Coding Tools
This article explains how to connect Chinese domestic large language models (LLMs) to mainstream AI-powered coding tools by building a protocol conversion layer. It compares the structural differences between Anthropic-style and OpenAI-style APIs, discusses why generic adapters often fail, and provides practical guidance on request mapping, streaming responses, tool-call translation, error handling, and implementation tips for a reliable integration.
Protocol Compatibility Is the Key: Integrating Domestic LLMs with AI Coding Tools
1. Background: When AI Coding Tools Meet Domestic LLMs
Over the past year, AI-powered coding tools have become indispensable assistants for many developers. These tools leverage sophisticated context engineering—understanding project structure, coordinating multi-file edits, orchestrating terminal commands—to significantly boost coding efficiency. However, a practical obstacle remains: mainstream coding tools typically default to their bundled closed-source model services, which often come with high costs, strict account registration requirements, and aggressive risk-control policies.
Meanwhile, the domestic LLM ecosystem is maturing rapidly. Several Chinese models have demonstrated impressive performance in code generation and logical reasoning, and some platforms offer free daily quota, making them highly attractive for individual developers and small teams.
This naturally raises a question: Can we plug domestic model APIs into mainstream coding tools to combine a superior interactive experience with manageable costs?
The answer is yes—but only if you understand a critical fact: the protocol is the substance.
2. Root Cause: Incompatibility Between Two API Protocols
To grasp the challenge, we must first recognize that different AI model providers use different API protocol specifications.
Two dominant styles exist in the industry:
- Anthropic-style protocol: Unique designs for request paths, message structures, system prompt delivery, and tool-use formats. Mainstream coding tools typically communicate with backend models using this style.
- OpenAI-style protocol: Centered around a
messagesarray, withroledistinguishing system/user/assistant messages, and tool calls handled via thefunction callingmechanism. Most Chinese model platforms (including public APIs of domestic LLMs) adopt this style.
Key differences include:
| Dimension | Anthropic Style | OpenAI Style |
|---|---|---|
| Request path | /v1/messages |
/v1/chat/completions |
| System prompt | Standalone system field |
A message with role: system inside messages |
| Tool call format | tool_use / tool_result content blocks |
function_call / tool_calls fields |
| Streaming response | Event-driven (content_block_delta, etc.) |
data: {...} chunks |
| Multi-turn organization | Array of content blocks | Array of messages |
This means the request format emitted by a coding tool and the format expected by a domestic model API are structurally misaligned. Without conversion, requests cannot be parsed correctly, let alone work reliably.
3. A Detour: The Limitations of “Universal Adapters”
Facing these protocol differences, a natural approach is to look for an existing “generic adapter layer”—an open-source solution that claims to connect any model to any tool. Such solutions usually run as a local proxy, intercepting requests from the tool, converting them to a format the target model understands, and forwarding them.
This sounds promising, but practical use reveals frequent issues:
- Incomplete protocol coverage: Some adapters only implement basic text-dialog conversion and lack proper support for tool calls, streaming responses, and multi-turn context management. When the coding tool triggers a tool-call flow, the adapter may return malformed responses or timeout.
- Version drift risk: Coding tools iterate rapidly, and their API protocol details may change with each release. Relying on a third-party adapter ties your stability to their update cadence.
- High debugging overhead: When a request fails, error messages are often obfuscated by multiple forwarding layers. Troubleshooting requires locating the issue across the tool, the adapter, and the model—extremely inefficient.
- Hidden missing features: Some adapters oversimplify for “compatibility,” causing certain model capabilities (e.g., parallel tool calls, structured output) to never be triggered.
In my own experience, an initial open-source adapter handled simple dialogs well, but failed frequently on file read/write operations. Examining the logs revealed that the adapter mishandled the return format of tool-call results, so the coding tool could not parse the model’s operation instructions. After days of tinkering, I realized: the problem was not whether the adapter was “good,” but that pinning hopes on “universal” was a misjudgment.
4. Back to Basics: Understand the Protocol and Do Targeted Conversion
After abandoning the “universal adapter” illusion, the correct path becomes clear: You don’t need a generic layer that handles every scenario; you need a focused conversion layer that precisely understands both ends’ protocols and performs direct mapping.
Specifically, the following core conversions are required:
4.1 Request Structure Mapping
Coding tools emit requests in the Anthropic style, with a system field, a messages array (where content can be a string or an array of content blocks), and tools definitions. The conversion layer must:
- Extract the
systemfield into an OpenAI-style message withrole: "system"and insert it at the beginning of themessagesarray. - Convert
textblocks within content block arrays into a concatenated string, andtool_useblocks intotool_callsformat. - Transform tool definitions from Anthropic’s
input_schemato OpenAI’sparametersformat.
4.2 Streaming Response Adaptation
Coding tools typically expect streaming responses for real-time display. Anthropic’s streaming uses event-driven types (e.g., message_start, content_block_delta, message_stop), while OpenAI’s style returns data: lines chunk by chunk. The conversion layer must parse the former’s event stream and reassemble it into the latter’s format while preserving semantics.
4.3 Bidirectional Tool-Call Translation
This is the most error-prone part. Coding tools rely on the model’s returned tool-call instructions to execute file operations, terminal commands, etc. The conversion layer must:
- Convert OpenAI-style response
tool_callsfields into Anthropic-styletool_usecontent blocks. - Convert Anthropic-style
tool_resultcontent blocks in subsequent requests into OpenAI-stylerole: "tool"messages.
Below is a simplified pseudo-code example of the conversion logic:
def convert_anthropic_to_openai(anthropic_req):openai_messages = []# system promptif "system" in anthropic_req:openai_messages.append({"role": "system", "content": anthropic_req["system"]})# messagesfor msg in anthropic_req["messages"]:if isinstance(msg["content"], str):openai_messages.append({"role": msg["role"], "content": msg["content"]})else:# content blocks -> flattentext_parts = []tool_calls = []for block in msg["content"]:if block["type"] == "text":text_parts.append(block["text"])elif block["type"] == "tool_use":tool_calls.append({"id": block["id"],"type": "function","function": {"name": block["name"],"arguments": json.dumps(block["input"])}})elif block["type"] == "tool_result":openai_messages.append({"role": "tool","tool_call_id": block["tool_use_id"],"content": block["content"]})if text_parts or tool_calls:m = {"role": msg["role"]}if text_parts:m["content"] = "\n".join(text_parts)if tool_calls:m["tool_calls"] = tool_callsopenai_messages.append(m)return {"messages": openai_messages, "model": anthropic_req.get("model")}
The code above only illustrates the logic. A production implementation must also handle streaming responses, error-code mapping, token counting, and other details.
4.4 Error Handling and Retry Strategy
Different providers use different error-code systems. The conversion layer should map upstream model errors (e.g., rate limiting, timeouts, parameter errors) into formats that the coding tool understands, while incorporating sensible retry and backoff strategies to avoid session interruptions caused by transient errors.
5. Practical Recommendations
When implementing the approach above, pay special attention to the following:
First, prioritize the core path. Don’t aim for 100% protocol coverage from the start. Ensure that text dialog, single-turn tool calls, and streaming output work first, then gradually add multi-turn tool calls, parallel calls, and other complex scenarios.
Second, invest in logging and observability. Record full request/response logs (with sensitive data redacted) at the conversion layer to quickly identify whether an issue originates from the tool, the conversion layer, or the model. Log levels should be dynamically adjustable to avoid excessive noise in production.
Third, choose models that match the task type. Different domestic models have varying strengths in code generation, long-context understanding, and instruction following. Select the most suitable model based on the actual use case (e.g., code completion, refactoring suggestions, error diagnosis) rather than blindly chasing the “most powerful”.
Fourth, watch context window and token limits. A core advantage of coding tools is their ability to handle large project contexts, which demands a sufficiently large context window from the model. Verify the actual usable context length of the target model and implement truncation or summarization strategies in the conversion layer to prevent failures from oversized requests.
Fifth, keep the conversion layer lightweight and maintainable. The conversion logic should be concise and testable. Encapsulate the core protocol conversion into an independent module, covered by unit tests for critical paths, to minimize rework when the tool updates its API.
6. Conclusion
Looking back at the whole process, the biggest takeaway is not a specific configuration trick but a conceptual shift: when integrating heterogeneous systems, “universal” solutions are often illusionary; understanding the protocols and performing precise, targeted adaptation is the reliable path.
The experience advantage of AI coding tools and the cost advantage of domestic models can coexist—provided you are willing to invest time in understanding the structural differences between the two ends and build a focused, controllable conversion layer. The technical barrier is not high, but it requires patience and attention to detail—and that is precisely the most valuable part of the journey from zero to one.
