Your AI isn’t truly smart until it can Google, query SQL, and flip through your PDFs. Let’s change that. Today we’ll explore how to make your LangChain-powered .NET apps capable of interacting with external systems like REST APIs, databases, and files. This is where AI becomes useful, not just clever.
Why External Data Access Matters
You might have a fine-tuned LLM, a great prompt strategy, and chains that dance. But without access to real-time external data, your AI can’t:
- Answer company-specific questions
- Act on real-world updates (like stock prices, CRM records)
- Retrieve documents, invoices, or files for users
- Store context in a persistent database
LangChain for .NET allows you to create tools and agents that can perform real-world tasks, not just answer trivia. Let’s break it down.
API Integration Tool: Connect to RESTful Endpoints
LangChain’s Tool
abstraction makes it simple to create reusable HTTP clients.
public class WeatherApiTool : Tool
{
public override string Name => "weather_api";
public override string Description => "Fetches current weather info for a given city.";
public override async Task<string> Run(string input)
{
var client = new HttpClient();
client.DefaultRequestHeaders.UserAgent.ParseAdd("LangChainClient/1.0");
var response = await client.GetAsync($"https://api.weatherapi.com/v1/current.json?key=API_KEY&q={input}");
var content = await response.Content.ReadAsStringAsync();
return content;
}
}
Explanation:
Name
andDescription
are used by the agent to understand and select this tool.Run
makes an HTTP GET request and returns the response body.- We set a
User-Agent
to comply with API requirements.
Additional Example: Currency Exchange Tool
public class ExchangeRateTool : Tool
{
public override string Name => "exchange_rate";
public override string Description => "Gets the exchange rate between two currencies.";
public override async Task<string> Run(string input)
{
var currencies = input.Split(" to ");
if (currencies.Length != 2) return "Use format: 'USD to EUR'";
var client = new HttpClient();
var url = $"https://api.exchangerate.host/convert?from={currencies[0]}&to={currencies[1]}";
var response = await client.GetAsync(url);
return await response.Content.ReadAsStringAsync();
}
}
This can be triggered by prompts like “Convert 100 USD to EUR”.
Database Interaction: Generate and Execute SQL
Let’s say you have a SQL Server database and want your AI to query it dynamically:
public class SqlQueryTool : Tool
{
public override string Name => "sql_tool";
public override string Description => "Executes SQL queries against the employee database.";
public override async Task<string> Run(string input)
{
using var connection = new SqlConnection("YourConnectionStringHere");
await connection.OpenAsync();
var command = new SqlCommand(input, connection);
var reader = await command.ExecuteReaderAsync();
var output = new StringBuilder();
while (await reader.ReadAsync())
{
for (int i = 0; i < reader.FieldCount; i++)
{
output.Append(reader[i].ToString() + (i < reader.FieldCount - 1 ? ", " : "\n"));
}
}
return output.ToString();
}
}
Explanation: This tool directly executes SQL queries and returns tabular data as text.
Safer Alternative: Parameterized Queries
public class DepartmentLookupTool : Tool
{
public override string Name => "employee_lookup";
public override string Description => "Looks up employees by department.";
public override async Task<string> Run(string input)
{
using var connection = new SqlConnection("YourConnectionStringHere");
await connection.OpenAsync();
var command = new SqlCommand("SELECT Name FROM Employees WHERE Department = @dept", connection);
command.Parameters.AddWithValue("@dept", input);
var reader = await command.ExecuteReaderAsync();
var result = new List<string>();
while (await reader.ReadAsync())
{
result.Add(reader["Name"].ToString());
}
return string.Join(", ", result);
}
}
This prevents SQL injection and simplifies LLM tool usage.
Working with Files and Documents: RAG-like Access
Need to summarize PDF contracts or extract insights from text files? Create tools for file parsing and chunking.
public class FileReaderTool : Tool
{
public override string Name => "file_reader";
public override string Description => "Reads content from a text file given its path.";
public override async Task<string> Run(string input)
{
if (!File.Exists(input)) return "File not found.";
return await File.ReadAllTextAsync(input);
}
}
Extended Example: Read PDF Files
public class PdfExtractorTool : Tool
{
public override string Name => "pdf_extractor";
public override string Description => "Extracts text from PDF documents.";
public override Task<string> Run(string input)
{
using var reader = new PdfReader(input);
var text = new StringBuilder();
for (int i = 1; i <= reader.NumberOfPages; i++)
{
text.Append(PdfTextExtractor.GetTextFromPage(reader, i));
}
return Task.FromResult(text.ToString());
}
}
This is ideal for building a document chatbot that understands uploaded forms, contracts, or manuals.
Use Case Example: AI-Powered Internal Knowledge Assistant
Let’s put this together:
- The WeatherApiTool fetches current weather
- The ExchangeRateTool converts currencies on-the-fly
- The SqlQueryTool or DepartmentLookupTool fetches employee data
- The PdfExtractorTool summarizes onboarding guides
Wrap them with an AgentExecutor
, and LangChain routes tasks like:
“What’s the weather in NYC, convert 500 USD to EUR, and list new HR hires from April?”
LangChain breaks this into API calls and SQL queries, then merges the outputs into a cohesive response:
Result:
“Weather in NYC: Sunny, 72°F. 500 USD = 460 EUR. New HR hires: Alice Carter, Bob Lim. Onboarding guide summary: …”
You now have a digital assistant that blends real-time data, structured enterprise records, and document insights seamlessly.
FAQ: Real-World LangChain Integrations
Yes. Modify the HttpClient
to add Authorization headers or use OAuth where necessary.
Definitely. You can parse JSON responses and use LangChain’s formatting or embed it in prompts.
Absolutely. If your app can connect via ADO.NET or EF Core, LangChain can access it too.
You can sandbox file operations and use background services for large document processing.
Use parallel calls and cache common queries for optimal performance.
Conclusion: Your AI Can Finally Reach the Real World
Think your AI is smart? Wait until it connects with your APIs, taps into your databases, and flips through your PDFs like a pro. That’s the leap from chatbot to enterprise assistant—and LangChain makes it surprisingly easy.
Start turning your LLM ideas into powerful, connected applications. Try building a real-world tool today, and show your AI what it means to really understand your data.
If this inspired you or helped in your development, leave a comment, share your tools, or explore the rest of this LangChain for .NET series for even more integration power! your LLM ideas into powerful, connected applications. Try building a real-world tool today, and show your AI what it means to really understand your data.