LangChain · Agent
Connect LangChain to Tikway: ChatOpenAI and an Agent tool loop
Last updated:
Use LangChain’s ChatOpenAI to connect a Python application to Tikway, then test tool calling separately from plain text generation. The model requests a tool; your application executes it and returns the result. This tutorial uses a local integer addition function so that you can inspect each step without connecting a search service or accessing business data.
1. Choose a model that supports tool calling
Open the model catalog and choose a text model with OpenAI protocol, Chat Completions, and Function Calling / tool support. Copy the full model ID. A successful text response alone does not establish tool compatibility.
Create a Tikway API Key in the console. Set the Base URL to https://api.tikway.ai/v1; the client appends /chat/completions. Do not put the complete endpoint in the Base URL, or use the website’s business /api path for model inference.
Install the integration in your own Python virtual environment:
python -m pip install -U langchain-openai
Set environment variables in the terminal that will run the script. Bash / macOS / Linux / WSL:
export TIKWAY_API_KEY='your Tikway API Key'
export TIKWAY_MODEL='the full model ID from the catalog'
Windows PowerShell:
$env:TIKWAY_API_KEY = 'your Tikway API Key'
$env:TIKWAY_MODEL = 'the full model ID from the catalog'
2. Test a plain text request first
Save this as langchain_chat.py. Running it sends a real model request and incurs the applicable API charges. This guide provides documented configuration and checks; it does not claim an end-to-end test with your account or selected model.
import os
from langchain_openai import ChatOpenAI
llm = ChatOpenAI(
model=os.environ["TIKWAY_MODEL"],
api_key=os.environ["TIKWAY_API_KEY"],
base_url="https://api.tikway.ai/v1",
use_responses_api=False,
timeout=60,
max_retries=0,
)
response = llm.invoke("Reply only with OK")
print(response.content)
print(response.usage_metadata)
python langchain_chat.py
use_responses_api=False explicitly selects Chat Completions. OpenAI built-in web search, code execution, and remote MCP are separate tool and endpoint features; do not assume that switching this Base URL enables them.
3. Add a local tool with a predictable result
After text generation works, save the following as langchain_agent.py. The loop makes at most three model requests, disables automatic retries, and stops on an unknown tool or invalid arguments. It does not execute arbitrary code generated by a model.
import os
from langchain_core.messages import HumanMessage, ToolMessage
from langchain_core.tools import tool
from langchain_openai import ChatOpenAI
@tool
def add_numbers(a: int, b: int) -> int:
"""Add two integers and return their sum."""
return a + b
llm = ChatOpenAI(
model=os.environ["TIKWAY_MODEL"],
api_key=os.environ["TIKWAY_API_KEY"],
base_url="https://api.tikway.ai/v1",
use_responses_api=False,
timeout=60,
max_retries=0,
)
agent = llm.bind_tools([add_numbers])
messages = [HumanMessage(content="Use the add_numbers tool to calculate 17 + 25, then report the result.")]
tool_seen = False
for step in range(3):
answer = agent.invoke(messages)
messages.append(answer)
print("step:", step + 1, "usage:", answer.usage_metadata)
if not answer.tool_calls:
print(answer.content)
if not tool_seen:
raise RuntimeError("The model did not request a tool; tool calling was not verified")
break
for call in answer.tool_calls:
if call["name"] != add_numbers.name:
raise RuntimeError("The model requested a tool that is not allowed")
result = add_numbers.invoke(call["args"])
tool_seen = True
print("tool:", call["name"], "args:", call["args"], "result:", result)
messages.append(ToolMessage(content=str(result), tool_call_id=call["id"]))
else:
raise RuntimeError("The tool loop has not finished after three requests")
python langchain_agent.py
Inspect the tool name add_numbers, arguments 17 and 25, local result 42, and the final answer after the result is returned. A model saying “42” without a recorded tool call is not proof of tool execution. Preserve the tool_call_id pairing and return the result as a ToolMessage after its assistant message.
4. Troubleshoot the connection
| Symptom | Check first |
|---|---|
| 401 | Tikway Key, whitespace, and the active terminal’s variables; see the 401 guide |
| 404 or an HTML response | The actual /v1/chat/completions URL; repeated /v1 or the website /api path |
Text works but tools fails |
Selected model and route support, then tool schema |
| No tool call | Inspect tool_calls, model capabilities, the tool description, and the task prompt |
| A tool call never finishes | Local function exceptions, argument validation, tool_call_id, message ordering, and loop limits |
| Streaming fails | Establish non-streaming tool behavior first; see the SSE guide |
Validate third-party tools, MCP connections, and more complex LangGraph workflows separately. A local function working does not establish compatibility with every Agent feature.
5. Estimate the cost of the entire Agent task
An Agent task can make several model requests. Tool definitions, conversation history, and tool results increase subsequent input; generated responses add output tokens. Use the token cost calculator for a per-request estimate, then reconcile actual requests, usage, and console records. A single chat request’s price is not the total price of a multi-step task.
Next: Agent API setup and model selection · Dify with Tikway · n8n AI Agent with Tikway · model and billing checks
Reference: LangChain ChatOpenAI documentation. These examples use its custom Base URL, bind_tools, and tool message interfaces. Parameter support can differ by integration version and model.